context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Text;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* this SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Lucene.Net.Util.Automaton
{
/// <summary>
/// Construction of basic automata.
///
/// @lucene.experimental
/// </summary>
public sealed class BasicAutomata
{
private BasicAutomata()
{
}
/// <summary>
/// Returns a new (deterministic) automaton with the empty language.
/// </summary>
public static Automaton MakeEmpty()
{
Automaton a = new Automaton();
State s = new State();
a.Initial = s;
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts only the empty string.
/// </summary>
public static Automaton MakeEmptyString()
{
Automaton a = new Automaton();
a.singleton = "";
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts all strings.
/// </summary>
public static Automaton MakeAnyString()
{
Automaton a = new Automaton();
State s = new State();
a.Initial = s;
s.accept = true;
s.AddTransition(new Transition(Character.MIN_CODE_POINT, Character.MAX_CODE_POINT, s));
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts any single codepoint.
/// </summary>
public static Automaton MakeAnyChar()
{
return MakeCharRange(Character.MIN_CODE_POINT, Character.MAX_CODE_POINT);
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts a single codepoint of
/// the given value.
/// </summary>
public static Automaton MakeChar(int c)
{
Automaton a = new Automaton();
a.singleton = new string(Character.ToChars(c));
a.deterministic = true;
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts a single codepoint whose
/// value is in the given interval (including both end points).
/// </summary>
public static Automaton MakeCharRange(int min, int max)
{
if (min == max)
{
return MakeChar(min);
}
Automaton a = new Automaton();
State s1 = new State();
State s2 = new State();
a.Initial = s1;
s2.accept = true;
if (min <= max)
{
s1.AddTransition(new Transition(min, max, s2));
}
a.deterministic = true;
return a;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of length
/// x.substring(n).length().
/// </summary>
private static State AnyOfRightLength(string x, int n)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
s.AddTransition(new Transition('0', '9', AnyOfRightLength(x, n + 1)));
}
return s;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of value at least
/// x.substring(n) and length x.substring(n).length().
/// </summary>
private static State AtLeast(string x, int n, ICollection<State> initials, bool zeros)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
if (zeros)
{
initials.Add(s);
}
char c = x[n];
s.AddTransition(new Transition(c, AtLeast(x, n + 1, initials, zeros && c == '0')));
if (c < '9')
{
s.AddTransition(new Transition((char)(c + 1), '9', AnyOfRightLength(x, n + 1)));
}
}
return s;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of value at most
/// x.substring(n) and length x.substring(n).length().
/// </summary>
private static State AtMost(string x, int n)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
char c = x[n];
s.AddTransition(new Transition(c, AtMost(x, (char)n + 1)));
if (c > '0')
{
s.AddTransition(new Transition('0', (char)(c - 1), AnyOfRightLength(x, n + 1)));
}
}
return s;
}
/// <summary>
/// Constructs sub-automaton corresponding to decimal numbers of value between
/// x.substring(n) and y.substring(n) and of length x.substring(n).length()
/// (which must be equal to y.substring(n).length()).
/// </summary>
private static State Between(string x, string y, int n, ICollection<State> initials, bool zeros)
{
State s = new State();
if (x.Length == n)
{
s.Accept = true;
}
else
{
if (zeros)
{
initials.Add(s);
}
char cx = x[n];
char cy = y[n];
if (cx == cy)
{
s.AddTransition(new Transition(cx, Between(x, y, n + 1, initials, zeros && cx == '0')));
}
else // cx<cy
{
s.AddTransition(new Transition(cx, AtLeast(x, n + 1, initials, zeros && cx == '0')));
s.AddTransition(new Transition(cy, AtMost(y, n + 1)));
if (cx + 1 < cy)
{
s.AddTransition(new Transition((char)(cx + 1), (char)(cy - 1), AnyOfRightLength(x, n + 1)));
}
}
}
return s;
}
/// <summary>
/// Returns a new automaton that accepts strings representing decimal
/// non-negative integers in the given interval.
/// </summary>
/// <param name="min"> minimal value of interval </param>
/// <param name="max"> maximal value of interval (both end points are included in the
/// interval) </param>
/// <param name="digits"> if >0, use fixed number of digits (strings must be prefixed
/// by 0's to obtain the right length) - otherwise, the number of
/// digits is not fixed </param>
/// <exception cref="IllegalArgumentException"> if min>max or if numbers in the
/// interval cannot be expressed with the given fixed number of
/// digits </exception>
public static Automaton MakeInterval(int min, int max, int digits)
{
Automaton a = new Automaton();
string x = Convert.ToString(min);
string y = Convert.ToString(max);
if (min > max || (digits > 0 && y.Length > digits))
{
throw new System.ArgumentException();
}
int d;
if (digits > 0)
{
d = digits;
}
else
{
d = y.Length;
}
StringBuilder bx = new StringBuilder();
for (int i = x.Length; i < d; i++)
{
bx.Append('0');
}
bx.Append(x);
x = bx.ToString();
StringBuilder by = new StringBuilder();
for (int i = y.Length; i < d; i++)
{
by.Append('0');
}
by.Append(y);
y = by.ToString();
ICollection<State> initials = new List<State>();
a.Initial = Between(x, y, 0, initials, digits <= 0);
if (digits <= 0)
{
List<StatePair> pairs = new List<StatePair>();
foreach (State p in initials)
{
if (a.Initial != p)
{
pairs.Add(new StatePair(a.Initial, p));
}
}
BasicOperations.AddEpsilons(a, pairs);
a.Initial.AddTransition(new Transition('0', a.Initial));
a.deterministic = false;
}
else
{
a.deterministic = true;
}
a.CheckMinimizeAlways();
return a;
}
/// <summary>
/// Returns a new (deterministic) automaton that accepts the single given
/// string.
/// </summary>
public static Automaton MakeString(string s)
{
Automaton a = new Automaton();
a.singleton = s;
a.deterministic = true;
return a;
}
public static Automaton MakeString(int[] word, int offset, int length)
{
Automaton a = new Automaton();
a.Deterministic = true;
State s = new State();
a.Initial = s;
for (int i = offset; i < offset + length; i++)
{
State s2 = new State();
s.AddTransition(new Transition(word[i], s2));
s = s2;
}
s.accept = true;
return a;
}
/// <summary>
/// Returns a new (deterministic and minimal) automaton that accepts the union
/// of the given collection of <seealso cref="BytesRef"/>s representing UTF-8 encoded
/// strings.
/// </summary>
/// <param name="utf8Strings">
/// The input strings, UTF-8 encoded. The collection must be in sorted
/// order.
/// </param>
/// <returns> An <seealso cref="Automaton"/> accepting all input strings. The resulting
/// automaton is codepoint based (full unicode codepoints on
/// transitions). </returns>
public static Automaton MakeStringUnion(ICollection<BytesRef> utf8Strings)
{
if (utf8Strings.Count == 0)
{
return MakeEmpty();
}
else
{
return DaciukMihovAutomatonBuilder.Build(utf8Strings);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.Devices.Common
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Azure.Devices.Common.WebApi;
using Microsoft.Owin;
public delegate bool TryParse<TInput, TOutput>(TInput input, bool ignoreCase, out TOutput output);
public static class CommonExtensionMethods
{
const char ValuePairDelimiter = ';';
const char ValuePairSeparator = '=';
public static string EnsureEndsWith(this string value, char suffix)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
var length = value.Length;
if (length == 0)
{
return suffix.ToString();
}
else if (value[length - 1] == suffix)
{
return value;
}
else
{
return value + suffix;
}
}
public static string EnsureStartsWith(this string value, char prefix)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Length == 0)
{
return prefix.ToString();
}
else
{
return value[0] == prefix ? value : prefix + value;
}
}
public static string GetValueOrDefault(this IDictionary<string, string> map, string keyName)
{
string value;
if (!map.TryGetValue(keyName, out value))
{
value = null;
}
return value;
}
public static IDictionary<string, string> ToDictionary(this string valuePairString, char kvpDelimiter, char kvpSeparator)
{
if (string.IsNullOrWhiteSpace(valuePairString))
{
throw new ArgumentException("Malformed Token");
}
IEnumerable<string[]> parts = valuePairString.Split(kvpDelimiter).
Select((part) => part.Split(new char[] { kvpSeparator }, 2));
if (parts.Any((part) => part.Length != 2))
{
throw new FormatException("Malformed Token");
}
IDictionary<string, string> map = parts.ToDictionary((kvp) => kvp[0], (kvp) => kvp[1], StringComparer.OrdinalIgnoreCase);
return map;
}
public static bool TryGetIotHubName(this HttpRequestMessage requestMessage, out string iotHubName)
{
object iotHubNameObj = null;
iotHubName = null;
// IotHubMessageHandler sets the request message property with IotHubName read from hostname
if (!requestMessage.Properties.TryGetValue(CustomHeaderConstants.HttpIotHubName, out iotHubNameObj) ||
!(iotHubNameObj is string))
{
return false;
}
iotHubName = (string)iotHubNameObj; ;
return true;
}
public static string GetIotHubNameFromHostName(this HttpRequestMessage requestMessage)
{
// {IotHubname}.[env-specific-sub-domain.]IotHub[-int].net
//
string[] hostNameParts = requestMessage.RequestUri.Host.Split('.');
if (hostNameParts.Length < 3)
{
throw new ArgumentException("Invalid request URI");
}
return hostNameParts[0];
}
public static string GetIotHubName(this HttpRequestMessage requestMessage)
{
string iotHubName;
if (!TryGetIotHubName(requestMessage, out iotHubName))
{
throw new ArgumentException("Invalid request URI");
}
return iotHubName;
}
public static string GetMaskedClientIpAddress(this HttpRequestMessage requestMessage)
{
// note that this only works if we are hosted as an OWIN app
if (requestMessage.Properties.ContainsKey("MS_OwinContext"))
{
OwinContext owinContext = requestMessage.Properties["MS_OwinContext"] as OwinContext;
if (owinContext != null)
{
string remoteIpAddress = owinContext.Request.RemoteIpAddress;
string maskedRemoteIpAddress = string.Empty;
IPAddress remoteIp = null;
IPAddress.TryParse(remoteIpAddress, out remoteIp);
if (null != remoteIp)
{
byte[] addressBytes = remoteIp.GetAddressBytes();
if (remoteIp.AddressFamily == AddressFamily.InterNetwork)
{
addressBytes[addressBytes.Length - 1] = 0xFF;
addressBytes[addressBytes.Length - 2] = 0xFF;
maskedRemoteIpAddress = new IPAddress(addressBytes).ToString();
}
else if (remoteIp.AddressFamily == AddressFamily.InterNetworkV6)
{
addressBytes[addressBytes.Length - 1] = 0xFF;
addressBytes[addressBytes.Length - 2] = 0xFF;
addressBytes[addressBytes.Length - 3] = 0xFF;
addressBytes[addressBytes.Length - 4] = 0xFF;
maskedRemoteIpAddress = new IPAddress(addressBytes).ToString();
}
}
return maskedRemoteIpAddress;
}
}
return null;
}
public static void AppendKeyValuePairIfNotEmpty(this StringBuilder builder, string name, object value)
{
if (value != null)
{
builder.Append(name);
builder.Append(ValuePairSeparator);
builder.Append(value);
builder.Append(ValuePairDelimiter);
}
}
public static bool IsNullOrWhiteSpace(this string value)
{
return string.IsNullOrWhiteSpace(value);
}
public static string RemoveWhitespace(this string value)
{
return new string(value.Where(c => !char.IsWhiteSpace(c)).ToArray());
}
}
}
| |
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using V1=AssetBundleGraph;
using Model=UnityEngine.AssetGraph.DataModel.Version2;
namespace UnityEngine.AssetGraph {
[CustomNode("Create Assets/Create Prefab From Group", 50)]
public class PrefabBuilder : Node, Model.NodeDataImporter {
public enum OutputOption : int {
CreateInCacheDirectory,
CreateInSelectedDirectory
}
[SerializeField] private SerializableMultiTargetInstance m_instance;
[SerializeField] private UnityEditor.ReplacePrefabOptions m_replacePrefabOptions = UnityEditor.ReplacePrefabOptions.Default;
[SerializeField] private SerializableMultiTargetString m_outputDir;
[SerializeField] private SerializableMultiTargetInt m_outputOption;
public static readonly string kCacheDirName = "Prefabs";
public UnityEditor.ReplacePrefabOptions Options {
get {
return m_replacePrefabOptions;
}
}
public SerializableMultiTargetInstance Builder {
get {
return m_instance;
}
}
public override string ActiveStyle {
get {
return "node 4 on";
}
}
public override string InactiveStyle {
get {
return "node 4";
}
}
public override string Category {
get {
return "Create";
}
}
public override void Initialize(Model.NodeData data) {
m_instance = new SerializableMultiTargetInstance();
m_outputDir = new SerializableMultiTargetString();
m_outputOption = new SerializableMultiTargetInt((int)OutputOption.CreateInCacheDirectory);
data.AddDefaultInputPoint();
data.AddDefaultOutputPoint();
}
public void Import(V1.NodeData v1, Model.NodeData v2) {
m_instance = new SerializableMultiTargetInstance(v1.ScriptClassName, v1.InstanceData);
m_replacePrefabOptions = v1.ReplacePrefabOptions;
m_outputDir = new SerializableMultiTargetString();
m_outputOption = new SerializableMultiTargetInt((int)OutputOption.CreateInCacheDirectory);
}
public override Node Clone(Model.NodeData newData) {
var newNode = new PrefabBuilder();
newNode.m_instance = new SerializableMultiTargetInstance(m_instance);
newNode.m_replacePrefabOptions = m_replacePrefabOptions;
newNode.m_outputDir = new SerializableMultiTargetString(m_outputDir);
newNode.m_outputOption = new SerializableMultiTargetInt(m_outputOption);
newData.AddDefaultInputPoint();
newData.AddDefaultOutputPoint();
return newNode;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) {
EditorGUILayout.HelpBox("Create Prefab From Group: Create prefab from incoming group of assets, using assigned script.", MessageType.Info);
editor.UpdateNodeName(node);
var builder = m_instance.Get<IPrefabBuilder>(editor.CurrentEditingGroup);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
var map = PrefabBuilderUtility.GetAttributeAssemblyQualifiedNameMap();
if(map.Count > 0) {
using(new GUILayout.HorizontalScope()) {
GUILayout.Label("PrefabBuilder");
var guiName = PrefabBuilderUtility.GetPrefabBuilderGUIName(m_instance.ClassName);
if (GUILayout.Button(guiName, "Popup", GUILayout.MinWidth(150f))) {
var builders = map.Keys.ToList();
if(builders.Count > 0) {
NodeGUI.ShowTypeNamesMenu(guiName, builders, (string selectedGUIName) =>
{
using(new RecordUndoScope("Change PrefabBuilder class", node, true)) {
builder = PrefabBuilderUtility.CreatePrefabBuilder(selectedGUIName);
m_instance.Set(editor.CurrentEditingGroup, builder);
onValueChanged();
}
}
);
}
}
MonoScript s = TypeUtility.LoadMonoScript(m_instance.ClassName);
using(new EditorGUI.DisabledScope(s == null)) {
if(GUILayout.Button("Edit", GUILayout.Width(50))) {
AssetDatabase.OpenAsset(s, 0);
}
}
}
ReplacePrefabOptions opt = (ReplacePrefabOptions)EditorGUILayout.EnumPopup("Prefab Replace Option", m_replacePrefabOptions, GUILayout.MinWidth(150f));
if(m_replacePrefabOptions != opt) {
using(new RecordUndoScope("Change Prefab Replace Option", node, true)) {
m_replacePrefabOptions = opt;
onValueChanged();
}
opt = m_replacePrefabOptions;
}
} else {
if(!string.IsNullOrEmpty(m_instance.ClassName)) {
EditorGUILayout.HelpBox(
string.Format(
"Your PrefabBuilder script {0} is missing from assembly. Did you delete script?", m_instance.ClassName), MessageType.Info);
} else {
string[] menuNames = Model.Settings.GUI_TEXT_MENU_GENERATE_PREFABBUILDER.Split('/');
EditorGUILayout.HelpBox(
string.Format(
"You need to create at least one PrefabBuilder script to use this node. To start, select {0}>{1}>{2} menu and create new script from template.",
menuNames[1],menuNames[2], menuNames[3]
), MessageType.Info);
}
}
GUILayout.Space(10f);
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope()) {
var disabledScope = editor.DrawOverrideTargetToggle(node, m_instance.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => {
if(enabled) {
m_instance.CopyDefaultValueTo(editor.CurrentEditingGroup);
m_outputDir[editor.CurrentEditingGroup] = m_outputDir.DefaultValue;
m_outputOption[editor.CurrentEditingGroup] = m_outputOption.DefaultValue;
} else {
m_instance.Remove(editor.CurrentEditingGroup);
m_outputDir.Remove(editor.CurrentEditingGroup);
m_outputOption.Remove(editor.CurrentEditingGroup);
}
onValueChanged();
});
using (disabledScope) {
OutputOption opt = (OutputOption)m_outputOption[editor.CurrentEditingGroup];
var newOption = (OutputOption)EditorGUILayout.EnumPopup("Output Option", opt);
if(newOption != opt) {
using(new RecordUndoScope("Change Output Option", node, true)){
m_outputOption[editor.CurrentEditingGroup] = (int)newOption;
onValueChanged();
}
opt = newOption;
}
using (new EditorGUI.DisabledScope (opt == OutputOption.CreateInCacheDirectory)) {
var newDirPath = editor.DrawFolderSelector ("Output Directory", "Select Output Folder",
m_outputDir[editor.CurrentEditingGroup],
Application.dataPath,
(string folderSelected) => {
string basePath = Application.dataPath;
if(basePath == folderSelected) {
folderSelected = string.Empty;
} else {
var index = folderSelected.IndexOf(basePath);
if(index >= 0 ) {
folderSelected = folderSelected.Substring(basePath.Length + index);
if(folderSelected.IndexOf('/') == 0) {
folderSelected = folderSelected.Substring(1);
}
}
}
return folderSelected;
}
);
if (newDirPath != m_outputDir[editor.CurrentEditingGroup]) {
using(new RecordUndoScope("Change Output Directory", node, true)){
m_outputDir[editor.CurrentEditingGroup] = newDirPath;
onValueChanged();
}
}
var dirPath = Path.Combine (Application.dataPath, m_outputDir [editor.CurrentEditingGroup]);
if (opt == OutputOption.CreateInSelectedDirectory &&
!string.IsNullOrEmpty(m_outputDir [editor.CurrentEditingGroup]) &&
!Directory.Exists (dirPath))
{
using (new EditorGUILayout.HorizontalScope()) {
EditorGUILayout.LabelField(m_outputDir[editor.CurrentEditingGroup] + " does not exist.");
if(GUILayout.Button("Create directory")) {
Directory.CreateDirectory(dirPath);
AssetDatabase.Refresh ();
}
}
EditorGUILayout.Space();
string parentDir = Path.GetDirectoryName(m_outputDir[editor.CurrentEditingGroup]);
if(Directory.Exists(parentDir)) {
EditorGUILayout.LabelField("Available Directories:");
string[] dirs = Directory.GetDirectories(parentDir);
foreach(string s in dirs) {
EditorGUILayout.LabelField(s);
}
}
EditorGUILayout.Space();
}
var outputDir = PrepareOutputDirectory (BuildTargetUtility.GroupToTarget(editor.CurrentEditingGroup), node.Data);
using (new EditorGUI.DisabledScope (!Directory.Exists (outputDir)))
{
using (new EditorGUILayout.HorizontalScope ()) {
GUILayout.FlexibleSpace ();
if (GUILayout.Button ("Highlight in Project Window", GUILayout.Width (180f))) {
var folder = AssetDatabase.LoadMainAssetAtPath (outputDir);
EditorGUIUtility.PingObject (folder);
}
}
}
}
GUILayout.Space (8f);
if (builder != null) {
Action onChangedAction = () => {
using(new RecordUndoScope("Change PrefabBuilder Setting", node)) {
m_instance.Set(editor.CurrentEditingGroup, builder);
onValueChanged();
}
};
builder.OnInspectorGUI(onChangedAction);
}
}
}
}
}
public override void OnContextMenuGUI(GenericMenu menu) {
MonoScript s = TypeUtility.LoadMonoScript(m_instance.ClassName);
if(s != null) {
menu.AddItem(
new GUIContent("Edit Script"),
false,
() => {
AssetDatabase.OpenAsset(s, 0);
}
);
}
}
public override void Prepare (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
ValidatePrefabBuilder(node, target, incoming,
() => {
throw new NodeException ("Output directory not found.", "Create output directory or set a valid directory path.", node);
},
() => {
throw new NodeException("PrefabBuilder is not configured.", "Configure PrefabBuilder from inspector.", node);
},
() => {
throw new NodeException("Failed to create PrefabBuilder from settings.", "Fix settings from inspector.", node);
},
(string groupKey) => {
throw new NodeException(string.Format("Can not create prefab with incoming assets for group {0}.", groupKey), "Fix group input assets for selected PrefabBuilder.",node);
},
(AssetReference badAsset) => {
throw new NodeException(string.Format("Can not import incoming asset {0}.", badAsset.fileNameAndExtension), "", node);
}
);
if(incoming == null) {
return;
}
var prefabOutputDir = PrepareOutputDirectory (target, node);
var builder = m_instance.Get<IPrefabBuilder>(target);
UnityEngine.Assertions.Assert.IsNotNull(builder);
Dictionary<string, List<AssetReference>> output = null;
if(Output != null) {
output = new Dictionary<string, List<AssetReference>>();
}
var aggregatedGroups = new Dictionary<string, List<AssetReference>>();
foreach(var ag in incoming) {
foreach(var key in ag.assetGroups.Keys) {
if(!aggregatedGroups.ContainsKey(key)){
aggregatedGroups[key] = new List<AssetReference>();
}
aggregatedGroups[key].AddRange(ag.assetGroups[key].AsEnumerable());
}
}
foreach(var key in aggregatedGroups.Keys) {
var assets = aggregatedGroups[key];
var threshold = PrefabBuilderUtility.GetPrefabBuilderAssetThreshold(m_instance.ClassName);
if( threshold < assets.Count ) {
var guiName = PrefabBuilderUtility.GetPrefabBuilderGUIName(m_instance.ClassName);
throw new NodeException(
string.Format("Too many assets passed to {0} for group:{1}. {2}'s threshold is set to {4}", guiName, key, guiName,threshold),
string.Format("Limit number of assets in a group to {4}", threshold), node);
}
GameObject previousPrefab = null; //TODO
List<UnityEngine.Object> allAssets = LoadAllAssets(assets);
var prefabFileName = builder.CanCreatePrefab(key, allAssets, previousPrefab);
if(output != null && prefabFileName != null) {
output[key] = new List<AssetReference> () {
AssetReferenceDatabase.GetPrefabReference(FileUtility.PathCombine(prefabOutputDir, prefabFileName + ".prefab"))
};
}
UnloadAllAssets(assets);
}
if(Output != null) {
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
Output(dst, output);
}
}
private static List<UnityEngine.Object> LoadAllAssets(List<AssetReference> assets) {
List<UnityEngine.Object> objects = new List<UnityEngine.Object>();
foreach(var a in assets) {
objects.AddRange(a.allData.AsEnumerable());
}
return objects;
}
private static void UnloadAllAssets(List<AssetReference> assets) {
assets.ForEach(a => a.ReleaseData());
}
public override void Build (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output,
Action<Model.NodeData, string, float> progressFunc)
{
if(incoming == null) {
return;
}
var builder = m_instance.Get<IPrefabBuilder>(target);
UnityEngine.Assertions.Assert.IsNotNull(builder);
var prefabOutputDir = PrepareOutputDirectory(target, node);
Dictionary<string, List<AssetReference>> output = null;
if(Output != null) {
output = new Dictionary<string, List<AssetReference>>();
}
var aggregatedGroups = new Dictionary<string, List<AssetReference>>();
foreach(var ag in incoming) {
foreach(var key in ag.assetGroups.Keys) {
if(!aggregatedGroups.ContainsKey(key)){
aggregatedGroups[key] = new List<AssetReference>();
}
aggregatedGroups[key].AddRange(ag.assetGroups[key].AsEnumerable());
}
}
var anyPrefabCreated = false;
foreach(var key in aggregatedGroups.Keys) {
var assets = aggregatedGroups[key];
var allAssets = LoadAllAssets(assets);
GameObject previousPrefab = null; //TODO
var prefabFileName = builder.CanCreatePrefab(key, allAssets, previousPrefab);
var prefabSavePath = FileUtility.PathCombine(prefabOutputDir, prefabFileName + ".prefab");
if (!Directory.Exists(Path.GetDirectoryName(prefabSavePath))) {
Directory.CreateDirectory(Path.GetDirectoryName(prefabSavePath));
}
if(!File.Exists(prefabSavePath) || PrefabBuildInfo.DoesPrefabNeedRebuilding(prefabOutputDir, this, node, target, key, assets)) {
UnityEngine.GameObject obj = builder.CreatePrefab(key, allAssets, previousPrefab);
if(obj == null) {
throw new AssetGraphException(string.Format("{0} :PrefabBuilder {1} returned null in CreatePrefab() [groupKey:{2}]",
node.Name, builder.GetType().FullName, key));
}
LogUtility.Logger.LogFormat(LogType.Log, "{0} is (re)creating Prefab:{1} with {2}({3})", node.Name, prefabFileName,
PrefabBuilderUtility.GetPrefabBuilderGUIName(m_instance.ClassName),
PrefabBuilderUtility.GetPrefabBuilderVersion(m_instance.ClassName));
if(progressFunc != null) progressFunc(node, string.Format("Creating {0}", prefabFileName), 0.5f);
PrefabUtility.CreatePrefab(prefabSavePath, obj, m_replacePrefabOptions);
PrefabBuildInfo.SavePrefabBuildInfo(prefabOutputDir, this, node, target, key, assets);
GameObject.DestroyImmediate(obj);
anyPrefabCreated = true;
AssetProcessEventRecord.GetRecord ().LogModify (AssetDatabase.AssetPathToGUID(prefabSavePath));
}
UnloadAllAssets(assets);
if (anyPrefabCreated) {
AssetDatabase.SaveAssets ();
}
if(output != null) {
output[key] = new List<AssetReference> () {
AssetReferenceDatabase.GetPrefabReference(prefabSavePath)
};
}
}
if(Output != null) {
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
Output(dst, output);
}
}
private void ValidatePrefabBuilder (
Model.NodeData node,
BuildTarget target,
IEnumerable<PerformGraph.AssetGroups> incoming,
Action folderDoesntExist,
Action noBuilderData,
Action failedToCreateBuilder,
Action<string> canNotCreatePrefab,
Action<AssetReference> canNotImportAsset
) {
var outputDir = PrepareOutputDirectory (target, node);
if (!Directory.Exists (outputDir)) {
folderDoesntExist ();
}
var builder = m_instance.Get<IPrefabBuilder>(target);
if(null == builder ) {
failedToCreateBuilder();
}
builder.OnValidate ();
if(null != builder && null != incoming) {
foreach(var ag in incoming) {
foreach(var key in ag.assetGroups.Keys) {
var assets = ag.assetGroups[key];
if(assets.Any()) {
bool isAllGoodAssets = true;
foreach(var a in assets) {
if(string.IsNullOrEmpty(a.importFrom)) {
canNotImportAsset(a);
isAllGoodAssets = false;
}
}
if(isAllGoodAssets) {
GameObject previousPrefab = null; //TODO
// do not call LoadAllAssets() unless all assets have importFrom
var al = ag.assetGroups[key];
List<UnityEngine.Object> allAssets = LoadAllAssets(al);
if(string.IsNullOrEmpty(builder.CanCreatePrefab(key, allAssets, previousPrefab))) {
canNotCreatePrefab(key);
}
UnloadAllAssets(al);
}
}
}
}
}
}
private string PrepareOutputDirectory(BuildTarget target, Model.NodeData node) {
var outputOption = (OutputOption)m_outputOption [target];
if(outputOption == OutputOption.CreateInCacheDirectory) {
return FileUtility.EnsureCacheDirExists (target, node, kCacheDirName);
}
return Path.Combine("Assets", m_outputDir [target]);
}
}
}
| |
using Xunit;
using System.IO;
using LanguageExt.Sys;
using LanguageExt.Sys.IO;
using LanguageExt.Sys.Test;
using System.Threading.Tasks;
using static LanguageExt.Prelude;
using File = LanguageExt.Sys.IO.File<LanguageExt.Sys.Test.Runtime>;
using Dir = LanguageExt.Sys.IO.Directory<LanguageExt.Sys.Test.Runtime>;
namespace LanguageExt.Tests
{
public class MemoryFSTests
{
[Fact]
public async Task Write_and_read_file()
{
var rt = Runtime.New();
var comp = from _ in File.writeAllText("C:\\test.txt", "Hello, World")
from t in File.readAllText("C:\\test.txt")
select t;
var r = await comp.Run(rt);
Assert.True(r == "Hello, World", FailMsg(r));
}
[Fact]
public async Task Write_to_non_existent_folder()
{
var rt = Runtime.New();
var comp = from _ in File.writeAllText("C:\\non-exist\\test.txt", "Hello, World")
from t in File.readAllText("C:\\non-exist\\test.txt")
select t;
var r = await comp.Run(rt);
Assert.True(r.IsFail);
}
[Fact]
public async Task Create_folder_write_and_read_file()
{
var rt = Runtime.New();
var comp = from _1 in Dir.create("C:\\non-exist\\")
from _2 in File.writeAllText("C:\\non-exist\\test.txt", "Hello, World")
from tx in File.readAllText("C:\\non-exist\\test.txt")
select tx;
var r = await comp.Run(rt);
Assert.True(r == "Hello, World", FailMsg(r));
}
[Fact]
public async Task Create_nested_folder_write_and_read_file()
{
var rt = Runtime.New();
var comp = from _1 in Dir.create("C:\\non-exist\\also-non-exist")
from _2 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.txt", "Hello, World")
from tx in File.readAllText("C:\\non-exist\\also-non-exist\\test.txt")
select tx;
var r = await comp.Run(rt);
Assert.True(r == "Hello, World", FailMsg(r));
}
[Fact]
public async Task Create_nested_folder_write_two_files_enumerate_one_of_them_using_star_pattern()
{
var rt = Runtime.New();
var comp = from _1 in Dir.create("C:\\non-exist\\also-non-exist")
from _2 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.txt", "Hello, World")
from _3 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.bat", "Goodbye, World")
from en in Dir.enumerateFiles("C:\\", "*.txt", SearchOption.AllDirectories)
from tx in File.readAllText(en.Head)
select (tx, en.Count);
var r = await comp.Run(rt);
Assert.True(r == ("Hello, World", 1), FailMsg(r));
}
[Fact]
public async Task Create_nested_folder_write_two_files_enumerate_one_of_them_using_qm_pattern()
{
var rt = Runtime.New();
var comp = from _1 in Dir.create("C:\\non-exist\\also-non-exist")
from _2 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.txt", "Hello, World")
from _3 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.bat", "Goodbye, World")
from en in Dir.enumerateFiles("C:\\", "????.txt", SearchOption.AllDirectories)
from tx in File.readAllText(en.Head)
select (tx, en.Count);
var r = await comp.Run(rt);
Assert.True(r == ("Hello, World", 1), FailMsg(r));
}
[Fact]
public async Task Create_nested_folder_write_two_files_enumerate_fail_using_singular_qm_pattern()
{
var rt = Runtime.New();
var comp = from _1 in Dir.create("C:\\non-exist\\also-non-exist")
from _2 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.txt", "Hello, World")
from _3 in File.writeAllText("C:\\non-exist\\also-non-exist\\test.bat", "Goodbye, World")
from en in Dir.enumerateFiles("C:\\", "?.txt", SearchOption.AllDirectories)
from tx in File.readAllText(en.Head)
select (tx, en.Count);
var r = await comp.Run(rt);
Assert.True(r.IsFail);
}
[Theory]
[InlineData("C:\\non-exist")]
[InlineData("C:\\non-exist\\also-non-exist")]
[InlineData("C:\\a\\b\\c\\d")]
public void Create_and_delete_folder(string path)
{
var rt = Runtime.New();
var comp = from p in SuccessEff(path)
from _1 in Dir.create(p)
from e1 in Dir.exists(p)
from _2 in Dir.delete(p)
from e2 in Dir.exists(p)
select (e1, e2);
var r = comp.Run(rt);
Assert.True(r == (true, false), FailMsg(r));
}
[Theory]
[InlineData("C:\\non-exist")]
[InlineData("C:\\non-exist\\also-non-exist")]
[InlineData("D:\\a\\b\\c\\d")]
public void Delete_non_existent_folder(string path)
{
var rt = Runtime.New();
var comp = from p in SuccessEff(path)
from _ in Dir.delete(p)
select unit;
var r = comp.Run(rt);
Assert.True(r.IsFail);
}
[Theory]
[InlineData("C:\\non-exist", "C:\\non-exist\\test.txt")]
[InlineData("C:\\non-exist\\also-non-exist", "C:\\non-exist\\also-non-exist\\test.txt")]
public async Task File_exists(string folder, string file)
{
var rt = Runtime.New();
var comp = from _1 in Dir.create(folder)
from _2 in File.writeAllText(file, "Hello, World")
from ex in File.exists(file)
select ex;
var r = await comp.Run(rt);
Assert.True(r == true, FailMsg(r));
}
[Theory]
[InlineData("C:\\non-exist\\test.txt")]
[InlineData("C:\\non-exist\\also-non-exist\\test.txt")]
[InlineData("X:\\non-exist\\also-non-exist\\test.txt")]
[InlineData("X:\\test.txt")]
public async Task File_doesnt_exist(string file)
{
var rt = Runtime.New();
var comp = from _2 in File.writeAllText(file, "Hello, World")
from ex in File.exists(file)
select ex;
var r = await comp.Run(rt);
Assert.True(r.IsFail);
}
[Theory]
[InlineData("C:\\a\\b\\c\\d", new[] {"C:\\a", "C:\\a\\b", "C:\\a\\b\\c", "C:\\a\\b\\c\\d", }, "*")]
[InlineData("C:\\a\\b\\c", new[] {"C:\\a", "C:\\a\\b", "C:\\a\\b\\c"}, "*")]
[InlineData("C:\\a\\b", new[] {"C:\\a", "C:\\a\\b"}, "*")]
[InlineData("C:\\a", new[] {"C:\\a"}, "*")]
[InlineData("C:\\and\\all\\the\\arrows", new[] {"C:\\and", "C:\\and\\all", "C:\\and\\all\\the\\arrows" }, "*a*")]
public void Enumerate_folders(string path, string[] folders, string pattern)
{
var rt = Runtime.New();
var comp = from _1 in Dir.create(path)
from ds in Dir.enumerateDirectories("C:\\", pattern, SearchOption.AllDirectories)
select ds.Strict();
var r = comp.Run(rt);
var dbg = ((Seq<string>)r).ToArray();
Assert.True(r == toSeq(folders));
}
[Theory]
[InlineData("C:\\a\\b", "C:\\c\\d", "test.txt")]
[InlineData("C:\\", "C:\\c\\d", "test.txt")]
public async Task Move_file_from_one_folder_to_another(string srcdir, string destdir, string file)
{
var rt = Runtime.New();
var comp = from _1 in Dir.create(srcdir)
from _2 in Dir.create(destdir)
from sf in SuccessEff(Path.Combine(srcdir, file))
from df in SuccessEff(Path.Combine(destdir, file))
from _3 in File.writeAllText(sf, "Hello, World")
from _4 in Dir.move(sf, df)
from tx in File.readAllText(df)
from ex in File.exists(sf)
select (ex, tx);
var r = await comp.Run(rt);
Assert.True(r == (false, "Hello, World"), FailMsg(r));
}
static string FailMsg<A>(Fin<A> ma) =>
ma.Match(Succ: _ => "", Fail: e => e.Message);
}
}
| |
using System;
using System.IO;
using System.Management.Automation;
namespace DD.CloudControl.Powershell
{
using Client;
using Client.Models;
/// <summary>
/// Factory methods for well-known <see cref="ErrorRecord"/>s.
/// </summary>
public static class Errors
{
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a connection already exists with the specified name.
/// </summary>
/// <param name="name">
/// The connection name.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord ConnectionExists(string name)
{
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("Connection name cannot be null, empty, or entirely composed of whitespace.", nameof(name));
return new ErrorRecord(
new Exception($"A connection named '{name}' already exists."),
errorId: "CloudControl.Connection.Exists",
errorCategory: ErrorCategory.ResourceExists,
targetObject: name
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when the ConnectionName parameter was not supplied to a Cmdlet and no default connection has been configured.
/// </summary>
/// <param name="cmdlet">
/// The calling Cmdlet.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord ConnectionRequired(PSCmdlet cmdlet)
{
if (cmdlet == null)
throw new ArgumentNullException(nameof(cmdlet));
return new ErrorRecord(
new Exception("The ConnectionName parameter was not specified and no default connection has been configured."),
errorId: "CloudControl.Connection.Required",
errorCategory: ErrorCategory.InvalidArgument,
targetObject: cmdlet.MyInvocation.MyCommand.Name
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a connection does exist with the specified name.
/// </summary>
/// <param name="name">
/// The connection name.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord ConnectionDoesNotExist(string name)
{
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("Connection name cannot be null, empty, or entirely composed of whitespace.", nameof(name));
return new ErrorRecord(
new Exception($"A connection named '{name}' does not exist."),
errorId: "CloudControl.Connection.DoesNotExist",
errorCategory: ErrorCategory.ObjectNotFound,
targetObject: name
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a resource was not found by Id.
/// </summary>
/// <typeparam name="TResource">
/// The type of resource that was not found.
/// </param>
/// <param name="resourceId">
/// The Id of the resource that was not found.
/// </param>
/// <param name="message">
/// An optional (custom) error message.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord ResourceNotFoundById<TResource>(Guid resourceId, string message = null)
{
return ResourceNotFoundById<TResource>(resourceId.ToString(), message);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a resource was not found by Id.
/// </summary>
/// <typeparam name="TResource">
/// The type of resource that was not found.
/// </param>
/// <param name="resourceId">
/// The Id of the resource that was not found.
/// </param>
/// <param name="message">
/// An optional (custom) error message.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord ResourceNotFoundById<TResource>(string resourceId, string message = null)
{
if (String.IsNullOrWhiteSpace(resourceId))
throw new ArgumentException("Resource Id cannot be null, empty, or entirely composed of whitespace.", nameof(resourceId));
Type resourceType = typeof(TResource);
string resourceTypeName = resourceType.Name;
string resourceTypeDescription = ResourceTypes.GetDescription(resourceType);
return new ErrorRecord(
new Exception(message ?? $"No {resourceTypeDescription} was found with Id '{resourceId}'."),
errorId: $"CloudControl.{resourceTypeName}.NotFound",
errorCategory: ErrorCategory.ObjectNotFound,
targetObject: resourceId
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a resource was not found with the specified name.
/// </summary>
/// <param name="resourceType">
/// The type of resource that was not found.
/// </param>
/// <param name="resourceName">
/// The name of the resource that was not found.
/// </param>
/// <param name="message">
/// An optional (custom) error message.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord ResourceNotFoundByName<TResource>(string resourceName, string message = null)
{
if (String.IsNullOrWhiteSpace(resourceName))
throw new ArgumentException("Resource name cannot be null, empty, or entirely composed of whitespace.", nameof(resourceName));
Type resourceType = typeof(TResource);
string resourceTypeName = resourceType.Name;
string resourceTypeDescription = ResourceTypes.GetDescription(resourceType);
return new ErrorRecord(
new Exception(message ?? $"No {resourceTypeDescription} named '{resourceName}' was found."),
errorId: $"CloudControl.{resourceTypeName}.NotFound",
errorCategory: ErrorCategory.ObjectNotFound,
targetObject: resourceName
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when an unrecognised parameter set is encountered by a Cmdlet.
/// </summary>
/// <param name="cmdlet">
/// The Cmdlet.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord UnrecognizedParameterSet(PSCmdlet cmdlet)
{
if (cmdlet == null)
throw new ArgumentNullException(nameof(cmdlet));
return new ErrorRecord(
new ArgumentException($"Unrecognised parameter-set: '{cmdlet.ParameterSetName}'."),
errorId: "UnrecognisedParameterSet",
errorCategory: ErrorCategory.InvalidArgument,
targetObject: cmdlet.ParameterSetName
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a Cmdlet (or part of its functionality) is not implemented.
/// </summary>
/// <param name="cmdlet">
/// A message or message format specifier describing what is not implemented (and why).
/// </param>
/// <param name="messageOrFormat">
/// An optional error message or message-format specifier.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="messageOrFormat"/> is <c>null</c>, empty, or entirely composed of whitespace.
/// </exception>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord NotImplemented(PSCmdlet cmdlet, string messageOrFormat = null, params object[] formatArguments)
{
if (cmdlet == null)
throw new ArgumentNullException(nameof(cmdlet));
string message;
if (String.IsNullOrWhiteSpace(messageOrFormat))
{
message = String.Format("Cmdlet not implemented: {0}.",
cmdlet.MyInvocation.MyCommand.Name
);
}
else
message = String.Format(messageOrFormat, formatArguments);
return new ErrorRecord(
new NotImplementedException(message),
errorId: "NotImplemented",
errorCategory: ErrorCategory.NotImplemented,
targetObject: null
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when requested functionality is not implemented.
/// </summary>
/// <param name="messageOrFormat">
/// A message or message format specifier describing what is not implemented (and why).
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="messageOrFormat"/> is <c>null</c>, empty, or entirely composed of whitespace.
/// </exception>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord NotImplemented(string messageOrFormat, params object[] formatArguments)
{
if (String.IsNullOrWhiteSpace(messageOrFormat))
throw new ArgumentException("Argument cannot be null, empty, or composed entirely of whitespace: 'messageOrFormat'.", nameof(messageOrFormat));
string message = String.Format(messageOrFormat, formatArguments);
return new ErrorRecord(
new NotImplementedException(message),
errorId: "NotImplemented",
errorCategory: ErrorCategory.NotImplemented,
targetObject: null
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a file was not found.
/// </summary>
/// <param name="file">
/// A <see cref="FileInfo"/> representing the file.
/// </param>
/// <param name="description">
/// A short description (sentence fragment) of the file that was not found.
/// </param>
/// <param name="errorCodePrefix">
/// An optional string to prepend to the error code.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord FileNotFound(FileInfo file, string description, string errorCodePrefix = "")
{
if (file == null)
throw new ArgumentNullException(nameof(file));
if (String.IsNullOrWhiteSpace(description))
throw new ArgumentException("Argument cannot be null, empty, or composed entirely of whitespace: 'description'.", nameof(description));
return new ErrorRecord(
new FileNotFoundException($"Cannot find {description} file '{file.FullName}'.",
fileName: file.FullName
),
errorId: errorCodePrefix + "FileNotFound",
errorCategory: ErrorCategory.ObjectNotFound,
targetObject: file
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> for when a Cmdlet has been passed an invalid parameter.
/// </summary>
/// <param name="cmdlet">
/// The calling Cmdlet.
/// </param>
/// <param name="parameterName">
/// The name of the invalid parameter.
/// </param>
/// <param name="messageOrFormat">
/// The error message or message-format specifier.
/// </param>
/// <param name="formatArguments">
/// Optional message format arguments.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord InvalidParameter(PSCmdlet cmdlet, string parameterName, string messageOrFormat, params object[] formatArguments)
{
if (cmdlet == null)
throw new ArgumentNullException(nameof(cmdlet));
if (String.IsNullOrWhiteSpace(parameterName))
throw new ArgumentException("Argument cannot be null, empty, or composed entirely of whitespace: 'parameterName'.", nameof(parameterName));
if (String.IsNullOrWhiteSpace(messageOrFormat))
throw new ArgumentException("Argument cannot be null, empty, or composed entirely of whitespace: 'messageOrFormat'.", nameof(messageOrFormat));
return new ErrorRecord(
new ArgumentException(String.Format(messageOrFormat, formatArguments)),
errorId: "DD.CloudControl.InvalidParameter",
errorCategory: ErrorCategory.InvalidArgument,
targetObject: cmdlet.MyInvocation.MyCommand.Name
);
}
/// <summary>
/// Create an <see cref="ErrorRecord"/> representing an error from the CloudControl API.
/// </summary>
/// <param name="client">
/// The CloudControl API client.
/// </param>
/// <param name="apiResponse">
/// The API response from CloudControl.
/// </param>
/// <returns>
/// The configured <see cref="ErrorRecord"/>.
/// </returns>
public static ErrorRecord CloudControlApi(CloudControlClient client, ApiResponseV2 apiResponse)
{
if (client == null)
throw new ArgumentNullException(nameof(client));
if (apiResponse == null)
throw new ArgumentNullException(nameof(apiResponse));
return new ErrorRecord(
exception: CloudControlException.FromApiV2Response(apiResponse, statusCode: 0),
errorId: $"CloudControl.API.{apiResponse.ResponseCode}",
errorCategory: ErrorCategory.NotSpecified,
targetObject: client.BaseAddress?.AbsoluteUri ?? "Unknown"
);
}
}
}
| |
using System;
using UnityEditor;
using UMA.ReorderableList;
using System.Collections.Generic;
using UnityEngine;
[CustomPropertyDrawer(typeof(UMACrowdRandomSet.CrowdRaceData))]
public class CrowdRaceDataEditor : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
var innerEntriesProp = prop.FindPropertyRelative("slotElements");
return ReorderableListGUI.CalculateListFieldHeight(innerEntriesProp) + 20;
}
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
var height = position.height;
var race = prop.FindPropertyRelative("raceID");
position.height = 18;
EditorGUI.PropertyField(position, race);
position.y += 20;
position.height = height - 20;
var innerEntriesProp = prop.FindPropertyRelative("slotElements");
ReorderableListGUI.ListFieldAbsolute(position, innerEntriesProp, ReorderableListFlags.DisableReordering);
}
}
[CustomPropertyDrawer(typeof(UMACrowdRandomSet.CrowdSlotElement))]
public class CrowdSlotElementEditor : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
var innerEntriesProp = prop.FindPropertyRelative("possibleSlots");
return ReorderableListGUI.CalculateListFieldHeight(innerEntriesProp) + 45;
}
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
var height = position.height;
position.height = 18;
var requirement = prop.FindPropertyRelative("requirement");
EditorGUI.PropertyField(position, requirement);
position.y += 22;
EditorGUI.LabelField(position, "Possible slots", LabelHelper.HeaderStyle);
position.y += 18;
position.height = height - 45;
var possibleSlots = prop.FindPropertyRelative("possibleSlots");
//ReorderableListGUI.Title("Possible Slots");
ReorderableListGUI.ListFieldAbsolute(position, possibleSlots, (pos) =>
{
pos.height = 20;
EditorGUI.LabelField(pos, "No slots");
}, ReorderableListFlags.DisableReordering);
}
}
[CustomPropertyDrawer(typeof(UMACrowdRandomSet.CrowdSlotData))]
public class CrowdSlotDataEditor : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
var innerEntriesProp = prop.FindPropertyRelative("overlayElements");
return ReorderableListGUI.CalculateListFieldHeight(innerEntriesProp) + 65;
}
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
var height = position.height;
position.height = 18;
var requirement = prop.FindPropertyRelative("slotID");
EditorGUI.PropertyField(position, requirement);
position.y += 20;
var overlayListSource = prop.FindPropertyRelative("overlayListSource");
EditorGUI.PropertyField(position, overlayListSource);
position.y += 20;
EditorGUI.LabelField(position, "Possible overlays", LabelHelper.HeaderStyle);
position.y += 18;
position.height = height - 65;
var innerEntriesProp = prop.FindPropertyRelative("overlayElements");
ReorderableListGUI.ListFieldAbsolute(position, innerEntriesProp, ReorderableListFlags.DisableReordering);
}
}
[CustomPropertyDrawer(typeof(UMACrowdRandomSet.CrowdOverlayElement))]
public class OuterListEntryEditor : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
var innerEntriesProp = prop.FindPropertyRelative("possibleOverlays");
return ReorderableListGUI.CalculateListFieldHeight(innerEntriesProp) + 25;
}
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
var height = position.height;
var innerEntriesProp = prop.FindPropertyRelative("possibleOverlays");
position.y += 5;
position.height = 18;
EditorGUI.LabelField(position, "Overlay Data", LabelHelper.HeaderStyle);
position.y += 18;
position.height = height - 25;
ReorderableListGUI.ListFieldAbsolute(position, innerEntriesProp, ReorderableListFlags.DisableReordering);
}
}
[CustomPropertyDrawer(typeof(UMACrowdRandomSet.CrowdOverlayData))]
public class InnerListEntryEditor : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty prop, GUIContent label)
{
var overlayType = prop.FindPropertyRelative("overlayType");
float size = 40f;
CleanProperty(overlayType, prop);
switch ((UMACrowdRandomSet.OverlayType)overlayType.enumValueIndex)
{
case UMACrowdRandomSet.OverlayType.Color:
size += 40f;
break;
case UMACrowdRandomSet.OverlayType.Texture:
size += 0;
break;
case UMACrowdRandomSet.OverlayType.Hair:
size += 40;
break;
case UMACrowdRandomSet.OverlayType.Skin:
size += 60;
break;
case UMACrowdRandomSet.OverlayType.Random:
size += 60;
break;
}
var colorChannelUse = prop.FindPropertyRelative("colorChannelUse");
if (colorChannelUse.enumValueIndex != 0)
{
size += 20f;
}
return size;
}
public static void CleanProperty(SerializedProperty overlayType, SerializedProperty prop)
{
if ((UMACrowdRandomSet.OverlayType)overlayType.enumValueIndex == UMACrowdRandomSet.OverlayType.Unknown)
{
var useSkinColor = prop.FindPropertyRelative("useSkinColor");
var useHairColor = prop.FindPropertyRelative("useHairColor");
var minRGB = prop.FindPropertyRelative("minRGB");
var maxRGB = prop.FindPropertyRelative("maxRGB");
if (useSkinColor.boolValue)
{
overlayType.enumValueIndex = (int)UMACrowdRandomSet.OverlayType.Skin;
}
else if (useHairColor.boolValue)
{
overlayType.enumValueIndex = (int)UMACrowdRandomSet.OverlayType.Hair;
}
else
{
if (minRGB.colorValue == maxRGB.colorValue)
{
if (minRGB.colorValue == Color.white)
{
overlayType.enumValueIndex = (int)UMACrowdRandomSet.OverlayType.Texture;
}
else
{
overlayType.enumValueIndex = (int)UMACrowdRandomSet.OverlayType.Color;
}
}
else
{
overlayType.enumValueIndex = (int)UMACrowdRandomSet.OverlayType.Random;
}
}
}
}
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label)
{
var width = position.width;
var x = position.x;
var labelWidth = 90;
position.height = 16;
var overlayId = prop.FindPropertyRelative("overlayID");
EditorGUI.LabelField(position, "Id");
position.width = labelWidth;
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
overlayId.stringValue = EditorGUI.TextField(position, overlayId.stringValue);
position.y += 20;
position.x = x;
position.width = labelWidth;
var overlayType = prop.FindPropertyRelative("overlayType");
EditorGUI.LabelField(position, "Type");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
overlayType.enumValueIndex =
(int)(UMACrowdRandomSet.OverlayType)EditorGUI.EnumPopup(
position,
(UMACrowdRandomSet.OverlayType)Enum.Parse(typeof(UMACrowdRandomSet.OverlayType), overlayType.enumNames[overlayType.enumValueIndex]));
var overlayTypeEnum = (UMACrowdRandomSet.OverlayType)overlayType.enumValueIndex;
switch (overlayTypeEnum)
{
case UMACrowdRandomSet.OverlayType.Color:
{
position.y += 20;
position.x = x;
position.width = labelWidth;
var minRGB = prop.FindPropertyRelative("minRGB");
EditorGUI.LabelField(position, "Color");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
minRGB.colorValue = EditorGUI.ColorField(position, minRGB.colorValue);
break;
}
case UMACrowdRandomSet.OverlayType.Texture:
{
break;
}
case UMACrowdRandomSet.OverlayType.Hair:
{
position.y += 20;
position.x = x;
position.width = labelWidth;
var hairColorMultiplier = prop.FindPropertyRelative("hairColorMultiplier");
EditorGUI.LabelField(position, "Hair Mult.");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
hairColorMultiplier.floatValue = EditorGUI.FloatField(position, hairColorMultiplier.floatValue);
break;
}
case UMACrowdRandomSet.OverlayType.Skin:
{
position.y += 20;
position.x = x;
position.width = labelWidth;
var minRGB = prop.FindPropertyRelative("minRGB");
EditorGUI.LabelField(position, "Add Min RGB");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
minRGB.colorValue = EditorGUI.ColorField(position, minRGB.colorValue);
position.y += 20;
position.x = x;
position.width = labelWidth;
var maxRGB = prop.FindPropertyRelative("maxRGB");
EditorGUI.LabelField(position, "Add Max RGB");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
maxRGB.colorValue = EditorGUI.ColorField(position, maxRGB.colorValue);
break;
}
case UMACrowdRandomSet.OverlayType.Random:
{
position.y += 20;
position.x = x;
position.width = labelWidth;
var minRGB = prop.FindPropertyRelative("minRGB");
EditorGUI.LabelField(position, "Min RGB");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
minRGB.colorValue = EditorGUI.ColorField(position, minRGB.colorValue);
position.y += 20;
position.x = x;
position.width = labelWidth;
var maxRGB = prop.FindPropertyRelative("maxRGB");
EditorGUI.LabelField(position, "Max RGB");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
maxRGB.colorValue = EditorGUI.ColorField(position, maxRGB.colorValue);
break;
}
}
if (overlayTypeEnum != UMACrowdRandomSet.OverlayType.Texture)
{
position.y += 20;
position.x = x;
position.width = labelWidth;
var colorChannelUse = prop.FindPropertyRelative("colorChannelUse");
EditorGUI.LabelField(position, "Extra Channel");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
colorChannelUse.enumValueIndex =
(int)(UMACrowdRandomSet.ChannelUse)EditorGUI.EnumPopup(
position,
(UMACrowdRandomSet.ChannelUse)Enum.Parse(typeof(UMACrowdRandomSet.ChannelUse), colorChannelUse.enumNames[colorChannelUse.enumValueIndex]));
if (colorChannelUse.enumValueIndex != 0)
{
position.y += 20;
position.x = x;
position.width = labelWidth;
EditorGUI.LabelField(position, "Channel");
position.x += labelWidth + 5;
position.width = width - (labelWidth + 5);
var colorChannel = prop.FindPropertyRelative("colorChannel");
colorChannel.intValue = EditorGUI.IntField(position, colorChannel.intValue);
}
}
}
}
static class LabelHelper
{
public static GUIStyle HeaderStyle;
static LabelHelper()
{
HeaderStyle = new GUIStyle();
HeaderStyle.border = new RectOffset(2, 2, 2, 1);
HeaderStyle.margin = new RectOffset(5, 5, 5, 0);
HeaderStyle.padding = new RectOffset(5, 5, 0, 0);
HeaderStyle.alignment = TextAnchor.MiddleLeft;
HeaderStyle.normal.background = EditorGUIUtility.isProSkin
? LoadTexture(s_DarkSkin)
: LoadTexture(s_LightSkin);
HeaderStyle.normal.textColor = EditorGUIUtility.isProSkin
? new Color(0.8f, 0.8f, 0.8f)
: new Color(0.2f, 0.2f, 0.2f);
}
static Texture2D LoadTexture(string textureData)
{
byte[] imageData = Convert.FromBase64String(textureData);
// Gather image size from image data.
int texWidth, texHeight;
GetImageSize(imageData, out texWidth, out texHeight);
// Generate texture asset.
var tex = new Texture2D(texWidth, texHeight, TextureFormat.ARGB32, false);
tex.hideFlags = HideFlags.HideAndDontSave;
tex.name = "ReorderableList";
tex.filterMode = FilterMode.Point;
tex.LoadImage(imageData);
return tex;
}
private static void GetImageSize(byte[] imageData, out int width, out int height)
{
width = ReadInt(imageData, 3 + 15);
height = ReadInt(imageData, 3 + 15 + 2 + 2);
}
private static int ReadInt(byte[] imageData, int offset)
{
return (imageData[offset] << 8) | imageData[offset + 1];
}
/// <summary>
/// Resource assets for light skin.
/// </summary>
/// <remarks>
/// <para>Resource assets are PNG images which have been encoded using a base-64
/// string so that actual asset files are not necessary.</para>
/// </remarks>
private static string s_LightSkin =
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAEFJREFUeNpi/P//P0NxcfF/BgRgZP78+fN/VVVVhpCQEAZjY2OGs2fPNrCApBwdHRkePHgAVwoWnDVrFgMyAAgwAAt4E1dCq1obAAAAAElFTkSuQmCC";
/// <summary>
/// Resource assets for dark skin.
/// </summary>
/// <remarks>
/// <para>Resource assets are PNG images which have been encoded using a base-64
/// string so that actual asset files are not necessary.</para>
/// </remarks>
private static string s_DarkSkin =
"iVBORw0KGgoAAAANSUhEUgAAAAUAAAAECAYAAABGM/VAAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADtJREFUeNpi/P//P4OKisp/Bii4c+cOIwtIQE9Pj+HLly9gQRCfBcQACbx69QqmmAEseO/ePQZkABBgAD04FXsmmijSAAAAAElFTkSuQmCC";
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.LPC3180
{
using System;
using System.Runtime.CompilerServices;
using Microsoft.Zelig.Runtime;
[MemoryMappedPeripheral(Base=0x40080000U,Length=0x00018020U)]
public class StandardUART
{
public enum Id
{
UART3 = 0,
UART4 = 1,
UART5 = 2,
UART6 = 3,
}
[BitFieldPeripheral(PhysicalType=typeof(byte))]
public struct UnIER_bitfield
{
[BitFieldRegister(Position=2)] public bool Rx; // Rx Line Status Interrupt Enable
//
// *0: Disable the Rx line status interrupts.
// 1: Enable the Rx line status interrupts.
//
// This bit enables the UARTn Receiver Line Status interrupt.
// This interrupt reflects Overrun Error, Parity Error, Framing Error, and Break conditions.
// The status of this interrupt can be read from UnLSR[4:1].
//
[BitFieldRegister(Position=1)] public bool THRE; // THRE Interrupt Enable
//
// *0: Disable the THRE interrupt.
// 1: Enable the THRE interrupt.
//
// This bit enables the Transmit Holding Register Empty (THRE) interrupt for UARTn.
// The status of this interrupt can be read from UnLSR[5].
//
//
[BitFieldRegister(Position=0)] public bool RDAE; // RDA Interrupt Enable
//
// *0: Disable the RDA interrupt.
// 1: Enable the RDA interrupt.
//
// This bit enables the Receive Data Available (RDA) interrupt for UARTn.
//
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(byte))]
public struct UnIIR_bitfield
{
public enum InterruptType : uint
{
//
//
// Priority | Interrupt type | Interrupt source | Method of clearing interrupt
// ---------+----------------------------------------+------------------------------------------------------------------------------+-------------------------------------------
RLS = 0x3, // 1 (High) | Receiver Line Status (RLS) | OE (Overrun Error), PE (Parity Error), FE (Framing Error), or | Read of UnLSR.
// | | BI (Break Indication). |
// | | Note that an RLS interrupt is asserted immediately rather |
// | | than waiting for the corresponding character to reach the top of the FIFO. |
// | | |
RDA = 0x2, // 2 | Receiver Data Available (RDA) | When the FIFO is turned off (UnFCR[0] = 0), | Read of UnRBR when UnFCR[0] = 0,
// | | this interrupt is asserted when receive data is available. | or UARTn FIFO contents go below the trigger level when UnFCR[0] = 1.
// | | |
// | | When the FIFO is turned on (UnFCR[0] = 1), |
// | | this interrupt is asserted when the receive trigger level (as specified by |
// | | UnFCR[7:6]) has been reached in the FIFO. |
// | | |
CTI = 0x6, // 2 | Character Time-out Indication (CTI) | This case occurs when there is at least one character in the Rx FIFO and | Read of UnRBR, or a Stop bit is received.
// | | no character has been received or removed from the FIFO |
// | | during the last 4 character times. |
// | | |
THRE = 0x1, // 3 | Transmit Holding Register Empty (THRE) | When the FIFO is turned off (UnFCR[0] = 0), | Read of UnIIR or write to THR.
// | | this interrupt is asserted when the transmit holding register is empty. |
// | | When the FIFO is turned on (UnFCR[0] = 1), |
// | | this interrupt is asserted when the transmit trigger level (as specified by |
// | | UnFCR[5:4]) has been reached in the FIFO. |
}
[BitFieldRegister(Position=1,Size=3)] public InterruptType IntId; // Interrupt Identification
//
[BitFieldRegister(Position=0 )] public bool NoIntPending; // Interrupt Pending
//
// This flag indicates when there are no UARTn related interrupts pending.
// Note that this bit is active LOW. The pending interrupt can be determined by evaluating UnIIR[3:0].
//
// 0: At least one interrupt is pending.
// *1: No pending interrupts.
//
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(byte))]
public struct UnFCR_bitfield
{
public enum RxTriggerLevel : uint
{
TriggerAt16 = 0, // *00: trigger level = 16
TriggerAt32 = 1, // 01: trigger level = 32
TriggerAt48 = 2, // 10: trigger level = 48
TriggerAt60 = 3, // 11: trigger level = 60
}
public enum TxTriggerLevel : uint
{
TriggerAt0 = 0, // *00: trigger level = 0
TriggerAt4 = 1, // 01: trigger level = 4
TriggerAt8 = 2, // 10: trigger level = 8
TriggerAt16 = 3, // 11: trigger level = 16
}
[BitFieldRegister(Position=6,Size=2)] public RxTriggerLevel RxLvl; // Receiver Trigger Level Select
// These two bits determine how many receiver UARTn FIFO characters must be present before an interrupt is activated.
//
[BitFieldRegister(Position=4,Size=2)] public TxTriggerLevel TxLvl; // Transmitter Trigger Level Select
// These two bits determine the level of the UARTn transmitter FIFO causes an interrupt.
//
[BitFieldRegister(Position=3 )] public bool FIFOControl; // FIFO Control.
//
// Internal UARTn FIFO control. This bit must be set to 1 for proper FIFO operation (default off)
//
[BitFieldRegister(Position=2 )] public bool ResetTxFIFO; // Transmitter FIFO Reset
//
// Writing a logic 1 to UnFCR[2] will clear all bytes in UARTn Tx FIFO and reset the pointer logic.
// This bit is self-clearing.
//
[BitFieldRegister(Position=1 )] public bool ResetRxFIFO; // Receiver FIFO Reset
//
// Writing a logic 1 to UnFCR[1] will clear all bytes in UARTn Rx FIFO and reset the pointer logic.
// This bit is self-clearing.
//
[BitFieldRegister(Position=0 )] public bool FIFOEnable; // FIFO Enable
//
// UARTn transmit and receive FIFO enable.
// Any transition on this bit will automatically clear the UARTn FIFOs.
//
// *0: UARTn Rx and Tx FIFOs disabled.
// 1: UARTn Rx and Tx FIFOs enabled and other UnFCR bits activated.
//
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(byte))]
public struct UnLCR_bitfield
{
public enum ParitySettings : uint
{
Odd = 0x0, // *00: Odd parity
Even = 0x1, // 01: Even parity
Forced1 = 0x2, // 10: Forced "1" stick parity
Forced0 = 0x3, // 11: Forced "0" stick parity
}
public enum LengthSettings : uint
{
Use5bits = 0x0, // *00: 5 bit character length
Use6bits = 0x1, // 01: 6 bit character length
Use7bits = 0x2, // 10: 7 bit character length
Use8bits = 0x3, // 11: 8 bit character length
}
[BitFieldRegister(Position=7 )] public bool DLAB; // Divisor Latch Access Bit
//
// Allows access to the alternate registers at address offsets 0 and 4.
//
// *0: Disable access to the baud rate Divisor Latches, enabling access to UnRBR, UnTHR, and UnIER.
// 1: Enable access to the baud rate Divisor Latches, disabling access to UnRBR, UnTHR, and UnIER.
//
[BitFieldRegister(Position=6 )] public bool Break; // Break Control
//
// Allows forcing the Un_TX output low in order to generate a break condition.
//
// *0: Disable break transmission
// 1: Enable break transmission.
//
[BitFieldRegister(Position=4,Size=2)] public ParitySettings Parity; // If bit UnLCR[3] = 1, selects the type of parity used by the UART.
//
//
[BitFieldRegister(Position=3 )] public bool ParityEnable; // Parity Enable
//
// Selects the whether or not the UART uses parity.
//
// *0: Disable parity generation and checking
// 1: Enable parity generation and checking
//
[BitFieldRegister(Position=2 )] public bool TwoStopBits; // Stop Bit Select
//
// Selects the number of stop bits used by the UART.
//
// *0: 1 stop bit
// 1: 2 stop bits (1.5 if UnLCR[1:0] = 00)
//
[BitFieldRegister(Position=0,Size=2)] public LengthSettings WordLen; // Word Length Select
//
// Selects the character length (in bits) used by the UART
//
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(byte))]
public struct UnLSR_bitfield
{
[BitFieldRegister(Position=7)] public bool FIFO_Rx_Error; // FIFO Rx Error
//
// This bit is set when a character with a receive error such as framing error, parity
// error or break interrupt, is loaded into the UnRBR. This bit is cleared when the
// UnLSR register is read and there are no subsequent errors in the UARTn FIFO.
//
// *0: UnRBR contains no UARTn Rx errors or UnFCR[0] = 0.
// 1: UARTn RBR contains at least one UARTn Rx error.
//
[BitFieldRegister(Position=6)] public bool TEMT; // Transmitter Empty
//
// This bit is set when the last character has been transmitted from the Transmit
// Shift Register. TEMT is cleared when another character is written to UnTHR.
//
// 0: UnTHR and/or the UnTSR contains valid data.
// *1: UnTHR and the UnTSR are empty.
//
[BitFieldRegister(Position=5)] public bool THRE; // Transmitter Holding Register Empty
//
// This bit is set when the transmitter FIFO reaches the level selected in UnFCR.
// THRE is cleared on a UnTHR write.
//
// 0: UnTHR contains valid data.
// *1: UnTHR is empty.
//
[BitFieldRegister(Position=4)] public bool BI; // Break Interrupt
//
// When the Un_RX pin is held low for one full character transmission (start, data,
// parity, stop), a break interrupt occurs. Once the break condition has been
// detected, the receiver goes idle until the Un_RX pin goes high. A read of UnLSR
// clears this status bit.
//
// *0: Break interrupt status is inactive.
// 1: Break interrupt status is active.
//
[BitFieldRegister(Position=3)] public bool FE; // Framing Error
//
// When the stop bit of a received character is a logic 0, a framing error occurs. A
// read of UnLSR clears this bit. A framing error is associated with the character at
// the top of the UARTn RBR FIFO.
// Upon detection of a framing error, the receiver will attempt to resynchronize to
// the data and assume that the bad stop bit is actually an early start bit.
// However, it cannot be assumed that the next received byte will be correct even if there is no Framing Error.
//
// *0: Framing error status is inactive.
// 1: Framing error status is active.
//
[BitFieldRegister(Position=2)] public bool PE; // Parity Error
//
// When the parity bit of a received character is in the wrong state, a parity error occurs.
// A read of UnLSR clears this bit. A parity error is associated with the character at the top of the UARTn RBR FIFO.
//
// *0: Parity error status is inactive.
// 1: Parity error status is active.
//
[BitFieldRegister(Position=1)] public bool OE; // Overrun Error
//
// This bit is set when the UARTn RSR has a new character assembled and the UARTn RBR FIFO is full.
// In this case, the UARTn RBR FIFO will not be overwritten and the character in the UARTn RSR will be lost.
// The overrun error condition is set as soon as it occurs. A read of UnLSR clears the OE flag.
//
// *0: Overrun error status is inactive.
// 1: Overrun error status is active.
//
[BitFieldRegister(Position=0)] public bool RDR; // Receiver Data Ready
//
// This bit is set when the UnRBR holds an unread character and is cleared when the UARTn RBR FIFO is empty.
// 0: UnRBR is empty.
// 1: UnRBR contains valid data.
//
}
//--//
[MemoryMappedPeripheral(Base=0x0000U,Length=0x8000U)]
public class Port
{
[Register(Offset=0x00U)] public byte UnRBR; // Receiver Buffer Register R
[Register(Offset=0x00U)] public byte UnTHR; // Transmit Holding Register W
[Register(Offset=0x04U)] public UnIER_bitfield UnIER; // Interrupt Enable Register
[Register(Offset=0x00U)] public byte UnDLL; // Divisor Latch Lower Byte W
[Register(Offset=0x04U)] public byte UnDLM; // Divisor Latch Upper Byte W
[Register(Offset=0x08U)] public UnIIR_bitfield UnIIR; // Interrupt ID Register R
[Register(Offset=0x08U)] public UnFCR_bitfield UnFCR; // FIFO Control Register W
[Register(Offset=0x0CU)] public UnLCR_bitfield UnLCR; // Line Control Register
[Register(Offset=0x14U)] public UnLSR_bitfield UnLSR; // Line Status Register
[Register(Offset=0x1CU)] public byte UnRXLEV; // Receive FIFO Level Register
//
// Helper Methods
//
[Inline]
public void EnableReceiveInterrupt()
{
this.UnIER.RDAE = true;
}
[Inline]
public void DisableReceiveInterrupt()
{
this.UnIER.RDAE = false;
}
[Inline]
public void EnableTransmitInterrupt()
{
this.UnIER.THRE = true;
}
[Inline]
public void DisableTransmitInterrupt()
{
this.UnIER.THRE = false;
}
[Inline]
public bool ReadByte( out byte rx )
{
if(this.CanReceive)
{
rx = this.UnRBR;
return true;
}
else
{
rx = 0;
return false;
}
}
[Inline]
public bool WriteByte( byte tx )
{
if(this.CanSend)
{
this.UnTHR = tx;
return true;
}
return false;
}
//
// Access Methods
//
public bool CanSend
{
[Inline]
get
{
return this.UnLSR.THRE;
}
}
public bool CanReceive
{
[Inline]
get
{
return this.UnLSR.RDR;
}
}
public bool IsTransmitInterruptEnabled
{
[Inline]
get
{
return this.UnIER.THRE;
}
}
public bool IsReceiveInterruptEnabled
{
[Inline]
get
{
return this.UnIER.RDAE;
}
}
//
// Debug Methods
//
public void DEBUG_WriteLine( string text ,
uint value )
{
DEBUG_Write( text, value );
DEBUG_Write( Environment.NewLine );
}
public void DEBUG_WriteLine( string text )
{
DEBUG_Write( text );
DEBUG_Write( Environment.NewLine );
}
public void DEBUG_Write( string text ,
uint value )
{
DEBUG_Write ( text );
DEBUG_WriteHex( value );
}
[DisableBoundsChecks()]
[DisableNullChecks]
public void DEBUG_Write( string s )
{
if(s != null)
{
foreach(char c in s)
{
DEBUG_Write( c );
}
}
}
public void DEBUG_WriteHex( uint value )
{
DEBUG_Write( "0x" );
for(int pos = 32 - 4; pos >= 0; pos -= 4)
{
uint digit = (value >> pos) & 0xF;
DEBUG_Write( digit >= 10 ? (char)('A' + (digit - 10)) : (char)('0' + digit) );
}
}
public void DEBUG_Write( char c )
{
while(this.CanSend == false)
{
}
this.UnTHR = (byte)c;
}
}
//--//
[Register(Offset=0x00000000U,Instances=4)] public Port[] Ports;
//--//
//
// Helper Methods
//
//// [Inline]
public Port Configure( StandardUART.Id portNo ,
bool fAutoClock ,
int baudrate )
{
var cfg = new BaseSerialStream.Configuration( null )
{
BaudRate = baudrate,
DataBits = 8,
Parity = System.IO.Ports.Parity.None,
StopBits = System.IO.Ports.StopBits.One,
};
return Configure( portNo, fAutoClock, ref cfg );
}
//// [Inline]
public Port Configure( StandardUART.Id portNo ,
bool fAutoClock ,
ref BaseSerialStream.Configuration cfg )
{
uint preDivX;
uint preDivY;
int divisor;
switch(cfg.BaudRate)
{
case 2400: preDivX = 1; preDivY = 169; divisor = 2; break;
case 4800: preDivX = 1; preDivY = 169; divisor = 1; break;
case 9600: preDivX = 3; preDivY = 254; divisor = 1; break;
case 19200: preDivX = 3; preDivY = 127; divisor = 1; break;
case 38400: preDivX = 6; preDivY = 127; divisor = 1; break;
case 57600: preDivX = 9; preDivY = 127; divisor = 1; break;
case 115200: preDivX = 19; preDivY = 134; divisor = 1; break;
case 230400: preDivX = 19; preDivY = 67; divisor = 1; break;
case 460800: preDivX = 38; preDivY = 67; divisor = 1; break;
default:
return null;
}
var sysCtrl = SystemControl.Instance;
var valUART_CLKMODE__UARTx_CLK = fAutoClock ? SystemControl.UART_CLKMODE_bitfield.Mode.AutoClock : SystemControl.UART_CLKMODE_bitfield.Mode.ClockOn;
var valUxCLK = new SystemControl.UxCLK_bitfield();
valUxCLK.UseHCLK = false;
valUxCLK.X = preDivX;
valUxCLK.Y = preDivY;
switch(portNo)
{
case Id.UART3:
sysCtrl.UARTCLK_CTRL.Uart3_Enable = true;
sysCtrl.UART_CLKMODE.UART3_CLK = valUART_CLKMODE__UARTx_CLK;
sysCtrl.U3CLK = valUxCLK;
break;
case Id.UART4:
sysCtrl.UARTCLK_CTRL.Uart4_Enable = true;
sysCtrl.UART_CLKMODE.UART4_CLK = valUART_CLKMODE__UARTx_CLK;
sysCtrl.U4CLK = valUxCLK;
break;
case Id.UART5:
sysCtrl.UARTCLK_CTRL.Uart5_Enable = true;
sysCtrl.UART_CLKMODE.UART5_CLK = valUART_CLKMODE__UARTx_CLK;
sysCtrl.U5CLK = valUxCLK;
break;
case Id.UART6:
sysCtrl.UARTCLK_CTRL.Uart6_Enable = true;
sysCtrl.UART_CLKMODE.UART6_CLK = valUART_CLKMODE__UARTx_CLK;
sysCtrl.U6CLK = valUxCLK;
break;
default:
return null;
}
//--//
var lcr = new UnLCR_bitfield();
if(cfg.Parity != System.IO.Ports.Parity.None)
{
lcr.ParityEnable = true;
switch(cfg.Parity)
{
case System.IO.Ports.Parity.Even:
lcr.Parity = UnLCR_bitfield.ParitySettings.Even;
break;
case System.IO.Ports.Parity.Odd:
lcr.Parity = UnLCR_bitfield.ParitySettings.Odd;
break;
default:
return null;
}
}
switch(cfg.StopBits)
{
case System.IO.Ports.StopBits.One:
break;
case System.IO.Ports.StopBits.Two:
lcr.TwoStopBits = true;
break;
default:
return null;
}
switch(cfg.DataBits)
{
case 5: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use5bits; break;
case 6: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use6bits; break;
case 7: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use7bits; break;
case 8: lcr.WordLen = UnLCR_bitfield.LengthSettings.Use8bits; break;
default:
return null;
}
//--//
Port uart = this.Ports[(int)portNo];
{
var val = new UnIER_bitfield();
uart.UnIER = val; // Disable both Rx and Tx interrupts
}
//--//
var fcr = new UnFCR_bitfield();
fcr.RxLvl = UnFCR_bitfield.RxTriggerLevel.TriggerAt16;
fcr.TxLvl = UnFCR_bitfield.TxTriggerLevel.TriggerAt0;
fcr.ResetRxFIFO = true;
fcr.ResetTxFIFO = true;
fcr.FIFOEnable = true;
uart.UnFCR = fcr;
//--//
{
var lcr2 = new UnLCR_bitfield();
lcr2.DLAB = true;
uart.UnLCR = lcr2;
}
uart.UnDLL = (byte) divisor;
uart.UnDLM = (byte)(divisor >> 8);
uart.UnLCR = lcr;
//--//
return uart;
}
//
// Access Methods
//
public static extern StandardUART Instance
{
[SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
}
}
| |
using System;
using System.IO;
using GitVersion;
using GitVersion.MSBuildTask;
using GitVersionCore.Tests.Helpers;
using GitVersionTask.Tests.Mocks;
using Microsoft.Build.Framework;
using NUnit.Framework;
namespace GitVersionTask.Tests
{
[TestFixture]
public class InvalidFileCheckerTests : TestBase
{
private string projectDirectory;
private string projectFile;
[SetUp]
public void CreateTemporaryProject()
{
projectDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
projectFile = Path.Combine(projectDirectory, "Fake.csproj");
Directory.CreateDirectory(projectDirectory);
File.Create(projectFile).Close();
}
[TearDown]
public void Cleanup()
{
Directory.Delete(projectDirectory, true);
}
[Test]
public void VerifyIgnoreNonAssemblyInfoFile()
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "SomeOtherFile.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
[assembly: AssemblyVersion(""1.0.0.0"")]
");
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "SomeOtherFile.cs" } }, projectFile);
}
[Test]
public void VerifyAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
[assembly:{0}(""1.0.0.0"")]
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs"));
}
[Test]
public void VerifyUnformattedAttributeFoundCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
[ assembly :
{0} ( ""1.0.0.0"")]
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.cs"));
}
[Test]
public void VerifyCommentWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
//[assembly: {0}(""1.0.0.0"")]
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyCommentWithNoNewLineAtEndWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
//[assembly: {0}(""1.0.0.0"")]", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyStringWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
public class Temp
{{
static const string Foo = ""[assembly: {0}(""""1.0.0.0"""")]"";
}}
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyIdentifierWorksCSharp([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.cs")))
{
writer.Write(@"
using System;
using System.Reflection;
public class {0}
{{
}}
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.cs" } }, projectFile);
}
[Test]
public void VerifyAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System.Reflection.AssemblyVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
<Assembly:{0}(""1.0.0.0"")>
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb"));
}
[Test]
public void VerifyUnformattedAttributeFoundVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion", "System . Reflection . AssemblyVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
< Assembly :
{0} ( ""1.0.0.0"")>
", attribute);
}
var ex = Assert.Throws<WarningException>(() => FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile), attribute);
Assert.That(ex.Message, Is.EqualTo("File contains assembly version attributes which conflict with the attributes generated by GitVersion AssemblyInfo.vb"));
}
[Test]
public void VerifyCommentWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
'<Assembly: {0}(""1.0.0.0"")>
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
[Test]
public void VerifyCommentWithNoNewLineAtEndWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
'<Assembly: {0}(""1.0.0.0"")>", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
[Test]
public void VerifyStringWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
Public Class Temp
static const string Foo = ""<Assembly: {0}(""""1.0.0.0"""")>"";
End Class
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
[Test]
public void VerifyIdentifierWorksVisualBasic([Values("AssemblyVersion", "AssemblyFileVersion", "AssemblyInformationalVersion")]string attribute)
{
using (var writer = File.CreateText(Path.Combine(projectDirectory, "AssemblyInfo.vb")))
{
writer.Write(@"
Imports System
Imports System.Reflection
Public Class {0}
End Class
", attribute);
}
FileHelper.CheckForInvalidFiles(new ITaskItem[] { new MockTaskItem { ItemSpec = "AssemblyInfo.vb" } }, projectFile);
}
}
}
| |
#region Header
/**
* JsonData.cs
* Generic type to hold JSON data (objects, arrays, and so on). This is
* the default type returned by JsonMapper.ToObject().
*
* The authors disclaim copyright to this source code. For more details, see
* the COPYING file included with this distribution.
**/
#endregion Header
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.InteropServices;
namespace CrowSerialization.LitJson
{
using JsonArray = List<JsonData>;
using JsonDict = OrderedDictionary;
public class JsonData : IJsonWrapper, IEquatable<JsonData>
{
[StructLayout ( LayoutKind.Explicit )]
private struct JsonValue
{
[FieldOffset ( 0 )]
public bool inst_boolean;
[FieldOffset ( 0 )]
public double inst_double;
[FieldOffset ( 0 )]
public int inst_int;
[FieldOffset ( 0 )]
public long inst_long;
}
#region Fields
private JsonType type;
private JsonValue inst_value;
private object inst_object;
// cache
private string json;
#endregion Fields
#region Properties
public int Count
{
get { return EnsureCollection ().Count; }
}
public bool IsArray
{
get { return type == JsonType.Array; }
}
public bool IsBoolean
{
get { return type == JsonType.Boolean; }
}
public bool IsDouble
{
get { return type == JsonType.Double; }
}
public bool IsInt
{
get { return type == JsonType.Int; }
}
public bool IsLong
{
get { return type == JsonType.Long; }
}
public bool IsObject
{
get { return type == JsonType.Object; }
}
public bool IsString
{
get { return type == JsonType.String; }
}
public ICollection Keys
{
get { EnsureDictionary (); return ((JsonDict)inst_object).Keys; }
}
#endregion Properties
#region ICollection Properties
int ICollection.Count
{
get { return Count; }
}
bool ICollection.IsSynchronized
{
get { return EnsureCollection ().IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return EnsureCollection ().SyncRoot; }
}
#endregion ICollection Properties
#region IDictionary Properties
bool IDictionary.IsFixedSize
{
get { return ((IDictionary)EnsureDictionary ()).IsFixedSize; }
}
bool IDictionary.IsReadOnly
{
get { return EnsureDictionary ().IsReadOnly; }
}
ICollection IDictionary.Keys
{
get { EnsureDictionary (); return ((JsonDict)inst_object).Keys; }
}
ICollection IDictionary.Values
{
get { EnsureDictionary (); return ((JsonDict)inst_object).Values; }
}
#endregion IDictionary Properties
#region IJsonWrapper Properties
bool IJsonWrapper.IsArray
{
get { return IsArray; }
}
bool IJsonWrapper.IsBoolean
{
get { return IsBoolean; }
}
bool IJsonWrapper.IsDouble
{
get { return IsDouble; }
}
bool IJsonWrapper.IsInt
{
get { return IsInt; }
}
bool IJsonWrapper.IsLong
{
get { return IsLong; }
}
bool IJsonWrapper.IsObject
{
get { return IsObject; }
}
bool IJsonWrapper.IsString
{
get { return IsString; }
}
#endregion IJsonWrapper Properties
#region IList Properties
bool IList.IsFixedSize
{
get { return ((IList)EnsureList ()).IsFixedSize; }
}
bool IList.IsReadOnly
{
get { return ((IList)EnsureList ()).IsReadOnly; }
}
#endregion IList Properties
#region IDictionary Indexer
object IDictionary.this[object key]
{
get { return EnsureDictionary ()[key]; }
set
{
if ( !(key is String) )
throw new ArgumentException (
"The key has to be a string" );
JsonData data = ToJsonData ( value );
this[(string)key] = data;
}
}
#endregion IDictionary Indexer
#region IOrderedDictionary Indexer
object IOrderedDictionary.this[int idx]
{
get { return EnsureDictionary ()[idx]; }
set { JsonData data = ToJsonData ( value ); EnsureDictionary ()[idx] = data; }
}
#endregion IOrderedDictionary Indexer
#region IList Indexer
object IList.this[int index]
{
get { return EnsureList ()[index]; }
set
{
EnsureList ();
this[index] = ToJsonData ( value );
}
}
#endregion IList Indexer
#region Public Indexers
public JsonData this[string prop_name]
{
get { return (JsonData)EnsureDictionary ()[prop_name]; }
set { EnsureDictionary ()[prop_name] = value; json = null; }
}
public JsonData this[int index]
{
get
{
EnsureCollection ();
if ( type == JsonType.Array )
return ((JsonArray)inst_object)[index];
else
return (JsonData)((JsonDict)inst_object)[index];
}
set
{
EnsureCollection ();
if ( type == JsonType.Array )
((JsonArray)inst_object)[index] = value;
else
((JsonDict)inst_object)[index] = value;
json = null;
}
}
#endregion Public Indexers
#region Constructors
public JsonData ()
{
}
public JsonData ( bool boolean )
{
type = JsonType.Boolean;
inst_value.inst_boolean = boolean;
}
public JsonData ( double number )
{
type = JsonType.Double;
inst_value.inst_double = number;
}
public JsonData ( int number )
{
type = JsonType.Int;
inst_value.inst_int = number;
}
public JsonData ( long number )
{
type = JsonType.Long;
inst_value.inst_long = number;
}
public JsonData ( string str )
{
type = JsonType.String;
inst_object = str;
}
public JsonData ( object obj )
{
if ( obj is Boolean )
{
type = JsonType.Boolean;
inst_value.inst_boolean = (bool)obj;
return;
}
if ( obj is Double )
{
type = JsonType.Double;
inst_value.inst_double = (double)obj;
return;
}
if ( obj is Int32 )
{
type = JsonType.Int;
inst_value.inst_int = (int)obj;
return;
}
if ( obj is Int64 )
{
type = JsonType.Long;
inst_value.inst_long = (long)obj;
return;
}
if ( obj is String )
{
type = JsonType.String;
inst_object = (string)obj;
return;
}
throw new ArgumentException ( "Unable to wrap the given object with JsonData" );
}
#endregion Constructors
#region Implicit Conversions
public static implicit operator JsonData ( Boolean data )
{
return new JsonData ( data );
}
public static implicit operator JsonData ( Double data )
{
return new JsonData ( data );
}
public static implicit operator JsonData ( Int32 data )
{
return new JsonData ( data );
}
public static implicit operator JsonData ( Int64 data )
{
return new JsonData ( data );
}
public static implicit operator JsonData ( String data )
{
return new JsonData ( data );
}
#endregion Implicit Conversions
#region Explicit Conversions
public static explicit operator Boolean ( JsonData data )
{
if ( data.type != JsonType.Boolean )
throw new InvalidCastException ( "Instance of JsonData doesn't hold a boolean" );
return data.inst_value.inst_boolean;
}
public static explicit operator Double ( JsonData data )
{
if ( data.type != JsonType.Double )
throw new InvalidCastException ( "Instance of JsonData doesn't hold a double" );
return data.inst_value.inst_double;
}
public static explicit operator Int32 ( JsonData data )
{
if ( data.type != JsonType.Int )
throw new InvalidCastException ( "Instance of JsonData doesn't hold an int32" );
return data.inst_value.inst_int;
}
public static explicit operator Int64 ( JsonData data )
{
if ( data.type != JsonType.Long )
throw new InvalidCastException ( "Instance of JsonData doesn't hold an int64" );
return data.inst_value.inst_long;
}
public static explicit operator String ( JsonData data )
{
if ( data.type != JsonType.String )
throw new InvalidCastException ( "Instance of JsonData doesn't hold a string" );
return (string)data.inst_object;
}
#endregion Explicit Conversions
#region ICollection Methods
void ICollection.CopyTo ( Array array, int index )
{
EnsureCollection ().CopyTo ( array, index );
}
#endregion ICollection Methods
#region IDictionary Methods
void IDictionary.Add ( object key, object value )
{
JsonData data = ToJsonData ( value );
EnsureDictionary ().Add ( key, data );
json = null;
}
void IDictionary.Clear ()
{
EnsureDictionary ().Clear ();
json = null;
}
bool IDictionary.Contains ( object key )
{
return EnsureDictionary ().Contains ( key );
}
IDictionaryEnumerator IDictionary.GetEnumerator ()
{
return ((IOrderedDictionary)this).GetEnumerator ();
}
void IDictionary.Remove ( object key )
{
EnsureDictionary ().Remove ( key );
json = null;
}
#endregion IDictionary Methods
#region IEnumerable Methods
IEnumerator IEnumerable.GetEnumerator ()
{
return EnsureCollection ().GetEnumerator ();
}
#endregion IEnumerable Methods
#region IJsonWrapper Methods
bool IJsonWrapper.GetBoolean ()
{
if ( type != JsonType.Boolean )
throw new InvalidOperationException (
"JsonData instance doesn't hold a boolean" );
return inst_value.inst_boolean;
}
double IJsonWrapper.GetDouble ()
{
if ( type != JsonType.Double )
throw new InvalidOperationException (
"JsonData instance doesn't hold a double" );
return inst_value.inst_double;
}
int IJsonWrapper.GetInt ()
{
if ( type != JsonType.Int )
throw new InvalidOperationException (
"JsonData instance doesn't hold an int" );
return inst_value.inst_int;
}
long IJsonWrapper.GetLong ()
{
if ( type != JsonType.Long )
throw new InvalidOperationException (
"JsonData instance doesn't hold a long" );
return inst_value.inst_long;
}
string IJsonWrapper.GetString ()
{
if ( type != JsonType.String )
throw new InvalidOperationException (
"JsonData instance doesn't hold a string" );
return (string)inst_object;
}
void IJsonWrapper.SetBoolean ( bool val )
{
type = JsonType.Boolean;
inst_value.inst_boolean = val;
json = null;
}
void IJsonWrapper.SetDouble ( double val )
{
type = JsonType.Double;
inst_value.inst_double = val;
json = null;
}
void IJsonWrapper.SetInt ( int val )
{
type = JsonType.Int;
inst_value.inst_int = val;
json = null;
}
void IJsonWrapper.SetLong ( long val )
{
type = JsonType.Long;
inst_value.inst_long = val;
json = null;
}
void IJsonWrapper.SetString ( string val )
{
type = JsonType.String;
inst_object = val;
json = null;
}
string IJsonWrapper.ToJson ()
{
return ToJson ();
}
void IJsonWrapper.ToJson ( JsonWriter writer )
{
ToJson ( writer );
}
#endregion IJsonWrapper Methods
#region IList Methods
int IList.Add ( object value )
{
return Add ( value );
}
void IList.Clear ()
{
EnsureList ().Clear ();
json = null;
}
bool IList.Contains ( object value )
{
return ((IList)EnsureList ()).Contains ( value );
}
int IList.IndexOf ( object value )
{
return ((IList)EnsureList ()).IndexOf ( value );
}
void IList.Insert ( int index, object value )
{
((IList)EnsureList ()).Insert ( index, value );
json = null;
}
void IList.Remove ( object value )
{
((IList)EnsureList ()).Remove ( value );
json = null;
}
void IList.RemoveAt ( int index )
{
EnsureList ().RemoveAt ( index );
json = null;
}
#endregion IList Methods
#region IOrderedDictionary Methods
IDictionaryEnumerator IOrderedDictionary.GetEnumerator ()
{
return EnsureDictionary ().GetEnumerator ();
}
void IOrderedDictionary.Insert ( int idx, object key, object value )
{
string property = (string)key;
JsonData data = ToJsonData ( value );
this[property] = data;
}
void IOrderedDictionary.RemoveAt ( int idx )
{
EnsureDictionary ().RemoveAt ( idx );
}
#endregion IOrderedDictionary Methods
#region Private Methods
private ICollection EnsureCollection ()
{
if ( type == JsonType.Array || type == JsonType.Object )
return (ICollection)inst_object;
throw new InvalidOperationException (
"The JsonData instance has to be initialized first" );
}
private JsonDict EnsureDictionary ()
{
if ( type == JsonType.Object )
return (JsonDict)inst_object;
if ( type != JsonType.None )
throw new InvalidOperationException ( "Instance of JsonData is not a dictionary" );
type = JsonType.Object;
inst_object = new JsonDict ( StringComparer.InvariantCulture );
return (JsonDict)inst_object;
}
private JsonArray EnsureList ()
{
if ( type == JsonType.Array )
return (JsonArray)inst_object;
if ( type != JsonType.None )
throw new InvalidOperationException (
"Instance of JsonData is not a list" );
type = JsonType.Array;
inst_object = new JsonArray ();
return (JsonArray)inst_object;
}
private JsonData ToJsonData ( object obj )
{
if ( obj == null )
return null;
if ( obj is JsonData )
return (JsonData)obj;
return new JsonData ( obj );
}
private static void WriteJson ( IJsonWrapper obj, JsonWriter writer )
{
if ( obj == null )
{
writer.Write ( null );
return;
}
if ( obj.IsString )
{
writer.Write ( obj.GetString () );
return;
}
if ( obj.IsBoolean )
{
writer.Write ( obj.GetBoolean () );
return;
}
if ( obj.IsDouble )
{
writer.Write ( obj.GetDouble () );
return;
}
if ( obj.IsInt )
{
writer.Write ( obj.GetInt () );
return;
}
if ( obj.IsLong )
{
writer.Write ( obj.GetLong () );
return;
}
if ( obj.IsArray )
{
writer.WriteArrayStart ();
foreach ( object elem in (IList)obj )
WriteJson ( (JsonData)elem, writer );
writer.WriteArrayEnd ();
return;
}
if ( obj.IsObject )
{
writer.WriteObjectStart ();
foreach ( DictionaryEntry entry in ((IDictionary)obj) )
{
writer.WritePropertyName ( (string)entry.Key );
WriteJson ( (JsonData)entry.Value, writer );
}
writer.WriteObjectEnd ();
return;
}
}
#endregion Private Methods
public object GetValue ()
{
switch ( type )
{
case JsonType.String: return (string)inst_object;
case JsonType.Int: return inst_value.inst_int;
case JsonType.Long: return inst_value.inst_long;
case JsonType.Double: return inst_value.inst_double;
case JsonType.Boolean: return inst_value.inst_boolean;
default: throw new InvalidDataException ();
}
}
public int Add ( object value )
{
JsonData data = ToJsonData ( value );
json = null;
return ((IList)EnsureList ()).Add ( data );
}
public void Clear ()
{
if ( IsObject )
{
((IDictionary)this).Clear ();
return;
}
if ( IsArray )
{
((IList)this).Clear ();
return;
}
}
public bool Equals ( JsonData x )
{
if ( x == null )
return false;
if ( x.type != this.type )
return false;
switch ( this.type )
{
case JsonType.None:
return true;
case JsonType.Object:
case JsonType.Array:
case JsonType.String:
return this.inst_object.Equals ( x.inst_object );
case JsonType.Int:
return this.inst_value.inst_int.Equals ( x.inst_value.inst_int );
case JsonType.Long:
return this.inst_value.inst_long.Equals ( x.inst_value.inst_long );
case JsonType.Double:
return this.inst_value.inst_double.Equals ( x.inst_value.inst_double );
case JsonType.Boolean:
return this.inst_value.inst_boolean.Equals ( x.inst_value.inst_boolean );
}
return false;
}
public JsonType GetJsonType ()
{
return type;
}
public void SetJsonType ( JsonType type )
{
if ( this.type == type )
return;
switch ( type )
{
case JsonType.None:
break;
case JsonType.Object:
inst_object = new JsonDict ( StringComparer.InvariantCulture );
break;
case JsonType.Array:
inst_object = new JsonArray ();
break;
case JsonType.String:
inst_object = default ( String );
break;
case JsonType.Int:
inst_value = default ( JsonValue );
break;
case JsonType.Long:
inst_value = default ( JsonValue );
break;
case JsonType.Double:
inst_value = default ( JsonValue );
break;
case JsonType.Boolean:
inst_value = default ( JsonValue );
break;
}
this.type = type;
}
public string ToJson ()
{
if ( json != null )
return json;
StringWriter sw = new StringWriter ();
JsonWriter writer = new JsonWriter ( sw );
writer.Validate = false;
WriteJson ( this, writer );
json = sw.ToString ();
return json;
}
public void ToJson ( JsonWriter writer )
{
bool old_validate = writer.Validate;
writer.Validate = false;
WriteJson ( this, writer );
writer.Validate = old_validate;
}
public override string ToString ()
{
switch ( type )
{
case JsonType.Array:
return "JsonData array";
case JsonType.Boolean:
return inst_value.inst_boolean.ToString ();
case JsonType.Double:
return inst_value.inst_double.ToString ();
case JsonType.Int:
return inst_value.inst_int.ToString ();
case JsonType.Long:
return inst_value.inst_long.ToString ();
case JsonType.Object:
return "JsonData object";
case JsonType.String:
return (string)inst_object;
}
return "Uninitialized JsonData";
}
}
}
| |
// 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.Threading;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI MARS connection. Multiple MARS streams will be overlaid on this connection.
/// </summary>
internal class SNIMarsConnection
{
private readonly Guid _connectionId = Guid.NewGuid();
private readonly Dictionary<int, SNIMarsHandle> _sessions = new Dictionary<int, SNIMarsHandle>();
private readonly byte[] _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH];
private SNIHandle _lowerHandle;
private ushort _nextSessionId = 0;
private int _currentHeaderByteCount = 0;
private int _dataBytesLeft = 0;
private SNISMUXHeader _currentHeader;
private SNIPacket _currentPacket;
/// <summary>
/// Connection ID
/// </summary>
public Guid ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="lowerHandle">Lower handle</param>
private SNIMarsConnection(SNIHandle lowerHandle)
{
_lowerHandle = lowerHandle;
_lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete);
}
public SNIMarsHandle CreateSession(TdsParserStateObject callbackObject, out SNIError sniError)
{
lock (this)
{
ushort sessionId = _nextSessionId++;
SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, out sniError);
_sessions.Add(sessionId, handle);
return handle;
}
}
/// <summary>
/// Enables MARS for a TdsParserStateObject and returns its new handle.
/// </summary>
public static SNIMarsHandle EnableMars(TdsParserStateObject stateObject, out SNIError sniError)
{
Debug.Assert(!(stateObject.Handle is SNIMarsHandle), "Cannot enable MARS on a SNIMarsHandle");
SNIMarsConnection marsConnection = new SNIMarsConnection(stateObject.Handle);
marsConnection.StartReceive();
return marsConnection.CreateSession(stateObject, out sniError);
}
/// <summary>
/// Start receiving
/// </summary>
public void StartReceive()
{
SNIPacket packet = null;
ReceiveAsync(ref packet);
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public SNIError Send(SNIPacket packet)
{
lock (this)
{
return _lowerHandle.Send(packet);
}
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>True if completed synchronously, otherwise false</returns>
public bool SendAsync(SNIPacket packet, SNIAsyncCallback callback, bool forceCallback, out SNIError sniError)
{
lock (this)
{
return _lowerHandle.SendAsync(packet, callback, forceCallback, out sniError);
}
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>True if completed synchronous, otherwise false</returns>
public void ReceiveAsync(ref SNIPacket packet)
{
lock (this)
{
SNIError sniError;
bool completedSync = _lowerHandle.ReceiveAsync(true, ref packet, out sniError);
Debug.Assert(!completedSync && (sniError == null), "Should not have completed sync");
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public bool CheckConnection()
{
lock (this)
{
return _lowerHandle.CheckConnection();
}
}
/// <summary>
/// Process a receive error
/// </summary>
public void HandleReceiveError(SNIError sniError)
{
Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked.");
foreach (SNIMarsHandle handle in _sessions.Values)
{
handle.HandleReceiveError(new SNIPacket(), sniError);
}
_lowerHandle.Dispose();
}
/// <summary>
/// Process a send completion
/// </summary>
public void HandleSendComplete(SNIPacket packet, SNIError sniError)
{
packet.InvokeCompletionCallback(sniError);
}
/// <summary>
/// Process a receive completion
/// </summary>
public void HandleReceiveComplete(SNIPacket packet, SNIError sniError)
{
SNISMUXHeader currentHeader = null;
SNIPacket currentPacket = null;
SNIMarsHandle currentSession = null;
if (sniError != null)
{
lock (this)
{
HandleReceiveError(sniError);
return;
}
}
int packetOffset = 0;
while (true)
{
lock (this)
{
bool sessionRemoved = false;
if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
{
currentHeader = null;
currentPacket = null;
currentSession = null;
while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
{
int bytesTaken = packet.TakeData(packetOffset, _headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount);
packetOffset += bytesTaken;
_currentHeaderByteCount += bytesTaken;
if (bytesTaken == 0)
{
packetOffset = 0;
ReceiveAsync(ref packet);
return;
}
}
_currentHeader = new SNISMUXHeader()
{
SMID = _headerBytes[0],
flags = _headerBytes[1],
sessionId = BitConverter.ToUInt16(_headerBytes, 2),
length = BitConverter.ToUInt32(_headerBytes, 4) - SNISMUXHeader.HEADER_LENGTH,
sequenceNumber = BitConverter.ToUInt32(_headerBytes, 8),
highwater = BitConverter.ToUInt32(_headerBytes, 12)
};
_dataBytesLeft = (int)_currentHeader.length;
_currentPacket = new SNIPacket();
_currentPacket.Allocate((int)_currentHeader.length);
}
currentHeader = _currentHeader;
currentPacket = _currentPacket;
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
{
if (_dataBytesLeft > 0)
{
int length = packet.TakeData(packetOffset, _currentPacket, _dataBytesLeft);
packetOffset += length;
_dataBytesLeft -= length;
if (_dataBytesLeft > 0)
{
packetOffset = 0;
ReceiveAsync(ref packet);
return;
}
}
}
_currentHeaderByteCount = 0;
if (!sessionRemoved && !_sessions.TryGetValue(_currentHeader.sessionId, out currentSession))
{
sniError = new SNIError(SNIProviders.TCP_PROV, 0, 0, "Packet for unknown MARS session received");
HandleReceiveError(sniError);
return;
}
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN)
{
RemoveSession(_currentHeader.sessionId);
sessionRemoved = true;
}
else
{
currentSession = _sessions[_currentHeader.sessionId];
}
}
if (currentSession != null)
{
if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
{
currentSession.HandleReceiveComplete(currentPacket, currentHeader);
}
else if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK)
{
currentSession.HandleAck(currentHeader.highwater);
}
}
lock (this)
{
if (packet.Length - packetOffset == 0)
{
packetOffset = 0;
ReceiveAsync(ref packet);
return;
}
}
}
}
/// <summary>
/// Enable SSL
/// </summary>
public SNIError EnableSsl(uint options)
{
return _lowerHandle.EnableSsl(options);
}
/// <summary>
/// Disable SSL
/// </summary>
public void DisableSsl()
{
_lowerHandle.DisableSsl();
}
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public void KillConnection()
{
_lowerHandle.KillConnection();
}
/// <summary>
/// Removes a session from the set of sessions.
/// </summary>
private void RemoveSession(ushort sessionId)
{
Debug.Assert(Monitor.IsEntered(this), "Must have lock before calling this method");
bool wasRemoved = _sessions.Remove(_currentHeader.sessionId);
Debug.Assert(wasRemoved, "Attempted to remove a session that doesn't exist");
if (_sessions.Count == 0)
{
_lowerHandle.Dispose();
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpTibiaProxy.Util
{
public static class WinApi
{
public const uint PROCESS_ALL_ACCESS = 0x1F0FFF;
public const uint PROCESS_VM_READ = 0x0010;
public const uint PROCESS_VM_WRITE = 0x0020;
public const uint PROCESS_VM_OPERATION = 0x0008;
public const uint MEM_COMMIT = 0x1000;
public const uint MEM_RESERVE = 0x2000;
public const uint MEM_RELEASE = 0x8000;
public const uint SWP_NOMOVE = 0x2;
public const uint SWP_NOSIZE = 0x1;
public const uint HWND_TOPMOST = 0xFFFFFFFF;
public const uint HWND_NOTOPMOST = 0xFFFFFFFE;
public const int SW_HIDE = 0;
public const int SW_SHOWNORMAL = 1;
public const int SW_SHOWMINIMIZED = 2;
public const int SW_SHOWMAXIMIZED = 3;
public const int SW_SHOWNOACTIVATE = 4;
public const int SW_SHOW = 5;
public const int SW_MINIMIZE = 6;
public const int SW_SHOWMINNOACTIVE = 7;
public const int SW_SHOWNA = 8;
public const int SW_RESTORE = 9;
public const int SW_SHOWDEFAULT = 10;
public const uint WM_LBUTTONDOWN = 0x201;
public const uint WM_LBUTTONUP = 0x202;
public const uint CREATE_SUSPENDED = 0x00000004;
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern void SetWindowText(IntPtr hWnd, string str);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll")]
public static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool IsZoomed(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool FlashWindow(IntPtr hWnd, bool invert);
[DllImport("user32.dll")]
public static extern bool SetWindowPos(IntPtr hWnd, uint hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, int nCmd);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder className, int maxCharCount);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CreateProcess(String imageName, String cmdLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool boolInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, String lpszCurrentDir, ref STARTUPINFO si, out PROCESS_INFORMATION pi);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern Int32 WaitForSingleObject(IntPtr Handle, UInt32 Wait);
[DllImport("kernel32.dll")]
public static extern uint ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll")]
public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, UInt32 dwProcessId);
[DllImport("kernel32.dll")]
public static extern Int32 ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, UIntPtr nSize, IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, IntPtr dwSize, MemoryProtection flNewProtect, ref MemoryProtection lpflOldProtect);
[DllImport("kernel32.dll")]
public static extern Int32 WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out IntPtr lpNumberOfBytesWritten);
[DllImport("kernel32.dll")]
public static extern Int32 CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, AllocationType flAllocationType, MemoryProtection flProtect);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, AllocationType dwFreeType);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateToolhelp32Snapshot(SnapshotFlags dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll")]
public static extern bool Module32First(IntPtr hSnapshot, ref MODULEENTRY32 lpme);
[DllImport("kernel32.dll")]
public static extern bool Module32Next(IntPtr hSnapshot, ref MODULEENTRY32 lpme);
[DllImport("kernel32.dll")]
public static extern bool VirtualQueryEx(IntPtr hProcess, IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, uint dwLength);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, MemoryProtection flNewProtect, out MemoryProtection lpflOldProtect);
[DllImport("kernel32.dll")]
public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] out SYSTEM_INFO lpSystemInfo);
#region Enums
[Flags]
public enum AllocationType
{
Commit = 0x1000,
Reserve = 0x2000,
Decommit = 0x4000,
Release = 0x8000,
Reset = 0x80000,
Physical = 0x400000,
TopDown = 0x100000,
WriteWatch = 0x200000,
LargePages = 0x20000000
}
[Flags]
public enum MemoryProtection
{
Execute = 0x10,
ExecuteRead = 0x20,
ExecuteReadWrite = 0x40,
ExecuteWriteCopy = 0x80,
NoAccess = 0x01,
ReadOnly = 0x02,
ReadWrite = 0x04,
WriteCopy = 0x08,
GuardModifierflag = 0x100,
NoCacheModifierflag = 0x200,
WriteCombineModifierflag = 0x400
}
[Flags]
public enum SnapshotFlags : uint
{
HeapList = 0x00000001,
Process = 0x00000002,
Thread = 0x00000004,
Module = 0x00000008,
Module32 = 0x00000010,
All = (HeapList | Process | Thread | Module),
Inherit = 0x80000000,
NoHeaps = 0x40000000
}
#endregion
#region Structures
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
public struct SECURITY_ATTRIBUTES
{
public int length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
public struct SYSTEM_INFO
{
public ushort processorArchitecture;
private ushort reserved;
public uint dwPageSize;
public IntPtr lpMinimumApplicationAddress;
public IntPtr lpMaximumApplicationAddress;
public IntPtr dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public uint dwProcessorType;
public uint dwAllocationGranularity;
public ushort dwProcessorLevel;
public ushort dwProcessorRevision;
}
public struct IMAGE_DOS_HEADER
{
public ushort e_magic;
public ushort e_cblp;
public ushort e_cp;
public ushort e_crlc;
public ushort e_cparhdr;
public ushort e_minalloc;
public ushort e_maxalloc;
public ushort e_ss;
public ushort e_sp;
public ushort e_csum;
public ushort e_ip;
public ushort e_cs;
public ushort e_lfarlc;
public ushort e_ovno;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public ushort[] e_res1;
public ushort e_oemid;
public ushort e_oeminfo;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public ushort[] e_res2;
public int e_lfanew;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct IMAGE_FILE_HEADER
{
public ushort Machine;
public ushort NumberOfSections;
public uint TimeDateStamp;
public uint PointerToSymbolTable;
public uint NumberOfSymbols;
public ushort SizeOfOptionalHeader;
public ushort Characteristics;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct MODULEENTRY32
{
public uint dwSize;
public uint th32ModuleID;
public uint th32ProcessID;
public uint GlblcntUsage;
public uint ProccntUsage;
IntPtr modBaseAddr;
public uint modBaseSize;
IntPtr hModule;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string szModule;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExePath;
};
public struct MEMORY_BASIC_INFORMATION
{
public IntPtr BaseAddress;
public IntPtr AllocationBase;
public uint AllocationProtect;
public IntPtr RegionSize;
public uint State;
public uint Protect;
public uint Type;
}
#endregion
#region Macros
public static int MakeLParam(int LoWord, int HiWord)
{
return ((HiWord << 16) | (LoWord & 0xffff));
}
//the same function but with another name =D
// just for understand the code better.
public static int MakeWParam(int LoWord, int HiWord)
{
return ((HiWord << 16) | (LoWord & 0xffff));
}
public static T ReadUnmanagedStructure<T>(IntPtr hProcess, IntPtr lpAddr)
{
byte[] array = new byte[Marshal.SizeOf(typeof(T))];
ReadProcessMemory(hProcess, lpAddr, array, new UIntPtr((uint)array.Length), IntPtr.Zero);
GCHandle gCHandle = GCHandle.Alloc(array, GCHandleType.Pinned);
T result = (T)((object)Marshal.PtrToStructure(gCHandle.AddrOfPinnedObject(), typeof(T)));
gCHandle.Free();
return result;
}
public static IntPtr GetBaseAddress(IntPtr hProcess)
{
SYSTEM_INFO sYSTEM_INFO;
GetSystemInfo(out sYSTEM_INFO);
IntPtr lpMinimumApplicationAddress = sYSTEM_INFO.lpMinimumApplicationAddress;
MEMORY_BASIC_INFORMATION mEMORY_BASIC_INFORMATION = default(MEMORY_BASIC_INFORMATION);
uint dwLength = (uint)Marshal.SizeOf(mEMORY_BASIC_INFORMATION);
while (lpMinimumApplicationAddress.ToInt64() < sYSTEM_INFO.lpMaximumApplicationAddress.ToInt64())
{
if (!VirtualQueryEx(hProcess, lpMinimumApplicationAddress, out mEMORY_BASIC_INFORMATION, dwLength))
{
Console.WriteLine("Could not VirtualQueryEx {0} segment at {1}; error {2}", hProcess.ToInt64(), lpMinimumApplicationAddress.ToInt64(), Marshal.GetLastWin32Error());
return IntPtr.Zero;
}
if (mEMORY_BASIC_INFORMATION.Type == 16777216u && mEMORY_BASIC_INFORMATION.BaseAddress == mEMORY_BASIC_INFORMATION.AllocationBase && (mEMORY_BASIC_INFORMATION.Protect & 256u) != 256u)
{
IMAGE_DOS_HEADER iMAGE_DOS_HEADER = ReadUnmanagedStructure<IMAGE_DOS_HEADER>(hProcess, lpMinimumApplicationAddress);
if (iMAGE_DOS_HEADER.e_magic == 23117)
{
IntPtr lpAddr = new IntPtr(lpMinimumApplicationAddress.ToInt64() + (long)(iMAGE_DOS_HEADER.e_lfanew + 4));
if ((ReadUnmanagedStructure<IMAGE_FILE_HEADER>(hProcess, lpAddr).Characteristics & 2) == 2)
{
return lpMinimumApplicationAddress;
}
}
}
lpMinimumApplicationAddress = new IntPtr(mEMORY_BASIC_INFORMATION.BaseAddress.ToInt64() + mEMORY_BASIC_INFORMATION.RegionSize.ToInt64());
}
return lpMinimumApplicationAddress;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// load gui used to display various metric outputs
exec("~/art/gui/FrameOverlayGui.gui");
// Note: To implement your own metrics overlay
// just add a function with a name in the form
// XXXXMetricsCallback which can be enabled via
// metrics( XXXX )
function fpsMetricsCallback()
{
return " | FPS |" @
" " @ $fps::real @
" max: " @ $fps::realMax @
" min: " @ $fps::realMin @
" mspf: " @ 1000 / $fps::real;
}
function gfxMetricsCallback()
{
return " | GFX |" @
" PolyCount: " @ $GFXDeviceStatistics::polyCount @
" DrawCalls: " @ $GFXDeviceStatistics::drawCalls @
" RTChanges: " @ $GFXDeviceStatistics::renderTargetChanges;
}
function terrainMetricsCallback()
{
return " | Terrain |" @
" Cells: " @ $TerrainBlock::cellsRendered @
" Override Cells: " @ $TerrainBlock::overrideCells @
" DrawCalls: " @ $TerrainBlock::drawCalls;
}
function netMetricsCallback()
{
return " | Net |" @
" BitsSent: " @ $Stats::netBitsSent @
" BitsRcvd: " @ $Stats::netBitsReceived @
" GhostUpd: " @ $Stats::netGhostUpdates;
}
function groundCoverMetricsCallback()
{
return " | GroundCover |" @
" Cells: " @ $GroundCover::renderedCells @
" Billboards: " @ $GroundCover::renderedBillboards @
" Batches: " @ $GroundCover::renderedBatches @
" Shapes: " @ $GroundCover::renderedShapes;
}
function forestMetricsCallback()
{
return " | Forest |" @
" Cells: " @ $Forest::totalCells @
" Cells Meshed: " @ $Forest::cellsRendered @
" Cells Billboarded: " @ $Forest::cellsBatched @
" Meshes: " @ $Forest::cellItemsRendered @
" Billboards: " @ $Forest::cellItemsBatched;
}
function sfxMetricsCallback()
{
return " | SFX |" @
" Sounds: " @ $SFX::numSounds @
" Lists: " @ ( $SFX::numSources - $SFX::numSounds - $SFX::Device::fmodNumEventSource ) @
" Events: " @ $SFX::fmodNumEventSources @
" Playing: " @ $SFX::numPlaying @
" Culled: " @ $SFX::numCulled @
" Voices: " @ $SFX::numVoices @
" Buffers: " @ $SFX::Device::numBuffers @
" Memory: " @ ( $SFX::Device::numBufferBytes / 1024.0 / 1024.0 ) @ " MB" @
" Time/S: " @ $SFX::sourceUpdateTime @
" Time/P: " @ $SFX::parameterUpdateTime @
" Time/A: " @ $SFX::ambientUpdateTime;
}
function sfxSourcesMetricsCallback()
{
return sfxDumpSourcesToString();
}
function sfxStatesMetricsCallback()
{
return " | SFXStates |" @ sfxGetActiveStates();
}
function timeMetricsCallback()
{
return " | Time |" @
" Sim Time: " @ getSimTime() @
" Mod: " @ getSimTime() % 32;
}
function reflectMetricsCallback()
{
return " | REFLECT |" @
" Objects: " @ $Reflect::numObjects @
" Visible: " @ $Reflect::numVisible @
" Occluded: " @ $Reflect::numOccluded @
" Updated: " @ $Reflect::numUpdated @
" Elapsed: " @ $Reflect::elapsed NL
" Allocated: " @ $Reflect::renderTargetsAllocated @
" Pooled: " @ $Reflect::poolSize NL
" " @ getWord( $Reflect::textureStats, 1 ) TAB
" " @ getWord( $Reflect::textureStats, 2 ) @ "MB" TAB
" " @ getWord( $Reflect::textureStats, 0 );
}
function decalMetricsCallback()
{
return " | DECAL |" @
" Batches: " @ $Decal::Batches @
" Buffers: " @ $Decal::Buffers @
" DecalsRendered: " @ $Decal::DecalsRendered;
}
function renderMetricsCallback()
{
return " | Render |" @
" Mesh: " @ $RenderMetrics::RIT_Mesh @
" MeshDL: " @ $RenderMetrics::RIT_MeshDynamicLighting @
" Shadow: " @ $RenderMetrics::RIT_Shadow @
" Sky: " @ $RenderMetrics::RIT_Sky @
" Obj: " @ $RenderMetrics::RIT_Object @
" ObjT: " @ $RenderMetrics::RIT_ObjectTranslucent @
" Decal: " @ $RenderMetrics::RIT_Decal @
" Water: " @ $RenderMetrics::RIT_Water @
" Foliage: " @ $RenderMetrics::RIT_Foliage @
" Trans: " @ $RenderMetris::RIT_Translucent @
" Custom: " @ $RenderMetrics::RIT_Custom;
}
function shadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $ShadowStats::activeMaps @
" Updated: " @ $ShadowStats::updatedMaps @
" PolyCount: " @ $ShadowStats::polyCount @
" DrawCalls: " @ $ShadowStats::drawCalls @
" RTChanges: " @ $ShadowStats::rtChanges @
" PoolTexCount: " @ $ShadowStats::poolTexCount @
" PoolTexMB: " @ $ShadowStats::poolTexMemory @ "MB";
}
function basicShadowMetricsCallback()
{
return " | Shadow |" @
" Active: " @ $BasicLightManagerStats::activePlugins @
" Updated: " @ $BasicLightManagerStats::shadowsUpdated @
" Elapsed Ms: " @ $BasicLightManagerStats::elapsedUpdateMs;
}
function lightMetricsCallback()
{
return " | Deferred Lights |" @
" Active: " @ $lightMetrics::activeLights @
" Culled: " @ $lightMetrics::culledLights;
}
function particleMetricsCallback()
{
return " | Particles |" @
" # Simulated " @ $particle::numSimulated;
}
function partMetricsCallback()
{
return particleMetricsCallback();
}
// alias
function audioMetricsCallback()
{
return sfxMetricsCallback();
}
// alias
function videoMetricsCallback()
{
return gfxMetricsCallback();
}
// Add a metrics HUD. %expr can be a vector of names where each element
// must have a corresponding '<name>MetricsCallback()' function defined
// that will be called on each update of the GUI control. The results
// of each function are stringed together.
//
// Example: metrics( "fps gfx" );
function metrics( %expr )
{
%metricsExpr = "";
if( %expr !$= "" )
{
for( %i = 0;; %i ++ )
{
%name = getWord( %expr, %i );
if( %name $= "" )
break;
else
{
%cb = %name @ "MetricsCallback";
if( !isFunction( %cb ) )
error( "metrics - undefined callback: " @ %cb );
else
{
%cb = %cb @ "()";
if( %i > 0 )
%metricsExpr = %metricsExpr @ " NL ";
%metricsExpr = %metricsExpr @ %cb;
}
}
}
if( %metricsExpr !$= "" )
%metricsExpr = %metricsExpr @ " @ \" \"";
}
if( %metricsExpr !$= "" )
{
$GameCanvas.pushDialog( FrameOverlayGui, 1000 );
TextOverlayControl.setValue( %metricsExpr );
}
else
$GameCanvas.popDialog(FrameOverlayGui);
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.Streams;
using Orleans.Streams.Core;
namespace Orleans.Providers.Streams.Common
{
[Serializable]
public enum PersistentStreamProviderState
{
None,
Initialized,
AgentsStarted,
AgentsStopped,
}
[Serializable]
public enum PersistentStreamProviderCommand
{
None,
StartAgents,
StopAgents,
GetAgentsState,
GetNumberRunningAgents,
AdapterCommandStartRange = 10000,
AdapterCommandEndRange = AdapterCommandStartRange + 9999,
AdapterFactoryCommandStartRange = AdapterCommandEndRange + 1,
AdapterFactoryCommandEndRange = AdapterFactoryCommandStartRange + 9999,
}
/// <summary>
/// Persistent stream provider that uses an adapter for persistence
/// </summary>
/// <typeparam name="TAdapterFactory"></typeparam>
public class PersistentStreamProvider<TAdapterFactory> : IInternalStreamProvider, IControllable, IStreamSubscriptionManagerRetriever
where TAdapterFactory : IQueueAdapterFactory, new()
{
private Logger logger;
private IQueueAdapterFactory adapterFactory;
private IStreamProviderRuntime providerRuntime;
private IQueueAdapter queueAdapter;
private IPersistentStreamPullingManager pullingAgentManager;
private PersistentStreamProviderConfig myConfig;
internal const string StartupStatePropertyName = "StartupState";
internal const PersistentStreamProviderState StartupStateDefaultValue = PersistentStreamProviderState.AgentsStarted;
private PersistentStreamProviderState startupState;
private readonly ProviderStateManager stateManager = new ProviderStateManager();
private SerializationManager serializationManager;
private IRuntimeClient runtimeClient;
private IStreamSubscriptionManager streamSubscriptionManager;
public string Name { get; private set; }
public bool IsRewindable { get { return queueAdapter.IsRewindable; } }
// this is a workaround until an IServiceProvider instance is used in the Orleans client
private class GrainFactoryServiceProvider : IServiceProvider
{
private readonly IStreamProviderRuntime providerRuntime;
public GrainFactoryServiceProvider(IStreamProviderRuntime providerRuntime)
{
this.providerRuntime = providerRuntime;
}
public object GetService(Type serviceType)
{
var service = providerRuntime.ServiceProvider?.GetService(serviceType);
if (service != null)
{
return service;
}
if (serviceType == typeof(IGrainFactory))
{
return providerRuntime.GrainFactory;
}
return null;
}
}
public async Task Init(string name, IProviderRuntime providerUtilitiesManager, IProviderConfiguration config)
{
if(!stateManager.PresetState(ProviderState.Initialized)) return;
if (String.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
if (providerUtilitiesManager == null) throw new ArgumentNullException("providerUtilitiesManager");
if (config == null) throw new ArgumentNullException("config");
Name = name;
providerRuntime = (IStreamProviderRuntime)providerUtilitiesManager;
logger = providerRuntime.GetLogger(this.GetType().Name);
adapterFactory = new TAdapterFactory();
// Temporary change, but we need GrainFactory inside ServiceProvider for now,
// so will change it back as soon as we have an action item to add GrainFactory to ServiceProvider.
adapterFactory.Init(config, Name, logger, new GrainFactoryServiceProvider(providerRuntime));
queueAdapter = await adapterFactory.CreateAdapter();
myConfig = new PersistentStreamProviderConfig(config);
this.serializationManager = this.providerRuntime.ServiceProvider.GetRequiredService<SerializationManager>();
this.runtimeClient = this.providerRuntime.ServiceProvider.GetRequiredService<IRuntimeClient>();
if (this.myConfig.PubSubType == StreamPubSubType.ExplicitGrainBasedAndImplicit
|| this.myConfig.PubSubType == StreamPubSubType.ExplicitGrainBasedOnly)
{
this.streamSubscriptionManager = this.providerRuntime.ServiceProvider
.GetService<IStreamSubscriptionManagerAdmin>().GetStreamSubscriptionManager(StreamSubscriptionManagerType.ExplicitSubscribeOnly);
}
string startup;
if (config.Properties.TryGetValue(StartupStatePropertyName, out startup))
{
if(!Enum.TryParse(startup, true, out startupState))
throw new ArgumentException(
String.Format("Unsupported value '{0}' for configuration parameter {1} of stream provider {2}.", startup, StartupStatePropertyName, config.Name));
}
else
startupState = StartupStateDefaultValue;
logger.Info("Initialized PersistentStreamProvider<{0}> with name {1}, Adapter {2} and config {3}, {4} = {5}.",
typeof(TAdapterFactory).Name,
Name,
queueAdapter.Name,
myConfig,
StartupStatePropertyName, startupState);
stateManager.CommitState();
}
public async Task Start()
{
if (!stateManager.PresetState(ProviderState.Started)) return;
if (queueAdapter.Direction.Equals(StreamProviderDirection.ReadOnly) ||
queueAdapter.Direction.Equals(StreamProviderDirection.ReadWrite))
{
var siloRuntime = providerRuntime as ISiloSideStreamProviderRuntime;
if (siloRuntime != null)
{
pullingAgentManager = await siloRuntime.InitializePullingAgents(Name, adapterFactory, queueAdapter, myConfig);
// TODO: No support yet for DeliveryDisabled, only Stopped and Started
if (startupState == PersistentStreamProviderState.AgentsStarted)
await pullingAgentManager.StartAgents();
}
}
stateManager.CommitState();
}
public IStreamSubscriptionManager GetStreamSubscriptionManager()
{
return this.streamSubscriptionManager;
}
public async Task Close()
{
if (!stateManager.PresetState(ProviderState.Closed)) return;
var siloRuntime = providerRuntime as ISiloSideStreamProviderRuntime;
if (siloRuntime != null)
{
await pullingAgentManager.Stop();
}
stateManager.CommitState();
}
public IAsyncStream<T> GetStream<T>(Guid id, string streamNamespace)
{
var streamId = StreamId.GetStreamId(id, Name, streamNamespace);
return providerRuntime.GetStreamDirectory().GetOrAddStream<T>(
streamId, () => new StreamImpl<T>(streamId, this, IsRewindable, this.runtimeClient));
}
IInternalAsyncBatchObserver<T> IInternalStreamProvider.GetProducerInterface<T>(IAsyncStream<T> stream)
{
if (queueAdapter.Direction == StreamProviderDirection.ReadOnly)
{
throw new InvalidOperationException($"Stream provider {queueAdapter.Name} is ReadOnly.");
}
return new PersistentStreamProducer<T>((StreamImpl<T>)stream, providerRuntime, queueAdapter, IsRewindable, this.serializationManager);
}
IInternalAsyncObservable<T> IInternalStreamProvider.GetConsumerInterface<T>(IAsyncStream<T> streamId)
{
return GetConsumerInterfaceImpl(streamId);
}
private IInternalAsyncObservable<T> GetConsumerInterfaceImpl<T>(IAsyncStream<T> stream)
{
return new StreamConsumer<T>((StreamImpl<T>)stream, Name, providerRuntime, providerRuntime.PubSub(myConfig.PubSubType), IsRewindable);
}
public Task<object> ExecuteCommand(int command, object arg)
{
if (command >= (int)PersistentStreamProviderCommand.AdapterCommandStartRange &&
command <= (int)PersistentStreamProviderCommand.AdapterCommandEndRange &&
queueAdapter is IControllable)
{
return ((IControllable)queueAdapter).ExecuteCommand(command, arg);
}
if (command >= (int)PersistentStreamProviderCommand.AdapterFactoryCommandStartRange &&
command <= (int)PersistentStreamProviderCommand.AdapterFactoryCommandEndRange &&
adapterFactory is IControllable)
{
return ((IControllable)adapterFactory).ExecuteCommand(command, arg);
}
if (pullingAgentManager != null)
{
return pullingAgentManager.ExecuteCommand((PersistentStreamProviderCommand)command, arg);
}
logger.Warn(0, String.Format("Got command {0} with arg {1}, but PullingAgentManager is not initialized yet. Ignoring the command.",
(PersistentStreamProviderCommand)command, arg != null ? arg.ToString() : "null"));
throw new ArgumentException("PullingAgentManager is not initialized yet.");
}
}
}
| |
using NBitcoin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using WalletWasabi.Helpers;
using WalletWasabi.Hwi.Exceptions;
using WalletWasabi.Hwi.Models;
namespace WalletWasabi.Hwi.Parsers
{
public static class HwiParser
{
public static bool TryParseErrors(string text, IEnumerable<HwiOption> options, [NotNullWhen(true)] out HwiException? error)
{
error = null;
if (JsonHelpers.TryParseJToken(text, out JToken? token) && TryParseError(token, out HwiException? e))
{
error = e;
}
else
{
var subString = "error:";
if (text.Contains(subString, StringComparison.OrdinalIgnoreCase))
{
int startIndex = text.IndexOf(subString, StringComparison.OrdinalIgnoreCase) + subString.Length;
var err = text[startIndex..];
error = new HwiException(HwiErrorCode.UnknownError, err);
}
}
// Help text has error in it, so if help command is requested, then don't throw the error.
// https://github.com/bitcoin-core/HWI/issues/252
if (error is { }
&& options is { }
&& options.Contains(HwiOption.Help)
&& error.ErrorCode == HwiErrorCode.HelpText)
{
error = null;
}
return error is { };
}
public static bool TryParseError(JToken token, [NotNullWhen(true)] out HwiException? error)
{
error = null;
if (token is JArray)
{
return false;
}
var errToken = token["error"];
var codeToken = token["code"];
var successToken = token["success"];
string err = "";
if (errToken is { })
{
err = Guard.Correct(errToken.Value<string>());
}
HwiErrorCode? code = null;
if (TryParseErrorCode(codeToken, out HwiErrorCode c))
{
code = c;
}
// HWI bug: it does not give error code.
// https://github.com/bitcoin-core/HWI/issues/216
else if (err == "Not initialized")
{
code = HwiErrorCode.DeviceNotInitialized;
}
if (code.HasValue)
{
error = new HwiException(code.Value, err);
}
else if (err.Length != 0)
{
error = new HwiException(HwiErrorCode.UnknownError, err);
}
else if (successToken is { } && successToken.Value<bool>() == false)
{
error = new HwiException(HwiErrorCode.UnknownError, "");
}
return error is { };
}
public static bool TryParseErrorCode(JToken codeToken, out HwiErrorCode code)
{
code = default;
if (codeToken is null)
{
return false;
}
try
{
var codeInt = codeToken.Value<int>();
if (Enum.IsDefined(typeof(HwiErrorCode), codeInt))
{
code = (HwiErrorCode)codeInt;
return true;
}
}
catch
{
return false;
}
return false;
}
public static bool TryParseHardwareWalletVendor(JToken token, out HardwareWalletModels vendor)
{
vendor = HardwareWalletModels.Unknown;
if (token is null)
{
return false;
}
try
{
var typeString = token.Value<string>();
if (Enum.TryParse(typeString, ignoreCase: true, out HardwareWalletModels t))
{
vendor = t;
return true;
}
}
catch
{
return false;
}
return false;
}
public static IEnumerable<HwiEnumerateEntry> ParseHwiEnumerateResponse(string responseString)
{
var jarr = JArray.Parse(responseString);
var response = new List<HwiEnumerateEntry>();
foreach (JObject json in jarr)
{
var hwiEntry = ParseHwiEnumerateEntry(json);
response.Add(hwiEntry);
}
return response;
}
public static ExtPubKey ParseExtPubKey(string json)
{
if (JsonHelpers.TryParseJToken(json, out JToken? token))
{
var extPubKeyString = token["xpub"]?.ToString().Trim();
var extPubKey = string.IsNullOrEmpty(extPubKeyString) ? null : NBitcoinHelpers.BetterParseExtPubKey(extPubKeyString);
return extPubKey;
}
else
{
throw new FormatException($"Could not parse extpubkey: {json}.");
}
}
public static BitcoinAddress ParseAddress(string json, Network network)
{
// HWI does not support regtest, so the parsing would fail here.
if (network == Network.RegTest)
{
network = Network.TestNet;
}
if (JsonHelpers.TryParseJToken(json, out JToken? token))
{
var addressString = token["address"]?.ToString()?.Trim() ?? null;
try
{
var address = BitcoinAddress.Create(addressString, network);
return address;
}
catch (FormatException)
{
BitcoinAddress.Create(addressString, network == Network.Main ? Network.TestNet : Network.Main);
throw new FormatException("Wrong network.");
}
}
else
{
throw new FormatException($"Could not parse address: {json}.");
}
}
public static PSBT ParsePsbt(string json, Network network)
{
// HWI does not support regtest, so the parsing would fail here.
if (network == Network.RegTest)
{
network = Network.TestNet;
}
if (JsonHelpers.TryParseJToken(json, out JToken? token))
{
var psbtString = token["psbt"]?.ToString()?.Trim() ?? null;
var psbt = PSBT.Parse(psbtString, network);
return psbt;
}
else
{
throw new FormatException($"Could not parse PSBT: {json}.");
}
}
public static HwiEnumerateEntry ParseHwiEnumerateEntry(JObject json)
{
JToken modelToken = json["model"];
var pathString = json["path"]?.ToString()?.Trim();
var serialNumberString = json["serial_number"]?.ToString()?.Trim();
var fingerprintString = json["fingerprint"]?.ToString()?.Trim();
var needsPinSentString = json["needs_pin_sent"]?.ToString()?.Trim();
var needsPassphraseSentString = json["needs_passphrase_sent"]?.ToString()?.Trim();
HDFingerprint? fingerprint = null;
if (fingerprintString is { })
{
if (HDFingerprint.TryParse(fingerprintString, out HDFingerprint fp))
{
fingerprint = fp;
}
else
{
throw new FormatException($"Could not parse fingerprint: {fingerprintString}");
}
}
bool? needsPinSent = null;
if (!string.IsNullOrEmpty(needsPinSentString))
{
needsPinSent = bool.Parse(needsPinSentString);
}
bool? needsPassphraseSent = null;
if (!string.IsNullOrEmpty(needsPassphraseSentString))
{
needsPassphraseSent = bool.Parse(needsPassphraseSentString);
}
HwiErrorCode? code = null;
string errorString = null;
if (TryParseError(json, out HwiException? err))
{
code = err.ErrorCode;
errorString = err.Message;
}
HardwareWalletModels model = HardwareWalletModels.Unknown;
if (TryParseHardwareWalletVendor(modelToken, out HardwareWalletModels t))
{
model = t;
}
return new HwiEnumerateEntry(
model: model,
path: pathString,
serialNumber: serialNumberString,
fingerprint: fingerprint,
needsPinSent: needsPinSent,
needsPassphraseSent: needsPassphraseSent,
error: errorString,
code: code);
}
public static string NormalizeRawDevicePath(string rawPath)
{
// There's some strangeness going on here.
// Seems like when we get a complex path like: "hid:\\\\\\\\?\\\\hid#vid_534c&pid_0001&mi_00#7&6f0b727&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}"
// While reading it out as the json, the duplicated \s are removed magically by newtonsoft.json.
// However the normalized path is accepted by HWI (not sure if the raw path is accepted also.)
return rawPath.Replace(@"\\", @"\");
}
public static bool TryParseVersion(string hwiResponse, [NotNullWhen(true)] out Version? version)
{
version = null;
try
{
version = ParseVersion(hwiResponse);
return true;
}
catch (Exception)
{
return false;
}
}
public static Version ParseVersion(string hwiResponse)
{
const string WinPrefix = "hwi.exe";
const string Prefix = "hwi";
// Order matters! https://github.com/zkSNACKs/WalletWasabi/pull/1905/commits/cecefcc50af140cc06cb93961cda86f9b21db11b
string prefixToTrim = hwiResponse.StartsWith(WinPrefix)
? WinPrefix
: hwiResponse.StartsWith(Prefix)
? Prefix
: null;
if (prefixToTrim is null)
{
throw new FormatException("HWI prefix is missing in the provided version response.");
}
hwiResponse = hwiResponse.TrimStart(prefixToTrim, StringComparison.InvariantCultureIgnoreCase).TrimEnd();
var onlyVersion = hwiResponse.Split("-")[0];
if (onlyVersion.Split('.').Length != 3)
{
throw new FormatException("Version must contain major.minor.build numbers.");
}
return Version.Parse(onlyVersion);
}
public static string ToArgumentString(Network network, IEnumerable<HwiOption> options, HwiCommands? command, string commandArguments)
{
options ??= Enumerable.Empty<HwiOption>();
var fullOptions = new List<HwiOption>(options);
if (network != Network.Main)
{
fullOptions.Insert(0, HwiOption.TestNet);
}
var optionsString = string.Join(" --", fullOptions.Select(x =>
{
string optionString;
if (x.Type == HwiOptions.DeviceType)
{
optionString = "device-type";
}
else if (x.Type == HwiOptions.DevicePath)
{
optionString = "device-path";
}
else
{
optionString = x.Type.ToString().ToLowerInvariant();
}
if (string.IsNullOrWhiteSpace(x.Arguments))
{
return optionString;
}
else
{
return $"{optionString} \"{x.Arguments}\"";
}
}));
optionsString = string.IsNullOrWhiteSpace(optionsString) ? "" : $"--{optionsString}";
var argumentBuilder = new StringBuilder(optionsString);
if (command is { })
{
if (argumentBuilder.Length != 0)
{
argumentBuilder.Append(' ');
}
argumentBuilder.Append(command.ToString().ToLowerInvariant());
}
commandArguments = Guard.Correct(commandArguments);
if (commandArguments.Length != 0)
{
argumentBuilder.Append(' ');
argumentBuilder.Append(commandArguments);
}
var arguments = argumentBuilder.ToString().Trim();
return arguments;
}
public static string ToHwiFriendlyString(this HardwareWalletModels me)
{
return me.ToString().ToLowerInvariant();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXORULE
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// Adapter of MS-OXORULE.
/// </summary>
public partial class MS_OXORULEAdapter : ManagedAdapterBase, IMS_OXORULEAdapter
{
#region Variables
/// <summary>
/// Indicate whether RPC connected.
/// </summary>
private bool isConnected = false;
/// <summary>
/// The OxcropsClient instance.
/// </summary>
private OxcropsClient oxcropsClient;
/// <summary>
/// The NSPIAdapter instance.
/// </summary>
private NSPIAdapter nspiAdapter;
/// <summary>
/// String server name.
/// </summary>
private string server;
/// <summary>
/// String user1 ESSDN.
/// </summary>
private string user1ESSDN;
/// <summary>
/// String user2 ESSDN.
/// </summary>
private string user2ESSDN;
/// <summary>
/// String domain name.
/// </summary>
private string domain;
/// <summary>
/// Mailbox guid value.
/// </summary>
private byte[] mailboxGUID;
/// <summary>
/// RPC raw data.
/// </summary>
private byte[] rawData;
/// <summary>
/// Response of ROP operation.
/// </summary>
private object response;
/// <summary>
/// Server objects handles.
/// </summary>
private List<List<uint>> responseSOHs;
/// <summary>
/// This enum is used to specify the ROP operation is performed on ExtendedRule, DAM, DEM or StandardRule.
/// </summary>
private TargetOfRop targetOfRop;
/// <summary>
/// Gets or sets indicate the Rop operation is performed for DAM, DEM or ExtendedRules.
/// </summary>
public TargetOfRop TargetOfRop
{
get { return this.targetOfRop; }
set { this.targetOfRop = value; }
}
#endregion
#region Defined in MS-OXORULE
/// <summary>
/// This ROP gets the rules table of a folder.
/// </summary>
/// <param name="objHandle">This index refers to the location in the Server object handle table used to find the handle for this operation.</param>
/// <param name="tableFlags">These Flags control the Type of table. The possible values are specified in [MS-OXORULE].</param>
/// <param name="getRulesTableResponse">Structure of RopGetRulesTableResponse.</param>
/// <returns>Table handle.</returns>
public uint RopGetRulesTable(uint objHandle, TableFlags tableFlags, out RopGetRulesTableResponse getRulesTableResponse)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopGetRulesTableRequest getRulesTableRequest;
getRulesTableRequest.RopId = 0x3F;
getRulesTableRequest.LogonId = 0x00;
getRulesTableRequest.InputHandleIndex = 0x00;
getRulesTableRequest.OutputHandleIndex = 0x01;
getRulesTableRequest.TableFlags = (byte)tableFlags;
this.responseSOHs = this.DoRPCCall(getRulesTableRequest, objHandle, ref this.response, ref this.rawData);
getRulesTableResponse = (RopGetRulesTableResponse)this.response;
uint tableHandle = this.responseSOHs[0][getRulesTableResponse.OutputHandleIndex];
// Verify the response of RopGetRulesTable
this.VerifyRopGetRulesTable(getRulesTableResponse, getRulesTableRequest);
return tableHandle;
}
/// <summary>
/// This ROP updates the entry IDs in the deferred action messages.
/// </summary>
/// <param name="objHandle">This index refers to the location in the Server object handle table used to find the handle for this operation.</param>
/// <param name="serverEntryId">This value specifies the ID of the message on the server.</param>
/// <param name="clientEntryId">This value specifies the ID of the downloaded message on the client.</param>
/// <returns>Structure of RopUpdateDeferredActionMessagesResponse.</returns>
public RopUpdateDeferredActionMessagesResponse RopUpdateDeferredActionMessages(uint objHandle, byte[] serverEntryId, byte[] clientEntryId)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopUpdateDeferredActionMessagesRequest updateDeferredActionMessagesRequest;
RopUpdateDeferredActionMessagesResponse updateDeferredActionMessagesResponse;
updateDeferredActionMessagesRequest.RopId = 0x57;
updateDeferredActionMessagesRequest.LogonId = 0x00;
updateDeferredActionMessagesRequest.InputHandleIndex = 0x00;
updateDeferredActionMessagesRequest.ServerEntryIdSize = 0;
if (serverEntryId != null)
{
updateDeferredActionMessagesRequest.ServerEntryIdSize = (ushort)serverEntryId.Length;
}
updateDeferredActionMessagesRequest.ServerEntryId = serverEntryId;
updateDeferredActionMessagesRequest.ClientEntryIdSize = 0;
if (clientEntryId != null)
{
updateDeferredActionMessagesRequest.ClientEntryIdSize = (ushort)clientEntryId.Length;
}
updateDeferredActionMessagesRequest.ClientEntryId = clientEntryId;
this.responseSOHs = this.DoRPCCall(updateDeferredActionMessagesRequest, objHandle, ref this.response, ref this.rawData);
updateDeferredActionMessagesResponse = (RopUpdateDeferredActionMessagesResponse)this.response;
return updateDeferredActionMessagesResponse;
}
/// <summary>
/// This ROP modifies the rules associated with a folder.
/// </summary>
/// <param name="objHandle">This index refers to the handle in the Server object handle table used as input for this operation.</param>
/// <param name="modifyRulesFlags">The possible values are specified in [MS-OXORULE]. These Flags specify behavior of this operation.</param>
/// <param name="ruleData">An array of RuleData structures, each of which specifies details about a standard rule.</param>
/// <returns>Structure of RopModifyRulesResponse.</returns>
public RopModifyRulesResponse RopModifyRules(uint objHandle, ModifyRuleFlag modifyRulesFlags, RuleData[] ruleData)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopModifyRulesRequest modifyRulesRequest;
RopModifyRulesResponse modifyRulesResponse;
modifyRulesRequest.RopId = 0x41;
modifyRulesRequest.LogonId = 0x0;
modifyRulesRequest.InputHandleIndex = 0x00;
modifyRulesRequest.ModifyRulesFlags = (byte)modifyRulesFlags;
modifyRulesRequest.RulesCount = 0;
if (ruleData != null)
{
modifyRulesRequest.RulesCount = (ushort)ruleData.Length;
}
modifyRulesRequest.RulesData = ruleData;
this.responseSOHs = this.DoRPCCall(modifyRulesRequest, objHandle, ref this.response, ref this.rawData);
modifyRulesResponse = (RopModifyRulesResponse)this.response;
// Verify the response of RopModifyRules
this.VerifyRopModifyRules(modifyRulesResponse, modifyRulesRequest);
// modifyRulesResponse.ReturnValue equals 0 means that RopModifyRules is successful.
// So the ruleDatas in modifyRulesRequest is correct.
if (modifyRulesResponse.ReturnValue == 0)
{
this.VerifyPropertiesInRuleData(ruleData[0]);
}
return modifyRulesResponse;
}
#endregion
/// <summary>
/// Initialize test environment
/// </summary>
/// <param name="testSite">Test Site.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
testSite.DefaultProtocolDocShortName = "MS-OXORULE";
Common.MergeConfiguration(this.Site);
this.server = Common.GetConfigurationPropertyValue(Constants.Server, this.Site);
this.user1ESSDN = Common.GetConfigurationPropertyValue(Constants.User1ESSDN, this.Site) + "\0";
this.domain = Common.GetConfigurationPropertyValue(Constants.Domain, this.Site);
this.user2ESSDN = Common.GetConfigurationPropertyValue(Constants.User2ESSDN, this.Site) + "\0";
this.oxcropsClient = new OxcropsClient(MapiContext.GetDefaultRpcContext(this.Site));
this.nspiAdapter = new NSPIAdapter(this.Site);
}
/// <summary>
/// Release RPC binding and destroy RPC context handle.
/// </summary>
public void CleanUp()
{
this.oxcropsClient.Disconnect();
}
/// <summary>
/// Create RPC connection.
/// </summary>
/// <param name="connectionType">The type of connection.</param>
/// <param name="userName">A string value indicates the domain account name that connects to server.</param>
/// <param name="userESSDN">A string that identifies user who is making the EcDoConnectEx call</param>
/// <param name="userPassword">A string value indicates the password of the user which is used.</param>
/// <returns>Identify if the connection has been established.</returns>
public bool Connect(ConnectionType connectionType, string userName, string userESSDN, string userPassword)
{
if (this.isConnected == true)
{
bool isDisconnect = this.oxcropsClient.Disconnect();
Site.Assert.IsTrue(isDisconnect, "The RPC connection should be disconnected!");
}
this.isConnected = this.oxcropsClient.Connect(this.server, connectionType, userESSDN, this.domain, userName, userPassword);
return this.isConnected;
}
/// <summary>
/// Get properties from NSPI table.
/// </summary>
/// <param name="server">Server address.</param>
/// <param name="userName">The value of user name.</param>
/// <param name="domain">The value of Domain.</param>
/// <param name="password">Password of the user.</param>
/// <param name="columns">PropertyTags to be query.</param>
/// <returns>Results in PropertyRowSet format.</returns>
public PropertyRowSet_r? GetRecipientInfo(string server, string userName, string domain, string password, PropertyTagArray_r? columns)
{
#region Call NspiBind method to initiate a session between the client and the server.
uint flags = 0;
STAT stat = new STAT();
stat.CodePage = 0x4e4; // Set a valid code page.
stat.TemplateLocale = 0x409; // Set a valid LCID.
stat.SortLocale = 0x409; // Set a valid LCID.
// Set value for serverGuid
FlatUID_r guid = new FlatUID_r
{
Ab = new byte[16]
};
FlatUID_r? serverGuid = guid;
ErrorCodeValue result = this.nspiAdapter.NspiBind(flags, stat, ref serverGuid);
Site.Assert.AreEqual<ErrorCodeValue>(ErrorCodeValue.Success, result, "NspiBind should return Success!");
#endregion
#region Call NspiQueryRows method to get the recipient information.
stat.ContainerID = 0; // Set the container id to the id of default global address book container
uint tableCount = 0;
uint[] table = null;
uint requestCount = 5000;
PropertyRowSet_r? propertyRowSet = null;
result = this.nspiAdapter.NspiQueryRows(flags, ref stat, tableCount, table, requestCount, columns, out propertyRowSet);
Site.Assert.AreEqual<ErrorCodeValue>(ErrorCodeValue.Success, result, "NspiQueryRows should return Success!");
#endregion
uint returnValue = this.nspiAdapter.NspiUnbind(0);
Site.Assert.AreEqual<uint>(1, returnValue, "NspiUnbind method should return 1 (Success).");
return propertyRowSet;
}
#region Related ROPs
/// <summary>
/// This ROP gets specific properties of a message.
/// </summary>
/// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param>
/// <param name="propertyTags">This field specifies the properties requested.</param>
/// <returns>Structure of RopGetPropertiesSpecificResponse.</returns>
public RopGetPropertiesSpecificResponse RopGetPropertiesSpecific(uint objHandle, PropertyTag[] propertyTags)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopGetPropertiesSpecificRequest getPropertiesSpecificRequest;
RopGetPropertiesSpecificResponse getPropertiesSpecificResponse;
getPropertiesSpecificRequest.RopId = 0x07;
getPropertiesSpecificRequest.LogonId = 0x00;
getPropertiesSpecificRequest.InputHandleIndex = 0x00;
getPropertiesSpecificRequest.PropertySizeLimit = 0x00;
getPropertiesSpecificRequest.WantUnicode = 0x01;
if (propertyTags != null)
{
getPropertiesSpecificRequest.PropertyTagCount = (ushort)propertyTags.Length;
}
else
{
getPropertiesSpecificRequest.PropertyTagCount = 0x00;
}
getPropertiesSpecificRequest.PropertyTags = propertyTags;
this.responseSOHs = this.DoRPCCall(getPropertiesSpecificRequest, objHandle, ref this.response, ref this.rawData);
getPropertiesSpecificResponse = (RopGetPropertiesSpecificResponse)this.response;
// The getPropertiesSpecificResponse.ReturnValue equals 0 means that this ROP is successful.
// So the propertyTags in getPropertiesSpecificRequest is correct
if (getPropertiesSpecificResponse.ReturnValue == 0)
{
this.VerifyPropertiesSpecific(propertyTags);
}
return getPropertiesSpecificResponse;
}
/// <summary>
/// This ROP adds or modifies recipients on a message.
/// </summary>
/// <param name="objHandle">Handle to operate.</param>
/// <param name="recipientColumns">Array of PropertyTag structures. The number of structures contained in this field is specified by the ColumnCount field. This field specifies the property values that can be included for each recipient.</param>
/// <param name="recipientRows">List of ModifyRecipientRow structures. The number of structures contained in this field is specified by the RowCount field. .</param>
/// <returns>Response of RopModifyRecipients.</returns>
public RopModifyRecipientsResponse RopModifyRecipients(uint objHandle, PropertyTag[] recipientColumns, ModifyRecipientRow[] recipientRows)
{
RopModifyRecipientsRequest modifyRecipientsRequest;
RopModifyRecipientsResponse modifyRecipientsResponse;
modifyRecipientsRequest.RopId = 0x0E;
modifyRecipientsRequest.LogonId = 0x00;
modifyRecipientsRequest.InputHandleIndex = 0x00;
modifyRecipientsRequest.ColumnCount = (ushort)recipientColumns.Length;
modifyRecipientsRequest.RecipientColumns = recipientColumns;
modifyRecipientsRequest.RowCount = (ushort)recipientRows.Length;
modifyRecipientsRequest.RecipientRows = recipientRows;
this.responseSOHs = this.DoRPCCall(modifyRecipientsRequest, objHandle, ref this.response, ref this.rawData);
modifyRecipientsResponse = (RopModifyRecipientsResponse)this.response;
return modifyRecipientsResponse;
}
/// <summary>
/// This ROP submits a message for sending.
/// </summary>
/// <param name="objHandle">Handle to operate.</param>
/// <param name="submitFlags">8-bit Flags structure. These Flags specify special behavior for submitting the message.</param>
/// <returns>Structure of RopSubmitMessageResponse.</returns>
public RopSubmitMessageResponse RopSubmitMessage(uint objHandle, SubmitFlag submitFlags)
{
RopSubmitMessageRequest submitMessageRequest;
RopSubmitMessageResponse submitMessageResponse;
submitMessageRequest.RopId = 0x32;
submitMessageRequest.LogonId = 0x00;
submitMessageRequest.InputHandleIndex = 0x00;
submitMessageRequest.SubmitFlags = (byte)submitFlags;
this.responseSOHs = this.DoRPCCall(submitMessageRequest, objHandle, ref this.response, ref this.rawData);
submitMessageResponse = (RopSubmitMessageResponse)this.response;
return submitMessageResponse;
}
/// <summary>
/// This ROP deletes specific properties on a message.
/// </summary>
/// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param>
/// <param name="propertyTags">Array of PropertyTag structures, this field specifies the property values to be deleted from the object.</param>
/// <returns>Structure of RopDeletePropertiesResponse.</returns>
public RopDeletePropertiesResponse RopDeleteProperties(uint objHandle, PropertyTag[] propertyTags)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopDeletePropertiesRequest deletePropertiesRequest;
RopDeletePropertiesResponse deletePropertiesResponse;
deletePropertiesRequest.RopId = 0x0B;
deletePropertiesRequest.LogonId = 0x0;
deletePropertiesRequest.InputHandleIndex = 0x00;
if (propertyTags != null)
{
deletePropertiesRequest.PropertyTagCount = (ushort)propertyTags.Length;
}
else
{
deletePropertiesRequest.PropertyTagCount = 0x00;
}
deletePropertiesRequest.PropertyTags = propertyTags;
this.responseSOHs = this.DoRPCCall(deletePropertiesRequest, objHandle, ref this.response, ref this.rawData);
deletePropertiesResponse = (RopDeletePropertiesResponse)this.response;
return deletePropertiesResponse;
}
/// <summary>
/// This ROP gets the contents table of a container.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <param name="tableFlags">8-bit Flags structure. These Flags control the Type of table.</param>+
/// <param name="tableHandle">Handle of contents table.</param>
/// <returns>Response of RopGetContentsTable.</returns>
public RopGetContentsTableResponse RopGetContentsTable(uint handle, ContentTableFlag tableFlags, out uint tableHandle)
{
RopGetContentsTableRequest getContentsTableRequest;
getContentsTableRequest.RopId = 0x05;
getContentsTableRequest.LogonId = 0x00;
getContentsTableRequest.InputHandleIndex = 0x00;
getContentsTableRequest.OutputHandleIndex = 0x01;
getContentsTableRequest.TableFlags = (byte)tableFlags;
this.responseSOHs = this.DoRPCCall(getContentsTableRequest, handle, ref this.response, ref this.rawData);
RopGetContentsTableResponse getContentsTableResponse = (RopGetContentsTableResponse)this.response;
tableHandle = this.responseSOHs[0][getContentsTableResponse.OutputHandleIndex];
return getContentsTableResponse;
}
/// <summary>
/// This ROP creates a new subfolder.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <param name="displayName">This value specifies the name of the created folder. .</param>
/// <param name="comment">This value specifies the folder comment that is associated with the created folder.</param>
/// <param name="createFolderResponse">Response of this ROP.</param>
/// <returns>Handle of new folder.</returns>
public uint RopCreateFolder(uint handle, string displayName, string comment, out RopCreateFolderResponse createFolderResponse)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopCreateFolderRequest createFolderRequest;
createFolderRequest.RopId = 0x1C;
createFolderRequest.LogonId = 0x0;
createFolderRequest.InputHandleIndex = 0x0;
createFolderRequest.OutputHandleIndex = 0x01;
// Generic folder
createFolderRequest.FolderType = 0x01;
// FALSE
createFolderRequest.UseUnicodeStrings = 0x0;
// non-zero(TRUE)
createFolderRequest.OpenExisting = 0xFF;
// FALSE
createFolderRequest.Reserved = 0x0;
createFolderRequest.DisplayName = Encoding.ASCII.GetBytes(displayName + "\0");
createFolderRequest.Comment = Encoding.ASCII.GetBytes(comment + "\0");
this.responseSOHs = this.DoRPCCall(createFolderRequest, handle, ref this.response, ref this.rawData);
createFolderResponse = (RopCreateFolderResponse)this.response;
uint folderHandle = this.responseSOHs[0][createFolderResponse.OutputHandleIndex];
return folderHandle;
}
/// <summary>
/// This ROP sets specific properties on a message.
/// </summary>
/// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param>
/// <param name="taggedPropertyValueArray">Array of TaggedPropertyValue structures, this field specifies the property values to be set on the object.</param>
/// <returns>Structure of RopSetPropertiesResponse.</returns>
public RopSetPropertiesResponse RopSetProperties(uint objHandle, TaggedPropertyValue[] taggedPropertyValueArray)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopSetPropertiesRequest setPropertiesRequest;
RopSetPropertiesResponse setPropertiesResponse;
setPropertiesRequest.RopId = 0x0A;
setPropertiesRequest.LogonId = 0x0;
setPropertiesRequest.InputHandleIndex = 0x00;
if (taggedPropertyValueArray != null)
{
setPropertiesRequest.PropertyValueCount = (ushort)taggedPropertyValueArray.Length;
ushort count = 2;
foreach (TaggedPropertyValue tagValue in taggedPropertyValueArray)
{
count += (ushort)(tagValue.Value.Length + 4);
}
setPropertiesRequest.PropertyValueSize = count;
}
else
{
setPropertiesRequest.PropertyValueCount = 0x00;
setPropertiesRequest.PropertyValueSize = 2;
}
setPropertiesRequest.PropertyValues = taggedPropertyValueArray;
this.responseSOHs = this.DoRPCCall(setPropertiesRequest, objHandle, ref this.response, ref this.rawData);
setPropertiesResponse = (RopSetPropertiesResponse)this.response;
return setPropertiesResponse;
}
/// <summary>
/// This ROP commits the changes made to a message.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <returns>Response of this ROP.</returns>
public RopSaveChangesMessageResponse RopSaveChangesMessage(uint handle)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopSaveChangesMessageRequest saveChangesMessageRequest;
RopSaveChangesMessageResponse saveChangesMessageResponse;
saveChangesMessageRequest.RopId = 0x0C;
saveChangesMessageRequest.LogonId = 0x0;
saveChangesMessageRequest.InputHandleIndex = 0x0;
saveChangesMessageRequest.ResponseHandleIndex = 0x01;
saveChangesMessageRequest.SaveFlags = 0x0C;
this.responseSOHs = this.DoRPCCall(saveChangesMessageRequest, handle, ref this.response, ref this.rawData);
saveChangesMessageResponse = (RopSaveChangesMessageResponse)this.response;
return saveChangesMessageResponse;
}
/// <summary>
/// This ROP gets all properties on a message.
/// </summary>
/// <param name="objHandle">This index specifies the location in the Server object handle table where the handle for the input Server object is stored.</param>
/// <param name="propertySizeLimit">This value specifies the maximum Size allowed for a property value returned.</param>
/// <param name="wantUnicode">This value specifies whether to return string properties in Unicode.</param>
/// <returns>Structure of RopGetPropertiesAllResponse.</returns>
public RopGetPropertiesAllResponse RopGetPropertiesAll(uint objHandle, ushort propertySizeLimit, ushort wantUnicode)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopGetPropertiesAllRequest getPropertiesAllRequest;
RopGetPropertiesAllResponse getPropertiesAllResponse;
getPropertiesAllRequest.RopId = 0x08;
getPropertiesAllRequest.LogonId = 0x0;
getPropertiesAllRequest.InputHandleIndex = 0x00;
getPropertiesAllRequest.PropertySizeLimit = propertySizeLimit;
getPropertiesAllRequest.WantUnicode = wantUnicode;
this.responseSOHs = this.DoRPCCall(getPropertiesAllRequest, objHandle, ref this.response, ref this.rawData);
getPropertiesAllResponse = (RopGetPropertiesAllResponse)this.response;
// The targetOfRop field indicates that where the Properties get from.
switch (this.targetOfRop)
{
// Verify ExtendedRule's Properties
case TargetOfRop.ForExtendedRules:
this.VerifyRopGetPropertiesAllForExtendedRules(getPropertiesAllResponse);
break;
// Verify DEM's Properties
case TargetOfRop.ForDEM:
this.VerifyRopGetPropertiesAllForDEM(getPropertiesAllResponse);
break;
}
return getPropertiesAllResponse;
}
/// <summary>
/// This ROP creates a Message object in a mailbox.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <param name="folderId">This value identifies the parent folder.</param>
/// <param name="isFAIMessage">8-bit Boolean. This value specifies whether the message is a folder associated information (FAI) message.</param>
/// <param name="createMessageResponse">Response of this ROP.</param>
/// <returns>Handle of the create message.</returns>
public uint RopCreateMessage(uint handle, ulong folderId, byte isFAIMessage, out RopCreateMessageResponse createMessageResponse)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopCreateMessageRequest req;
req.RopId = 0x06;
req.LogonId = 0;
req.InputHandleIndex = 0;
req.OutputHandleIndex = 1;
req.CodePageId = 0x0fff;
req.FolderId = folderId;
req.AssociatedFlag = isFAIMessage;
this.responseSOHs = this.DoRPCCall(req, handle, ref this.response, ref this.rawData);
createMessageResponse = (RopCreateMessageResponse)this.response;
return this.responseSOHs[0][createMessageResponse.OutputHandleIndex];
}
/// <summary>
/// This ROP opens an existing message in a mailbox.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <param name="folderId">64-bit identifier. This value identifies the parent folder of the message to be opened.</param>
/// <param name="messageId">64-bit identifier. This value identifies the message to be opened.</param>
/// <param name="openMessageResponse">Response of this ROP.</param>
/// <returns>Handle of the open message.</returns>
public uint RopOpenMessage(uint handle, ulong folderId, ulong messageId, out RopOpenMessageResponse openMessageResponse)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopOpenMessageRequest req;
req.RopId = 0x03;
req.LogonId = 0;
req.InputHandleIndex = 0;
req.OutputHandleIndex = 1;
// Use the same codepage as logon object used
req.CodePageId = 0x0fff;
req.FolderId = folderId;
// Read and write
req.OpenModeFlags = 0x01;
req.MessageId = messageId;
this.responseSOHs = this.DoRPCCall(req, handle, ref this.response, ref this.rawData);
openMessageResponse = (RopOpenMessageResponse)this.response;
return this.responseSOHs[0][openMessageResponse.OutputHandleIndex];
}
/// <summary>
/// This ROP logs on to a mailbox or public folder.
/// </summary>
/// <param name="logonType">This Type specifies ongoing action on the mailbox or public folder.</param>
/// <param name="userESSDN">A string that identifies the user to log on to the server.</param>
/// <param name="logonResponse">Response of this ROP.</param>
/// <returns>Handle of logon object.</returns>
public uint RopLogon(LogonType logonType, string userESSDN, out RopLogonResponse logonResponse)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopLogonRequest logonRequest;
uint objHandle1 = 0;
byte[] rawData1 = null;
object response1 = null;
List<List<uint>> responseSOHs1 = null;
logonRequest.RopId = 0xFE;
logonRequest.LogonId = 0x0;
logonRequest.OutputHandleIndex = 0x0;
logonRequest.StoreState = 0;
if (LogonType.PublicFolder == logonType)
{
// Logon to public folders
logonRequest.LogonFlags = 0x00;
// Logon to public folders
logonRequest.OpenFlags = 0x01000002;
logonRequest.EssdnSize = 0;
logonRequest.Essdn = null;
}
else
{
// Logon to a private mailbox
logonRequest.LogonFlags = 0x01;
// USE_PER_MDB_REPLID_MAPPING flag.
logonRequest.OpenFlags = 0x01000000;
if (userESSDN + "\0" == this.user1ESSDN)
{
logonRequest.EssdnSize = (ushort)Encoding.ASCII.GetByteCount(this.user1ESSDN);
logonRequest.Essdn = Encoding.ASCII.GetBytes(this.user1ESSDN);
}
else
{
logonRequest.EssdnSize = (ushort)Encoding.ASCII.GetByteCount(this.user2ESSDN);
logonRequest.Essdn = Encoding.ASCII.GetBytes(this.user2ESSDN);
}
}
responseSOHs1 = this.DoRPCCall(logonRequest, objHandle1, ref response1, ref rawData1);
logonResponse = (RopLogonResponse)response1;
this.mailboxGUID = logonResponse.MailboxGuid;
uint handle = responseSOHs1[0][logonResponse.OutputHandleIndex];
return handle;
}
/// <summary>
/// This ROP opens an existing folder in a mailbox.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <param name="folderId">64-bit identifier. This identifier specifies the folder to be opened.</param>
/// <param name="openFolderResponse">Response of this ROP.</param>
/// <returns>Handle of the open folder.</returns>
public uint RopOpenFolder(uint handle, ulong folderId, out RopOpenFolderResponse openFolderResponse)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopOpenFolderRequest openFolderRequest;
openFolderRequest.RopId = 0x02;
openFolderRequest.LogonId = 0x0;
openFolderRequest.InputHandleIndex = 0x0;
openFolderRequest.OutputHandleIndex = 0x01;
// Open Inbox here
openFolderRequest.FolderId = folderId;
// Opening an existing folder
openFolderRequest.OpenModeFlags = 0x0;
this.responseSOHs = this.DoRPCCall(openFolderRequest, handle, ref this.response, ref this.rawData);
openFolderResponse = (RopOpenFolderResponse)this.response;
uint openedFolderHandle = this.responseSOHs[0][openFolderResponse.OutputHandleIndex];
return openedFolderHandle;
}
/// <summary>
/// This ROP deletes all messages and subfolders from a folder.
/// </summary>
/// <param name="handle">Handle to operate.</param>
/// <param name="wantAsynchronous">8-bit Boolean. This value specifies whether the operation is to be executed asynchronously with status reported via RopProgress.</param>
/// <returns>Response of this ROP.</returns>
public RopEmptyFolderResponse RopEmptyFolder(uint handle, byte wantAsynchronous)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopEmptyFolderRequest emptyFolderRequest;
RopEmptyFolderResponse emptyFolderResponse;
emptyFolderRequest.RopId = 0x58;
emptyFolderRequest.LogonId = 0x00;
emptyFolderRequest.InputHandleIndex = 0x0;
// Synchronously
emptyFolderRequest.WantAsynchronous = wantAsynchronous;
// TRUE: delete all messages
emptyFolderRequest.WantDeleteAssociated = 0xFF;
this.responseSOHs = this.DoRPCCall(emptyFolderRequest, handle, ref this.response, ref this.rawData);
emptyFolderResponse = (RopEmptyFolderResponse)this.response;
return emptyFolderResponse;
}
/// <summary>
/// This ROP sets the properties visible on a table.
/// </summary>
/// <param name="objHandle">Handle to operate.</param>
/// <param name="setColumnsFlags">8-bit Flags structure. These Flags control this operation.</param>
/// <param name="propertyTags">Array of PropertyTag structures. This field specifies the property values that are visible in table rows.</param>
/// <returns>Response of this ROP.</returns>
public RopSetColumnsResponse RopSetColumns(uint objHandle, byte setColumnsFlags, PropertyTag[] propertyTags)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopSetColumnsRequest setColumnsRequest;
RopSetColumnsResponse setColumnsResponse;
setColumnsRequest.RopId = 0x12;
setColumnsRequest.LogonId = 0x00;
setColumnsRequest.InputHandleIndex = 0x00;
setColumnsRequest.SetColumnsFlags = setColumnsFlags;
setColumnsRequest.PropertyTagCount = 0;
if (propertyTags != null)
{
setColumnsRequest.PropertyTagCount = (ushort)propertyTags.Length;
}
setColumnsRequest.PropertyTags = propertyTags;
this.responseSOHs = this.DoRPCCall(setColumnsRequest, objHandle, ref this.response, ref this.rawData);
setColumnsResponse = (RopSetColumnsResponse)this.response;
return setColumnsResponse;
}
/// <summary>
/// This ROP retrieves rows from a table.
/// </summary>
/// <param name="objHandle">Handle to operate.</param>
/// <param name="queryRowsFlags">8-bit Flags structure. The possible values are specified in [MS-OXCTABL]. These Flags control this operation.</param>
/// <param name="forwardRead">8-bit Boolean. This value specifies the direction to read rows.</param>
/// <param name="rowCount">Unsigned 16-bit integer. This value specifies the number of requested rows.</param>
/// <returns>Response of this ROP.</returns>
public RopQueryRowsResponse RopQueryRows(uint objHandle, byte queryRowsFlags, byte forwardRead, ushort rowCount)
{
this.rawData = null;
this.response = null;
this.responseSOHs = null;
RopQueryRowsRequest queryRowsRequest;
RopQueryRowsResponse queryRowsResponse;
queryRowsRequest.RopId = 0x15;
queryRowsRequest.LogonId = 0x00;
queryRowsRequest.InputHandleIndex = 0x00;
queryRowsRequest.QueryRowsFlags = queryRowsFlags;
queryRowsRequest.ForwardRead = forwardRead;
queryRowsRequest.RowCount = rowCount;
this.responseSOHs = this.DoRPCCall(queryRowsRequest, objHandle, ref this.response, ref this.rawData);
queryRowsResponse = (RopQueryRowsResponse)this.response;
return queryRowsResponse;
}
/// <summary>
/// Get LongTermId from object id.
/// </summary>
/// <param name="objHandle">object handle.</param>
/// <param name="objId">Object id value.</param>
/// <returns>ROP response.</returns>
public RopLongTermIdFromIdResponse GetLongTermId(uint objHandle, ulong objId)
{
RopLongTermIdFromIdRequest longTermIdFromIdRequest = new RopLongTermIdFromIdRequest();
RopLongTermIdFromIdResponse longTermIdFromIdResponse = new RopLongTermIdFromIdResponse();
longTermIdFromIdRequest.InputHandleIndex = 0x00;
longTermIdFromIdRequest.LogonId = 0x00;
longTermIdFromIdRequest.RopId = 0x43;
longTermIdFromIdRequest.ObjectId = objId;
this.responseSOHs = this.DoRPCCall(longTermIdFromIdRequest, objHandle, ref this.response, ref this.rawData);
longTermIdFromIdResponse = (RopLongTermIdFromIdResponse)this.response;
return longTermIdFromIdResponse;
}
/// <summary>
/// Delete specific folder.
/// </summary>
/// <param name="objHandle">object handle .</param>
/// <param name="folderId">ID of the folder will be deleted.</param>
/// <returns>ROP response of RopDeleteFolder.</returns>
public RopDeleteFolderResponse RopDeleteFolder(uint objHandle, ulong folderId)
{
RopDeleteFolderRequest deleteFolderRequest = new RopDeleteFolderRequest();
RopDeleteFolderResponse deleteFolderResponse = new RopDeleteFolderResponse();
deleteFolderRequest.RopId = 0x1D;
deleteFolderRequest.LogonId = 0x00;
deleteFolderRequest.InputHandleIndex = 0x00;
// Delete all messages and subfolders
deleteFolderRequest.DeleteFolderFlags = 0x15;
// Folder to be deleted
deleteFolderRequest.FolderId = folderId;
this.responseSOHs = this.DoRPCCall(deleteFolderRequest, objHandle, ref this.response, ref this.rawData);
deleteFolderResponse = (RopDeleteFolderResponse)this.response;
return deleteFolderResponse;
}
/// <summary>
/// Release resources.
/// </summary>
/// <param name="handle">Unsigned integer value indicates the Server object Handle</param>
public void ReleaseRop(uint handle)
{
RopReleaseRequest relR = new RopReleaseRequest
{
InputHandleIndex = 0x00,
RopId = (byte)RopId.RopRelease,
LogonId = 0x00
};
this.responseSOHs = this.DoRPCCall(relR, handle, ref this.response, ref this.rawData);
}
#endregion
#region Help method
/// <summary>
/// Create Reply Template use settings in Util.cs file.
/// It will be used by create Rule of ActioType: OP_REPLY
/// </summary>
/// <param name="inboxFolderHandle">The inbox folder's handle.</param>
/// <param name="inboxFolderID">The inbox folder's ID.</param>
/// <param name="isOOFReplyTemplate">Indicate whether the template to be created is a template for OP_REPLY or OP_OOF_REPLY .</param>
/// <param name="templateSubject">The name of the template.</param>
/// <param name="addedProperties">The properties that need to add to the reply template.</param>
/// <param name="messageId">Message id of reply template message.</param>
/// <param name="messageHandler">The reply message Handler.</param>
/// <returns>Return the value of ReplyTemplateGUID.</returns>
public byte[] CreateReplyTemplate(uint inboxFolderHandle, ulong inboxFolderID, bool isOOFReplyTemplate, string templateSubject, TaggedPropertyValue[] addedProperties, out ulong messageId, out uint messageHandler)
{
// Create a new FAI message in the inbox folder
RopCreateMessageResponse ropCreateMessageResponse = new RopCreateMessageResponse();
messageHandler = this.RopCreateMessage(inboxFolderHandle, inboxFolderID, Convert.ToByte(true), out ropCreateMessageResponse);
#region Set the new created message's properties
TaggedPropertyValue[] replyTemplateProperties = new TaggedPropertyValue[3];
// PidTagMessageClass
replyTemplateProperties[0] = new TaggedPropertyValue();
PropertyTag replyTemplatePropertiesPropertyTag = new PropertyTag
{
PropertyType = (ushort)PropertyType.PtypString,
PropertyId = (ushort)PropertyId.PidTagMessageClass
};
replyTemplateProperties[0].PropertyTag = replyTemplatePropertiesPropertyTag;
if (isOOFReplyTemplate == true)
{
replyTemplateProperties[0].Value = Encoding.Unicode.GetBytes(Constants.OOFReplyTemplate + "\0");
}
else
{
replyTemplateProperties[0].Value = Encoding.Unicode.GetBytes(Constants.ReplyTemplate + "\0");
}
// PidTagReplyTemplateId
replyTemplateProperties[1] = new TaggedPropertyValue();
PropertyTag pidTagReplyTemplateIdPropertyTag = new PropertyTag
{
PropertyId = (ushort)PropertyId.PidTagReplyTemplateId,
PropertyType = (ushort)PropertyType.PtypBinary
};
replyTemplateProperties[1].PropertyTag = pidTagReplyTemplateIdPropertyTag;
Guid newGuid = System.Guid.NewGuid();
replyTemplateProperties[1].Value = Common.AddInt16LengthBeforeBinaryArray(newGuid.ToByteArray());
// PidTagSubject
replyTemplateProperties[2] = new TaggedPropertyValue();
PropertyTag pidTagSubjectPropertyTag = new PropertyTag
{
PropertyId = (ushort)PropertyId.PidTagSubject,
PropertyType = (ushort)PropertyType.PtypString
};
replyTemplateProperties[2].PropertyTag = pidTagSubjectPropertyTag;
replyTemplateProperties[2].Value = Encoding.Unicode.GetBytes(templateSubject + "\0");
this.RopSetProperties(messageHandler, replyTemplateProperties);
this.RopSetProperties(messageHandler, addedProperties);
#endregion
// Save changes of the message
RopSaveChangesMessageResponse ropSaveChangesMessagResponse = this.RopSaveChangesMessage(messageHandler);
messageId = ropSaveChangesMessagResponse.MessageId;
return newGuid.ToByteArray();
}
/// <summary>
/// Query properties in contents table.
/// </summary>
/// <param name="tableHandle">Handle of a specific contents table.</param>
/// <param name="propertyTags">Array of PropertyTag structures. This field specifies the property values that are visible in table rows.</param>
/// <returns>Response of this query rows.</returns>
public RopQueryRowsResponse QueryPropertiesInTable(uint tableHandle, PropertyTag[] propertyTags)
{
// Set the properties in propertyTags to be visible.
RopSetColumnsResponse setColumnsResponse = this.RopSetColumns(tableHandle, 0x00, propertyTags);
// Query properties values specified in propertyTags.
RopQueryRowsResponse queryRowsResponse = this.RopQueryRows(tableHandle, 0x00, 0x01, 1000);
// That the two Rops are successful means that the propertyTags in request is correct
if (setColumnsResponse.ReturnValue == 0 && queryRowsResponse.ReturnValue == 0 && queryRowsResponse.RowData.PropertyRows != null)
{
// Verify PropertyTags
this.VerifyPropertiesInTable(propertyTags, queryRowsResponse);
for (int i = 0; i < propertyTags.Length; i++)
{
// If the property queried is PidTagRuleActions
if (propertyTags[i].PropertyId == (ushort)PropertyId.PidTagRuleActions)
{
for (int j = 0; j < queryRowsResponse.RowData.PropertyRows.Count; j++)
{
// Verify structure RuleAction
RuleAction ruleAction = new RuleAction();
ruleAction.Deserialize(queryRowsResponse.RowData.PropertyRows[j].PropertyValues[i].Value);
this.VerifyRuleAction(ruleAction);
}
}
// If the property queried is PidTagExtendedRuleMessageActions
if (propertyTags[i].PropertyId == (ushort)PropertyId.PidTagExtendedRuleMessageActions)
{
for (int j = 0; j < queryRowsResponse.RowData.PropertyRows.Count; j++)
{
if (BitConverter.ToUInt32(queryRowsResponse.RowData.PropertyRows[j].PropertyValues[i].Value, 0) != (uint)ErrorCodeValue.NotFound)
{
// Verify structure RuleAction
ExtendedRuleActions ruleAction = new ExtendedRuleActions();
byte[] extendedRuleMessageActionBuffer = new byte[queryRowsResponse.RowData.PropertyRows[j].PropertyValues[i].Value.Length - 2];
Array.Copy(queryRowsResponse.RowData.PropertyRows[j].PropertyValues[i].Value, 2, extendedRuleMessageActionBuffer, 0, queryRowsResponse.RowData.PropertyRows[j].PropertyValues[i].Value.Length - 2);
ruleAction.Deserialize(extendedRuleMessageActionBuffer);
this.VerifyExtendRuleAction(ruleAction.RuleActionBuffer);
}
}
}
}
}
return queryRowsResponse;
}
/// <summary>
/// Get notification detail from server.
/// </summary>
/// <returns>Notify ROP response.</returns>
public RopNotifyResponse NotificationProcess()
{
List<IDeserializable> responseRops = new List<IDeserializable>();
RopNotifyResponse notifyResponse = new RopNotifyResponse();
uint ret = this.oxcropsClient.RopCall(null, null, ref responseRops, ref this.responseSOHs, ref this.rawData, 0x10008);
Site.Assert.AreEqual<uint>(OxcRpcErrorCode.ECNone, ret, "ROP call should be successful here, the error code is: {0}", ret);
foreach (IDeserializable response in responseRops)
{
string responseName = response.GetType().Name;
if (responseName == Constants.NameOfRopNotifyResponse)
{
notifyResponse = (RopNotifyResponse)response;
break;
}
}
return notifyResponse;
}
/// <summary>
/// Get folder EntryID bytes array.
/// </summary>
/// <param name="storeObjectType">Identify the store object is a mailbox or a public folder.</param>
/// <param name="objHandle">Logon handle.</param>
/// <param name="folderid">Folder id value.</param>
/// <returns>Folder EntryID bytes array.</returns>
public byte[] GetFolderEntryId(StoreObjectType storeObjectType, uint objHandle, ulong folderid)
{
// Get folder longterm id.
RopLongTermIdFromIdResponse longTermIdFromId = this.GetLongTermId(objHandle, folderid);
FolderEntryID folderEntryId;
if (storeObjectType == StoreObjectType.Mailbox)
{
folderEntryId = new FolderEntryID(storeObjectType, this.mailboxGUID, longTermIdFromId.LongTermId.DatabaseGuid, longTermIdFromId.LongTermId.GlobalCounter);
}
else
{
byte[] providerUID = new byte[] { 0x1A, 0x44, 0x73, 0x90, 0xAA, 0x66, 0x11, 0xCD, 0x9B, 0xC8, 0x00, 0xAA, 0x00, 0x2F, 0xC4, 0x5A };
folderEntryId = new FolderEntryID(storeObjectType, providerUID, longTermIdFromId.LongTermId.DatabaseGuid, longTermIdFromId.LongTermId.GlobalCounter);
}
this.VerifyFolderEntryID(folderEntryId, storeObjectType);
return folderEntryId.Serialize();
}
/// <summary>
/// Get message EntryID bytes array.
/// </summary>
/// <param name="folderHandle">Folder handle which the message exist.</param>
/// <param name="folderId">Folder id value.</param>
/// <param name="messageHandle">message handle.</param>
/// <param name="messageId">Message id value.</param>
/// <returns>Message EntryID bytes array.</returns>
public byte[] GetMessageEntryId(uint folderHandle, ulong folderId, uint messageHandle, ulong messageId)
{
// Get the message longterm ID.
RopLongTermIdFromIdResponse ropLongTermIdOfMessage = this.GetLongTermId(messageHandle, messageId);
// Get inbox folder's longterm ID.
RopLongTermIdFromIdResponse ropLongTermIdOfInboxFolder = this.GetLongTermId(folderHandle, folderId);
MessageEntryID messageEntryId;
// Get message's entry ID.
messageEntryId = new MessageEntryID(this.mailboxGUID, ropLongTermIdOfInboxFolder.LongTermId.DatabaseGuid, ropLongTermIdOfInboxFolder.LongTermId.GlobalCounter, ropLongTermIdOfMessage.LongTermId.DatabaseGuid, ropLongTermIdOfMessage.LongTermId.GlobalCounter);
this.VerifyMessageEntryID(messageEntryId);
return messageEntryId.Serialize();
}
#endregion
#region Private method
/// <summary>
/// Process and send ROP request.
/// </summary>
/// <param name="ropRequest">ROP request objects.</param>
/// <param name="objHandle">Server object handle in request.</param>
/// <param name="response">ROP response objects.</param>
/// <param name="rawData">The ROP response payload.</param>
/// <returns>Server objects handles in response.</returns>
private List<List<uint>> DoRPCCall(ISerializable ropRequest, uint objHandle, ref object response, ref byte[] rawData)
{
List<ISerializable> requestRops = new List<ISerializable>
{
ropRequest
};
List<uint> requestSOH = new List<uint>
{
objHandle
};
if (Common.IsOutputHandleInRopRequest(ropRequest))
{
// Add an element for server output object handle, set default value to 0xFFFFFFFF.
requestSOH.Add(0xFFFFFFFF);
}
List<IDeserializable> responseRops = new List<IDeserializable>();
List<List<uint>> responseSOHs = new List<List<uint>>();
// 0x10008 specifies the maximum size of the rgbOut buffer to place in Response.
uint ret = this.oxcropsClient.RopCall(requestRops, requestSOH, ref responseRops, ref responseSOHs, ref rawData, 0x10008);
Site.Assert.AreEqual<uint>(OxcRpcErrorCode.ECNone, ret, "ROP call should be successful here, the error code is: {0}", ret);
if (responseRops.Count != 0)
{
response = responseRops[0];
}
this.VerifyMAPITransport();
return responseSOHs;
}
#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 OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
/**
* @brief Wrapper class for ILGenerator.
* It writes the object code to a file and can then make real ILGenerator calls
* based on the file's contents.
*/
namespace OpenSim.Region.ScriptEngine.Yengine
{
public enum ScriptObjWriterCode: byte
{
BegMethod, EndMethod, TheEnd,
DclLabel, DclLocal, DclMethod, MarkLabel,
EmitNull, EmitField, EmitLocal, EmitType, EmitLabel, EmitMethodExt,
EmitMethodInt, EmitCtor, EmitDouble, EmitFloat, EmitInteger, EmitString,
EmitLabels,
BegExcBlk, BegCatBlk, BegFinBlk, EndExcBlk
}
public class ScriptObjWriter: ScriptMyILGen
{
private static Dictionary<short, OpCode> opCodes = PopulateOpCodes();
private static Dictionary<string, Type> string2Type = PopulateS2T();
private static Dictionary<Type, string> type2String = PopulateT2S();
private static MethodInfo monoGetCurrentOffset = typeof(ILGenerator).GetMethod("Mono_GetCurrentOffset",
BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null,
new Type[] { typeof(ILGenerator) }, null);
private static readonly OpCode[] opCodesLdcI4M1P8 = new OpCode[] {
OpCodes.Ldc_I4_M1, OpCodes.Ldc_I4_0, OpCodes.Ldc_I4_1, OpCodes.Ldc_I4_2, OpCodes.Ldc_I4_3,
OpCodes.Ldc_I4_4, OpCodes.Ldc_I4_5, OpCodes.Ldc_I4_6, OpCodes.Ldc_I4_7, OpCodes.Ldc_I4_8
};
private BinaryWriter objFileWriter;
private string lastErrorAtFile = "";
private int lastErrorAtLine = 0;
private int lastErrorAtPosn = 0;
private Dictionary<Type, string> sdTypesRev = new Dictionary<Type, string>();
public int labelNumber = 0;
public int localNumber = 0;
private string _methName;
public string methName
{
get
{
return _methName;
}
}
public Type retType;
public Type[] argTypes;
/**
* @brief Begin function declaration
* @param sdTypes = script-defined types
* @param methName = name of the method being declared, eg, "Verify(array,list,string)"
* @param retType = its return value type
* @param argTypes[] = its argument types
* @param objFileWriter = file to write its object code to
*
* After calling this function, the following functions should be called:
* this.BegMethod ();
* this.<as required> ();
* this.EndMethod ();
*
* The design of this object is such that many constructors may be called,
* but once a BegMethod() is called for one of the objects, no method may
* called for any of the other objects until EndMethod() is called (or it
* would break up the object stream for that method). But we need to have
* many constructors possible so we get function headers at the beginning
* of the object file in case there are forward references to the functions.
*/
public ScriptObjWriter(TokenScript tokenScript, string methName, Type retType, Type[] argTypes, string[] argNames, BinaryWriter objFileWriter)
{
this._methName = methName;
this.retType = retType;
this.argTypes = argTypes;
this.objFileWriter = objFileWriter;
// Build list that translates system-defined types to script defined types.
foreach(TokenDeclSDType sdt in tokenScript.sdSrcTypesValues)
{
Type sys = sdt.GetSysType();
if(sys != null)
sdTypesRev[sys] = sdt.longName.val;
}
// This tells the reader to call 'new DynamicMethod()' to create
// the function header. Then any forward reference calls to this
// method will have a MethodInfo struct to call.
objFileWriter.Write((byte)ScriptObjWriterCode.DclMethod);
objFileWriter.Write(methName);
objFileWriter.Write(GetStrFromType(retType));
int nArgs = argTypes.Length;
objFileWriter.Write(nArgs);
for(int i = 0; i < nArgs; i++)
{
objFileWriter.Write(GetStrFromType(argTypes[i]));
objFileWriter.Write(argNames[i]);
}
}
/**
* @brief Begin outputting object code for the function
*/
public void BegMethod()
{
// This tells the reader to call methodInfo.GetILGenerator()
// so it can start writing CIL code for the method.
objFileWriter.Write((byte)ScriptObjWriterCode.BegMethod);
objFileWriter.Write(methName);
}
/**
* @brief End of object code for the function
*/
public void EndMethod()
{
// This tells the reader that all code for the method has
// been written and so it will typically call CreateDelegate()
// to finalize the method and create an entrypoint.
objFileWriter.Write((byte)ScriptObjWriterCode.EndMethod);
objFileWriter = null;
}
/**
* @brief Declare a local variable for use by the function
*/
public ScriptMyLocal DeclareLocal(Type type, string name)
{
ScriptMyLocal myLocal = new ScriptMyLocal();
myLocal.type = type;
myLocal.name = name;
myLocal.number = localNumber++;
myLocal.isReferenced = true; // so ScriptCollector won't optimize references away
return DeclareLocal(myLocal);
}
public ScriptMyLocal DeclareLocal(ScriptMyLocal myLocal)
{
objFileWriter.Write((byte)ScriptObjWriterCode.DclLocal);
objFileWriter.Write(myLocal.number);
objFileWriter.Write(myLocal.name);
objFileWriter.Write(GetStrFromType(myLocal.type));
return myLocal;
}
/**
* @brief Define a label for use by the function
*/
public ScriptMyLabel DefineLabel(string name)
{
ScriptMyLabel myLabel = new ScriptMyLabel();
myLabel.name = name;
myLabel.number = labelNumber++;
return DefineLabel(myLabel);
}
public ScriptMyLabel DefineLabel(ScriptMyLabel myLabel)
{
objFileWriter.Write((byte)ScriptObjWriterCode.DclLabel);
objFileWriter.Write(myLabel.number);
objFileWriter.Write(myLabel.name);
return myLabel;
}
/**
* @brief try/catch blocks.
*/
public void BeginExceptionBlock()
{
objFileWriter.Write((byte)ScriptObjWriterCode.BegExcBlk);
}
public void BeginCatchBlock(Type excType)
{
objFileWriter.Write((byte)ScriptObjWriterCode.BegCatBlk);
objFileWriter.Write(GetStrFromType(excType));
}
public void BeginFinallyBlock()
{
objFileWriter.Write((byte)ScriptObjWriterCode.BegFinBlk);
}
public void EndExceptionBlock()
{
objFileWriter.Write((byte)ScriptObjWriterCode.EndExcBlk);
}
public void Emit(Token errorAt, OpCode opcode)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitNull);
WriteOpCode(errorAt, opcode);
}
public void Emit(Token errorAt, OpCode opcode, FieldInfo field)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitField);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(GetStrFromType(field.ReflectedType));
objFileWriter.Write(field.Name);
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLocal myLocal)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitLocal);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(myLocal.number);
}
public void Emit(Token errorAt, OpCode opcode, Type type)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitType);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(GetStrFromType(type));
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel myLabel)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitLabel);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(myLabel.number);
}
public void Emit(Token errorAt, OpCode opcode, ScriptMyLabel[] myLabels)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitLabels);
WriteOpCode(errorAt, opcode);
int nLabels = myLabels.Length;
objFileWriter.Write(nLabels);
for(int i = 0; i < nLabels; i++)
{
objFileWriter.Write(myLabels[i].number);
}
}
public void Emit(Token errorAt, OpCode opcode, ScriptObjWriter method)
{
if(method == null)
throw new ArgumentNullException("method");
objFileWriter.Write((byte)ScriptObjWriterCode.EmitMethodInt);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(method.methName);
}
public void Emit(Token errorAt, OpCode opcode, MethodInfo method)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitMethodExt);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(method.Name);
objFileWriter.Write(GetStrFromType(method.ReflectedType));
ParameterInfo[] parms = method.GetParameters();
int nArgs = parms.Length;
objFileWriter.Write(nArgs);
for(int i = 0; i < nArgs; i++)
{
objFileWriter.Write(GetStrFromType(parms[i].ParameterType));
}
}
public void Emit(Token errorAt, OpCode opcode, ConstructorInfo ctor)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitCtor);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(GetStrFromType(ctor.ReflectedType));
ParameterInfo[] parms = ctor.GetParameters();
int nArgs = parms.Length;
objFileWriter.Write(nArgs);
for(int i = 0; i < nArgs; i++)
{
objFileWriter.Write(GetStrFromType(parms[i].ParameterType));
}
}
public void Emit(Token errorAt, OpCode opcode, double value)
{
if(opcode != OpCodes.Ldc_R8)
{
throw new Exception("bad opcode " + opcode.ToString());
}
objFileWriter.Write((byte)ScriptObjWriterCode.EmitDouble);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(value);
}
public void Emit(Token errorAt, OpCode opcode, float value)
{
if(opcode != OpCodes.Ldc_R4)
{
throw new Exception("bad opcode " + opcode.ToString());
}
objFileWriter.Write((byte)ScriptObjWriterCode.EmitFloat);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(value);
}
public void Emit(Token errorAt, OpCode opcode, int value)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitInteger);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(value);
}
public void Emit(Token errorAt, OpCode opcode, string value)
{
objFileWriter.Write((byte)ScriptObjWriterCode.EmitString);
WriteOpCode(errorAt, opcode);
objFileWriter.Write(value);
}
/**
* @brief Declare that the target of a label is the next instruction.
*/
public void MarkLabel(ScriptMyLabel myLabel)
{
objFileWriter.Write((byte)ScriptObjWriterCode.MarkLabel);
objFileWriter.Write(myLabel.number);
}
/**
* @brief Write end-of-file marker to binary file.
*/
public static void TheEnd(BinaryWriter objFileWriter)
{
objFileWriter.Write((byte)ScriptObjWriterCode.TheEnd);
}
/**
* @brief Take an object file created by ScriptObjWriter() and convert it to a series of dynamic methods.
* @param sdTypes = script-defined types
* @param objReader = where to read object file from (as written by ScriptObjWriter above).
* @param scriptObjCode.EndMethod = called for each method defined at the end of the methods definition
* @param objectTokens = write disassemble/decompile data (or null if not wanted)
*/
public static void CreateObjCode(Dictionary<string, TokenDeclSDType> sdTypes, BinaryReader objReader,
ScriptObjCode scriptObjCode, ObjectTokens objectTokens)
{
Dictionary<string, DynamicMethod> methods = new Dictionary<string, DynamicMethod>();
DynamicMethod method = null;
ILGenerator ilGen = null;
Dictionary<int, Label> labels = new Dictionary<int, Label>();
Dictionary<int, LocalBuilder> locals = new Dictionary<int, LocalBuilder>();
Dictionary<int, string> labelNames = new Dictionary<int, string>();
Dictionary<int, string> localNames = new Dictionary<int, string>();
object[] ilGenArg = new object[1];
int offset = 0;
Dictionary<int, ScriptSrcLoc> srcLocs = null;
string srcFile = "";
int srcLine = 0;
int srcPosn = 0;
while(true)
{
// Get IL instruction offset at beginning of instruction.
offset = 0;
if((ilGen != null) && (monoGetCurrentOffset != null))
{
offset = (int)monoGetCurrentOffset.Invoke(null, ilGenArg);
}
// Read and decode next internal format code from input file (.xmrobj file).
ScriptObjWriterCode code = (ScriptObjWriterCode)objReader.ReadByte();
switch(code)
{
// Reached end-of-file so we are all done.
case ScriptObjWriterCode.TheEnd:
return;
// Beginning of method's contents.
// Method must have already been declared via DclMethod
// so all we need is its name to retrieve from methods[].
case ScriptObjWriterCode.BegMethod:
{
string methName = objReader.ReadString();
method = methods[methName];
ilGen = method.GetILGenerator();
ilGenArg[0] = ilGen;
labels.Clear();
locals.Clear();
labelNames.Clear();
localNames.Clear();
srcLocs = new Dictionary<int, ScriptSrcLoc>();
if(objectTokens != null)
objectTokens.BegMethod(method);
break;
}
// End of method's contents (ie, an OpCodes.Ret was probably just output).
// Call the callback to tell it the method is complete, and it can do whatever
// it wants with the method.
case ScriptObjWriterCode.EndMethod:
{
ilGen = null;
ilGenArg[0] = null;
scriptObjCode.EndMethod(method, srcLocs);
srcLocs = null;
if(objectTokens != null)
objectTokens.EndMethod();
break;
}
// Declare a label for branching to.
case ScriptObjWriterCode.DclLabel:
{
int number = objReader.ReadInt32();
string name = objReader.ReadString();
labels.Add(number, ilGen.DefineLabel());
labelNames.Add(number, name + "_" + number.ToString());
if(objectTokens != null)
objectTokens.DefineLabel(number, name);
break;
}
// Declare a local variable to store into.
case ScriptObjWriterCode.DclLocal:
{
int number = objReader.ReadInt32();
string name = objReader.ReadString();
string type = objReader.ReadString();
Type syType = GetTypeFromStr(sdTypes, type);
locals.Add(number, ilGen.DeclareLocal(syType));
localNames.Add(number, name + "_" + number.ToString());
if(objectTokens != null)
objectTokens.DefineLocal(number, name, type, syType);
break;
}
// Declare a method that will subsequently be defined.
// We create the DynamicMethod object at this point in case there
// are forward references from other method bodies.
case ScriptObjWriterCode.DclMethod:
{
string methName = objReader.ReadString();
Type retType = GetTypeFromStr(sdTypes, objReader.ReadString());
int nArgs = objReader.ReadInt32();
Type[] argTypes = new Type[nArgs];
string[] argNames = new string[nArgs];
for(int i = 0; i < nArgs; i++)
{
argTypes[i] = GetTypeFromStr(sdTypes, objReader.ReadString());
argNames[i] = objReader.ReadString();
}
methods.Add(methName, new DynamicMethod(methName, retType, argTypes));
if(objectTokens != null)
objectTokens.DefineMethod(methName, retType, argTypes, argNames);
break;
}
// Mark a previously declared label at this spot.
case ScriptObjWriterCode.MarkLabel:
{
int number = objReader.ReadInt32();
ilGen.MarkLabel(labels[number]);
if(objectTokens != null)
objectTokens.MarkLabel(offset, number);
break;
}
// Try/Catch blocks.
case ScriptObjWriterCode.BegExcBlk:
{
ilGen.BeginExceptionBlock();
if(objectTokens != null)
objectTokens.BegExcBlk(offset);
break;
}
case ScriptObjWriterCode.BegCatBlk:
{
Type excType = GetTypeFromStr(sdTypes, objReader.ReadString());
ilGen.BeginCatchBlock(excType);
if(objectTokens != null)
objectTokens.BegCatBlk(offset, excType);
break;
}
case ScriptObjWriterCode.BegFinBlk:
{
ilGen.BeginFinallyBlock();
if(objectTokens != null)
objectTokens.BegFinBlk(offset);
break;
}
case ScriptObjWriterCode.EndExcBlk:
{
ilGen.EndExceptionBlock();
if(objectTokens != null)
objectTokens.EndExcBlk(offset);
break;
}
// Emit an opcode with no operand.
case ScriptObjWriterCode.EmitNull:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode);
if(objectTokens != null)
objectTokens.EmitNull(offset, opCode);
break;
}
// Emit an opcode with a FieldInfo operand.
case ScriptObjWriterCode.EmitField:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
Type reflectedType = GetTypeFromStr(sdTypes, objReader.ReadString());
string fieldName = objReader.ReadString();
FieldInfo field = reflectedType.GetField(fieldName);
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, field);
if(objectTokens != null)
objectTokens.EmitField(offset, opCode, field);
break;
}
// Emit an opcode with a LocalBuilder operand.
case ScriptObjWriterCode.EmitLocal:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
int number = objReader.ReadInt32();
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, locals[number]);
if(objectTokens != null)
objectTokens.EmitLocal(offset, opCode, number);
break;
}
// Emit an opcode with a Type operand.
case ScriptObjWriterCode.EmitType:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
string name = objReader.ReadString();
Type type = GetTypeFromStr(sdTypes, name);
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, type);
if(objectTokens != null)
objectTokens.EmitType(offset, opCode, type);
break;
}
// Emit an opcode with a Label operand.
case ScriptObjWriterCode.EmitLabel:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
int number = objReader.ReadInt32();
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, labels[number]);
if(objectTokens != null)
objectTokens.EmitLabel(offset, opCode, number);
break;
}
// Emit an opcode with a Label array operand.
case ScriptObjWriterCode.EmitLabels:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
int nLabels = objReader.ReadInt32();
Label[] lbls = new Label[nLabels];
int[] nums = new int[nLabels];
for(int i = 0; i < nLabels; i++)
{
nums[i] = objReader.ReadInt32();
lbls[i] = labels[nums[i]];
}
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, lbls);
if(objectTokens != null)
objectTokens.EmitLabels(offset, opCode, nums);
break;
}
// Emit an opcode with a MethodInfo operand (such as a call) of an external function.
case ScriptObjWriterCode.EmitMethodExt:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
string methName = objReader.ReadString();
Type methType = GetTypeFromStr(sdTypes, objReader.ReadString());
int nArgs = objReader.ReadInt32();
Type[] argTypes = new Type[nArgs];
for(int i = 0; i < nArgs; i++)
{
argTypes[i] = GetTypeFromStr(sdTypes, objReader.ReadString());
}
MethodInfo methInfo = methType.GetMethod(methName, argTypes);
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, methInfo);
if(objectTokens != null)
objectTokens.EmitMethod(offset, opCode, methInfo);
break;
}
// Emit an opcode with a MethodInfo operand of an internal function
// (previously declared via DclMethod).
case ScriptObjWriterCode.EmitMethodInt:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
string methName = objReader.ReadString();
MethodInfo methInfo = methods[methName];
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, methInfo);
if(objectTokens != null)
objectTokens.EmitMethod(offset, opCode, methInfo);
break;
}
// Emit an opcode with a ConstructorInfo operand.
case ScriptObjWriterCode.EmitCtor:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
Type ctorType = GetTypeFromStr(sdTypes, objReader.ReadString());
int nArgs = objReader.ReadInt32();
Type[] argTypes = new Type[nArgs];
for(int i = 0; i < nArgs; i++)
{
argTypes[i] = GetTypeFromStr(sdTypes, objReader.ReadString());
}
ConstructorInfo ctorInfo = ctorType.GetConstructor(argTypes);
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, ctorInfo);
if(objectTokens != null)
objectTokens.EmitCtor(offset, opCode, ctorInfo);
break;
}
// Emit an opcode with a constant operand of various types.
case ScriptObjWriterCode.EmitDouble:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
double value = objReader.ReadDouble();
if(opCode != OpCodes.Ldc_R8)
{
throw new Exception("bad opcode " + opCode.ToString());
}
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, value);
if(objectTokens != null)
objectTokens.EmitDouble(offset, opCode, value);
break;
}
case ScriptObjWriterCode.EmitFloat:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
float value = objReader.ReadSingle();
if(opCode != OpCodes.Ldc_R4)
{
throw new Exception("bad opcode " + opCode.ToString());
}
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, value);
if(objectTokens != null)
objectTokens.EmitFloat(offset, opCode, value);
break;
}
case ScriptObjWriterCode.EmitInteger:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
int value = objReader.ReadInt32();
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
if(opCode == OpCodes.Ldc_I4)
{
if((value >= -1) && (value <= 8))
{
opCode = opCodesLdcI4M1P8[value + 1];
ilGen.Emit(opCode);
if(objectTokens != null)
objectTokens.EmitNull(offset, opCode);
break;
}
if((value >= 0) && (value <= 127))
{
opCode = OpCodes.Ldc_I4_S;
ilGen.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
goto pemitint;
}
}
ilGen.Emit(opCode, value);
pemitint:
if(objectTokens != null)
objectTokens.EmitInteger(offset, opCode, value);
break;
}
case ScriptObjWriterCode.EmitString:
{
OpCode opCode = ReadOpCode(objReader, ref srcFile, ref srcLine, ref srcPosn);
string value = objReader.ReadString();
SaveSrcLoc(srcLocs, offset, srcFile, srcLine, srcPosn);
ilGen.Emit(opCode, value);
if(objectTokens != null)
objectTokens.EmitString(offset, opCode, value);
break;
}
// Who knows what?
default:
throw new Exception("bad ScriptObjWriterCode " + ((byte)code).ToString());
}
}
}
/**
* @brief Generate array to quickly translate OpCode.Value to full OpCode struct.
*/
private static Dictionary<short, OpCode> PopulateOpCodes()
{
Dictionary<short, OpCode> opCodeDict = new Dictionary<short, OpCode>();
FieldInfo[] fields = typeof(OpCodes).GetFields();
for(int i = 0; i < fields.Length; i++)
{
OpCode opcode = (OpCode)fields[i].GetValue(null);
opCodeDict.Add(opcode.Value, opcode);
}
return opCodeDict;
}
/**
* @brief Write opcode out to file.
*/
private void WriteOpCode(Token errorAt, OpCode opcode)
{
if(errorAt == null)
{
objFileWriter.Write("");
objFileWriter.Write(lastErrorAtLine);
objFileWriter.Write(lastErrorAtPosn);
}
else
{
if(errorAt.file != lastErrorAtFile)
{
objFileWriter.Write(errorAt.file);
lastErrorAtFile = errorAt.file;
}
else
{
objFileWriter.Write("");
}
objFileWriter.Write(errorAt.line);
objFileWriter.Write(errorAt.posn);
lastErrorAtLine = errorAt.line;
lastErrorAtPosn = errorAt.posn;
}
objFileWriter.Write(opcode.Value);
}
/**
* @brief Read opcode in from file.
*/
private static OpCode ReadOpCode(BinaryReader objReader, ref string srcFile, ref int srcLine, ref int srcPosn)
{
string f = objReader.ReadString();
if(f != "")
srcFile = f;
srcLine = objReader.ReadInt32();
srcPosn = objReader.ReadInt32();
short value = objReader.ReadInt16();
return opCodes[value];
}
/**
* @brief Save an IL_offset -> source location translation entry
* @param srcLocs = saved entries for the current function
* @param offset = offset in IL object code for next instruction
* @param src{File,Line,Posn} = location in source file corresponding to opcode
* @returns with entry added to srcLocs
*/
private static void SaveSrcLoc(Dictionary<int, ScriptSrcLoc> srcLocs, int offset, string srcFile, int srcLine, int srcPosn)
{
ScriptSrcLoc srcLoc = new ScriptSrcLoc();
srcLoc.file = srcFile;
srcLoc.line = srcLine;
srcLoc.posn = srcPosn;
srcLocs[offset] = srcLoc;
}
/**
* @brief Create type<->string conversions.
* Using Type.AssemblyQualifiedName is horribly inefficient
* and all our types should be known.
*/
private static Dictionary<string, Type> PopulateS2T()
{
Dictionary<string, Type> s2t = new Dictionary<string, Type>();
s2t.Add("badcallx", typeof(ScriptBadCallNoException));
s2t.Add("binopstr", typeof(BinOpStr));
s2t.Add("bool", typeof(bool));
s2t.Add("char", typeof(char));
s2t.Add("delegate", typeof(Delegate));
s2t.Add("delarr[]", typeof(Delegate[]));
s2t.Add("double", typeof(double));
s2t.Add("exceptn", typeof(Exception));
s2t.Add("float", typeof(float));
s2t.Add("htlist", typeof(HeapTrackerList));
s2t.Add("htobject", typeof(HeapTrackerObject));
s2t.Add("htstring", typeof(HeapTrackerString));
s2t.Add("inlfunc", typeof(CompValuInline));
s2t.Add("int", typeof(int));
s2t.Add("int*", typeof(int).MakeByRefType());
s2t.Add("intrlokd", typeof(System.Threading.Interlocked));
s2t.Add("lslfloat", typeof(LSL_Float));
s2t.Add("lslint", typeof(LSL_Integer));
s2t.Add("lsllist", typeof(LSL_List));
s2t.Add("lslrot", typeof(LSL_Rotation));
s2t.Add("lslstr", typeof(LSL_String));
s2t.Add("lslvec", typeof(LSL_Vector));
s2t.Add("math", typeof(Math));
s2t.Add("midround", typeof(MidpointRounding));
s2t.Add("object", typeof(object));
s2t.Add("object*", typeof(object).MakeByRefType());
s2t.Add("object[]", typeof(object[]));
s2t.Add("scrbase", typeof(ScriptBaseClass));
s2t.Add("scrcode", typeof(ScriptCodeGen));
s2t.Add("sdtclobj", typeof(XMRSDTypeClObj));
s2t.Add("string", typeof(string));
s2t.Add("typecast", typeof(TypeCast));
s2t.Add("undstatx", typeof(ScriptUndefinedStateException));
s2t.Add("void", typeof(void));
s2t.Add("xmrarray", typeof(XMR_Array));
s2t.Add("xmrinst", typeof(XMRInstAbstract));
return s2t;
}
private static Dictionary<Type, string> PopulateT2S()
{
Dictionary<string, Type> s2t = PopulateS2T();
Dictionary<Type, string> t2s = new Dictionary<Type, string>();
foreach(KeyValuePair<string, Type> kvp in s2t)
{
t2s.Add(kvp.Value, kvp.Key);
}
return t2s;
}
/**
* @brief Add to list of internally recognized types.
*/
public static void DefineInternalType(string name, Type type)
{
if(!string2Type.ContainsKey(name))
{
string2Type.Add(name, type);
type2String.Add(type, name);
}
}
private string GetStrFromType(Type t)
{
string s = GetStrFromTypeWork(t);
return s;
}
private string GetStrFromTypeWork(Type t)
{
string s;
// internal fixed types like int and xmrarray etc
if(type2String.TryGetValue(t, out s))
return s;
// script-defined types
if(sdTypesRev.TryGetValue(t, out s))
return "sdt$" + s;
// inline function types
s = TokenDeclSDTypeDelegate.TryGetInlineName(t);
if(s != null)
return s;
// last resort
return t.AssemblyQualifiedName;
}
private static Type GetTypeFromStr(Dictionary<string, TokenDeclSDType> sdTypes, string s)
{
Type t;
// internal fixed types like int and xmrarray etc
if(string2Type.TryGetValue(s, out t))
return t;
// script-defined types
if(s.StartsWith("sdt$"))
return sdTypes[s.Substring(4)].GetSysType();
// inline function types
t = TokenDeclSDTypeDelegate.TryGetInlineSysType(s);
if(t != null)
return t;
// last resort
return Type.GetType(s, true);
}
}
public class ScriptSrcLoc
{
public string file;
public int line;
public int posn;
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Microsoft.Windows.Themes
{
/// <summary>
/// A Border used to provide the default look of headers.
/// When Background or BorderBrush are set, the rendering will
/// revert back to the default Border implementation.
/// </summary>
public partial class DataGridHeaderBorder
{
#region Theme Rendering
private Thickness? ThemeDefaultPadding
{
get
{
return null;
}
}
private void RenderTheme(DrawingContext dc)
{
Size size = RenderSize;
bool horizontal = Orientation == Orientation.Horizontal;
bool isClickable = IsClickable && IsEnabled;
bool isHovered = isClickable && IsHovered;
bool isPressed = isClickable && IsPressed;
ListSortDirection? sortDirection = SortDirection;
bool isSorted = sortDirection != null;
bool isSelected = IsSelected;
EnsureCache((int)RoyaleFreezables.NumFreezables);
if (horizontal)
{
// When horizontal, rotate the rendering by -90 degrees
Matrix m1 = new Matrix();
m1.RotateAt(-90.0, 0.0, 0.0);
Matrix m2 = new Matrix();
m2.Translate(0.0, size.Height);
MatrixTransform horizontalRotate = new MatrixTransform(m1 * m2);
horizontalRotate.Freeze();
dc.PushTransform(horizontalRotate);
double temp = size.Width;
size.Width = size.Height;
size.Height = temp;
}
// Draw the background
RoyaleFreezables backgroundType = isPressed ? RoyaleFreezables.PressedBackground : isHovered ? RoyaleFreezables.HoveredBackground : RoyaleFreezables.NormalBackground;
LinearGradientBrush background = (LinearGradientBrush)GetCachedFreezable((int)backgroundType);
if (background == null)
{
background = new LinearGradientBrush();
background.StartPoint = new Point();
background.EndPoint = new Point(0.0, 1.0);
if (isPressed)
{
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xB9, 0xB9, 0xC8), 0.0));
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xEC, 0xEC, 0xF3), 0.1));
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xEC, 0xEC, 0xF3), 1.0));
}
else if (isHovered || isSelected)
{
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xFE, 0xFE, 0xFE), 0.0));
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xFE, 0xFE, 0xFE), 0.85));
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xBD, 0xBE, 0xCE), 1.0));
}
else
{
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xF9, 0xFA, 0xFD), 0.0));
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xF9, 0xFA, 0xFD), 0.85));
background.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xBD, 0xBE, 0xCE), 1.0));
}
background.Freeze();
CacheFreezable(background, (int)backgroundType);
}
dc.DrawRectangle(background, null, new Rect(0.0, 0.0, size.Width, size.Height));
if (isHovered && !isPressed && (size.Width >= 6.0) && (size.Height >= 4.0))
{
// When hovered, there is a colored tab at the bottom
TranslateTransform positionTransform = new TranslateTransform(0.0, size.Height - 3.0);
positionTransform.Freeze();
dc.PushTransform(positionTransform);
PathGeometry tabGeometry = new PathGeometry();
PathFigure tabFigure = new PathFigure();
tabFigure.StartPoint = new Point(0.5, 0.5);
LineSegment line = new LineSegment(new Point(size.Width - 0.5, 0.5), true);
line.Freeze();
tabFigure.Segments.Add(line);
ArcSegment arc = new ArcSegment(new Point(size.Width - 2.5, 2.5), new Size(2.0, 2.0), 90.0, false, SweepDirection.Clockwise, true);
arc.Freeze();
tabFigure.Segments.Add(arc);
line = new LineSegment(new Point(2.5, 2.5), true);
line.Freeze();
tabFigure.Segments.Add(line);
arc = new ArcSegment(new Point(0.5, 0.5), new Size(2.0, 2.0), 90.0, false, SweepDirection.Clockwise, true);
arc.Freeze();
tabFigure.Segments.Add(arc);
tabFigure.IsClosed = true;
tabFigure.Freeze();
tabGeometry.Figures.Add(tabFigure);
tabGeometry.Freeze();
Pen tabStroke = (Pen)GetCachedFreezable((int)RoyaleFreezables.TabStroke);
if (tabStroke == null)
{
SolidColorBrush tabStrokeBrush = new SolidColorBrush(Color.FromArgb(0xFF, 0xF8, 0xA9, 0x00));
tabStrokeBrush.Freeze();
tabStroke = new Pen(tabStrokeBrush, 1.0);
tabStroke.Freeze();
CacheFreezable(tabStroke, (int)RoyaleFreezables.TabStroke);
}
LinearGradientBrush tabFill = (LinearGradientBrush)GetCachedFreezable((int)RoyaleFreezables.TabFill);
if (tabFill == null)
{
tabFill = new LinearGradientBrush();
tabFill.StartPoint = new Point();
tabFill.EndPoint = new Point(1.0, 0.0);
tabFill.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xFC, 0xE0, 0xA6), 0.0));
tabFill.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xF6, 0xC4, 0x56), 0.1));
tabFill.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xF6, 0xC4, 0x56), 0.9));
tabFill.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF, 0xDF, 0x97, 0x00), 1.0));
tabFill.Freeze();
CacheFreezable(tabFill, (int)RoyaleFreezables.TabFill);
}
dc.DrawGeometry(tabFill, tabStroke, tabGeometry);
dc.Pop(); // Translate Transform
}
if (isPressed && (size.Width >= 2.0) && (size.Height >= 2.0))
{
// When pressed, there is a border on the left and bottom
SolidColorBrush border = (SolidColorBrush)GetCachedFreezable((int)RoyaleFreezables.PressedBorder);
if (border == null)
{
border = new SolidColorBrush(Color.FromArgb(0xFF, 0x80, 0x80, 0x99));
border.Freeze();
CacheFreezable(border, (int)RoyaleFreezables.PressedBorder);
}
dc.DrawRectangle(border, null, new Rect(0.0, 0.0, 1.0, size.Height));
dc.DrawRectangle(border, null, new Rect(0.0, Max0(size.Height - 1.0), size.Width, 1.0));
}
if (!isPressed && !isHovered && (size.Width >= 4.0))
{
if (SeparatorVisibility == Visibility.Visible)
{
Brush sideBrush;
if (SeparatorBrush != null)
{
sideBrush = SeparatorBrush;
}
else
{
// When not pressed or hovered, draw the resize gripper
LinearGradientBrush gripper = (LinearGradientBrush)GetCachedFreezable((int)(horizontal ? RoyaleFreezables.HorizontalGripper : RoyaleFreezables.VerticalGripper));
if (gripper == null)
{
gripper = new LinearGradientBrush();
gripper.StartPoint = new Point();
gripper.EndPoint = new Point(1.0, 0.0);
Color highlight = Color.FromArgb(0xFF, 0xFF, 0xFF, 0xFF);
Color shadow = Color.FromArgb(0xFF, 0xC7, 0xC5, 0xB2);
if (horizontal)
{
gripper.GradientStops.Add(new GradientStop(highlight, 0.0));
gripper.GradientStops.Add(new GradientStop(highlight, 0.25));
gripper.GradientStops.Add(new GradientStop(shadow, 0.75));
gripper.GradientStops.Add(new GradientStop(shadow, 1.0));
}
else
{
gripper.GradientStops.Add(new GradientStop(shadow, 0.0));
gripper.GradientStops.Add(new GradientStop(shadow, 0.25));
gripper.GradientStops.Add(new GradientStop(highlight, 0.75));
gripper.GradientStops.Add(new GradientStop(highlight, 1.0));
}
gripper.Freeze();
CacheFreezable(gripper, (int)(horizontal ? RoyaleFreezables.HorizontalGripper : RoyaleFreezables.VerticalGripper));
}
sideBrush = gripper;
}
dc.DrawRectangle(sideBrush, null, new Rect(horizontal ? 0.0 : Max0(size.Width - 2.0), 4.0, 2.0, Max0(size.Height - 8.0)));
}
}
if (isSorted && (size.Width > 14.0) && (size.Height > 10.0))
{
// When sorted, draw an arrow on the right
TranslateTransform positionTransform = new TranslateTransform(size.Width - 15.0, (size.Height - 5.0) * 0.5);
positionTransform.Freeze();
dc.PushTransform(positionTransform);
bool ascending = (sortDirection == ListSortDirection.Ascending);
PathGeometry arrowGeometry = (PathGeometry)GetCachedFreezable(ascending ? (int)RoyaleFreezables.ArrowUpGeometry : (int)RoyaleFreezables.ArrowDownGeometry);
if (arrowGeometry == null)
{
arrowGeometry = new PathGeometry();
PathFigure arrowFigure = new PathFigure();
if (ascending)
{
arrowFigure.StartPoint = new Point(0.0, 5.0);
LineSegment line = new LineSegment(new Point(5.0, 0.0), false);
line.Freeze();
arrowFigure.Segments.Add(line);
line = new LineSegment(new Point(10.0, 5.0), false);
line.Freeze();
arrowFigure.Segments.Add(line);
}
else
{
arrowFigure.StartPoint = new Point(0.0, 0.0);
LineSegment line = new LineSegment(new Point(10.0, 0.0), false);
line.Freeze();
arrowFigure.Segments.Add(line);
line = new LineSegment(new Point(5.0, 5.0), false);
line.Freeze();
arrowFigure.Segments.Add(line);
}
arrowFigure.IsClosed = true;
arrowFigure.Freeze();
arrowGeometry.Figures.Add(arrowFigure);
arrowGeometry.Freeze();
CacheFreezable(arrowGeometry, ascending ? (int)RoyaleFreezables.ArrowUpGeometry : (int)RoyaleFreezables.ArrowDownGeometry);
}
SolidColorBrush arrowFill = (SolidColorBrush)GetCachedFreezable((int)RoyaleFreezables.ArrowFill);
if (arrowFill == null)
{
arrowFill = new SolidColorBrush(Color.FromArgb(0xFF, 0xAC, 0xA8, 0x99));
arrowFill.Freeze();
CacheFreezable(arrowFill, (int)RoyaleFreezables.ArrowFill);
}
dc.DrawGeometry(arrowFill, null, arrowGeometry);
dc.Pop(); // Position Transform
}
if (horizontal)
{
dc.Pop(); // Horizontal Rotate
}
}
private enum RoyaleFreezables
{
NormalBackground,
HoveredBackground,
PressedBackground,
HorizontalGripper,
VerticalGripper,
PressedBorder,
TabGeometry,
TabStroke,
TabFill,
ArrowFill,
ArrowUpGeometry,
ArrowDownGeometry,
NumFreezables
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Rhino.ServiceBus.Impl;
using Rhino.ServiceBus.Internal;
using Rhino.ServiceBus.Sagas;
using Rhino.ServiceBus.Sagas.Persisters;
using Xunit;
namespace Rhino.ServiceBus.Tests
{
public class SagaTests : MsmqBehaviorTests
{
private static Guid sagaId;
private static ManualResetEvent wait;
private readonly IWindsorContainer container;
public SagaTests()
{
OrderProcessor.LastState = null;
wait = new ManualResetEvent(false);
container = new WindsorContainer(new XmlInterpreter());
container.Kernel.AddFacility("rhino.esb", new RhinoServiceBusFacility());
container.Register(
Component.For(typeof(ISagaPersister<>))
.ImplementedBy(typeof(InMemorySagaPersister<>)),
Component.For<OrderProcessor>()
);
}
[Fact]
public void when_sending_non_initiating_message_saga_will_not_be_invoked()
{
using (var bus = container.Resolve<IStartableServiceBus>())
{
var transport = container.Resolve<ITransport>();
bus.Start();
transport.MessageProcessingCompleted += (i,e) => wait.Set();
bus.Send(bus.Endpoint, new AddLineItemMessage());
wait.WaitOne(TimeSpan.FromSeconds(30), false);
Assert.Null(OrderProcessor.LastState);
}
}
[Fact]
public void When_saga_with_same_correlation_id_exists_and_get_initiating_message_will_usage_same_saga()
{
using (var bus = container.Resolve<IStartableServiceBus>())
{
bus.Start();
var guid = Guid.NewGuid();
bus.Send(bus.Endpoint, new NewOrderMessage { CorrelationId = guid });
wait.WaitOne(TimeSpan.FromSeconds(30), false);
wait.Reset();
bus.Send(bus.Endpoint, new NewOrderMessage { CorrelationId = guid });
wait.WaitOne(TimeSpan.FromSeconds(30), false);
Assert.Equal(2, OrderProcessor.LastState.Count);
}
}
[Fact]
public void Can_create_saga_entity()
{
using (var bus = container.Resolve<IStartableServiceBus>())
{
bus.Start();
bus.Send(bus.Endpoint, new NewOrderMessage());
wait.WaitOne(TimeSpan.FromSeconds(30), false);
var persister = container.Resolve<ISagaPersister<OrderProcessor>>();
OrderProcessor processor = null;
while (processor == null)
{
Thread.Sleep(500);
processor = persister.Get(sagaId);
}
Assert.Equal(1, processor.State.Count);
}
}
[Fact]
public void When_creating_saga_entity_will_set_saga_id()
{
using (var bus = container.Resolve<IStartableServiceBus>())
{
bus.Start();
bus.Send(bus.Endpoint, new NewOrderMessage2());
wait.WaitOne(TimeSpan.FromSeconds(30), false);
var persister = container.Resolve<ISagaPersister<OrderProcessor>>();
OrderProcessor processor = null;
while (processor == null)
{
Thread.Sleep(500);
processor = persister.Get(sagaId);
}
Assert.NotEqual(Guid.Empty, sagaId);
}
}
[Fact]
public void Can_send_several_messaged_to_same_instance_of_saga_entity()
{
using (var bus = container.Resolve<IStartableServiceBus>())
{
bus.Start();
bus.Send(bus.Endpoint, new NewOrderMessage());
wait.WaitOne(TimeSpan.FromSeconds(30), false);
wait.Reset();
Assert.Equal(1, OrderProcessor.LastState.Count);
bus.Send(bus.Endpoint, new AddLineItemMessage { CorrelationId = sagaId });
wait.WaitOne(TimeSpan.FromSeconds(30), false);
Assert.Equal(2, OrderProcessor.LastState.Count);
}
}
[Fact]
public void Completing_saga_will_get_it_out_of_the_in_memory_persister()
{
using (var bus = container.Resolve<IStartableServiceBus>())
{
bus.Start();
bus.Send(bus.Endpoint, new NewOrderMessage());
wait.WaitOne(TimeSpan.FromSeconds(30), false);
wait.Reset();
var persister = container.Resolve<ISagaPersister<OrderProcessor>>();
OrderProcessor processor = null;
while (processor == null)
{
Thread.Sleep(500);
processor = persister.Get(sagaId);
}
bus.Send(bus.Endpoint, new SubmitOrderMessage { CorrelationId = sagaId });
wait.WaitOne(TimeSpan.FromSeconds(30), false);
while (processor != null)
{
Thread.Sleep(500);
processor = persister.Get(sagaId);
}
Assert.Null(processor);
}
}
#region Nested type: AddLineItemMessage
public class AddLineItemMessage : ISagaMessage
{
#region ISagaMessage Members
public Guid CorrelationId { get; set; }
#endregion
}
#endregion
#region Nested type: NewOrderMessage
public class NewOrderMessage : ISagaMessage
{
public Guid CorrelationId
{
get;
set;
}
}
#endregion
#region Nested type: OrderProcessor
public class OrderProcessor :
ISaga<List<object>>,
InitiatedBy<NewOrderMessage2>,
InitiatedBy<NewOrderMessage>,
Orchestrates<AddLineItemMessage>,
Orchestrates<SubmitOrderMessage>
{
public static List<object> LastState;
public OrderProcessor()
{
State = new List<object>();
}
#region InitiatedBy<NewOrderMessage> Members
public void Consume(NewOrderMessage pong)
{
State.Add(pong);
sagaId = Id;
LastState = State;
wait.Set();
}
public Guid Id { get; set; }
public bool IsCompleted { get; set; }
#endregion
#region Orchestrates<AddLineItemMessage> Members
public void Consume(AddLineItemMessage pong)
{
State.Add(pong);
sagaId = Id;
LastState = State;
wait.Set();
}
#endregion
public void Consume(SubmitOrderMessage message)
{
IsCompleted = true;
LastState = State;
wait.Set();
}
public List<object> State
{
get;
set;
}
public void Consume(NewOrderMessage2 message)
{
LastState = State;
sagaId = Id;
wait.Set();
}
}
#endregion
#region Nested type: SubmitOrderMessage
public class SubmitOrderMessage : ISagaMessage
{
#region ISagaMessage Members
public Guid CorrelationId { get; set; }
#endregion
}
#endregion
}
public class NewOrderMessage2
{
}
}
| |
using NUnit.Framework;
using RefactoringEssentials.CSharp.Diagnostics;
namespace RefactoringEssentials.Tests.CSharp.Diagnostics
{
[TestFixture]
[Ignore("TODO: Issue not ported yet")]
public class LockThisTests : CSharpDiagnosticTestBase
{
[Test]
public void TestLockThisInMethod()
{
var input = @"
class TestClass
{
void TestMethod ()
{
lock (this) {
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
void TestMethod ()
{
lock (locker) {
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockThisInGetter()
{
var input = @"
class TestClass
{
int MyProperty {
get {
lock (this) {
return 0;
}
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
int MyProperty {
get {
lock (locker) {
return 0;
}
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockThisInSetter()
{
var input = @"
class TestClass
{
int MyProperty {
set {
lock (this) {
}
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
int MyProperty {
set {
lock (locker) {
}
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockThisInConstructor()
{
var input = @"
class TestClass
{
TestClass()
{
lock (this) {
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
TestClass()
{
lock (locker) {
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockThisInDelegate()
{
var input = @"
class TestClass
{
TestClass()
{
Action lockThis = delegate ()
{
lock (this) {
}
};
}
}";
var output = @"
class TestClass
{
object locker = new object ();
TestClass()
{
Action lockThis = delegate ()
{
lock (locker) {
}
};
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockThisInLambda()
{
var input = @"
class TestClass
{
TestClass()
{
Action lockThis = () =>
{
lock (this) {
}
};
}
}";
var output = @"
class TestClass
{
object locker = new object ();
TestClass()
{
Action lockThis = () =>
{
lock (locker) {
}
};
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockParenthesizedThis()
{
var input = @"
class TestClass
{
void TestMethod ()
{
lock ((this)) {
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
void TestMethod ()
{
lock (locker) {
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestFixMultipleLockThis()
{
var input = @"
class TestClass
{
void TestMethod ()
{
lock (this) {
}
}
void TestMethod2 ()
{
lock (this) {
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
void TestMethod ()
{
lock (locker) {
}
}
void TestMethod2 ()
{
lock (locker) {
}
}
}";
Test<LockThisAnalyzer>(input, 2, output, 0);
}
[Test]
public void TestFixMixedLocks()
{
var input = @"
class TestClass
{
void TestMethod ()
{
lock (this) {
}
}
object locker2 = new object ();
void TestMethod2 ()
{
lock (locker2) {
}
}
}";
var output = @"
class TestClass
{
object locker = new object ();
void TestMethod ()
{
lock (locker) {
}
}
object locker2 = new object ();
void TestMethod2 ()
{
lock (locker2) {
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestLockNonThis()
{
var input = @"
class TestClass
{
object locker = new object ();
TestClass()
{
lock (locker) {
}
}
}";
Test<LockThisAnalyzer>(input, 0);
}
[Test]
public void TestNestedTypeLock()
{
var input = @"
class TestClass
{
class Nested
{
Nested()
{
lock (this) {
}
}
}
}";
var output = @"
class TestClass
{
class Nested
{
object locker = new object ();
Nested()
{
lock (locker) {
}
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestMethodSynchronized()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
void TestMethod ()
{
System.Console.WriteLine (""Foo"");
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
object locker = new object ();
void TestMethod ()
{
lock (locker) {
System.Console.WriteLine (""Foo"");
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestMethodWithSynchronizedValue()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
[MethodImpl (Value = MethodImplOptions.Synchronized)]
void TestMethod ()
{
System.Console.WriteLine (""Foo"");
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
object locker = new object ();
void TestMethod ()
{
lock (locker) {
System.Console.WriteLine (""Foo"");
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestMethodHasSynchronized()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized | MethodImplOptions.NoInlining)]
void TestMethod ()
{
System.Console.WriteLine (""Foo"");
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
object locker = new object ();
[MethodImpl (MethodImplOptions.NoInlining)]
void TestMethod ()
{
lock (locker) {
System.Console.WriteLine (""Foo"");
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestMethodNotSynchronized()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
[MethodImpl (MethodImplOptions.NoInlining)]
void TestMethod ()
{
System.Console.WriteLine (""Foo"");
}
}";
Test<LockThisAnalyzer>(input, 0);
}
[Test]
public void TestAbstractSynchronized()
{
var input = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
public abstract void TestMethod ();
}";
var output = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
public abstract void TestMethod ();
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestDoubleLocking()
{
var input = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
public void TestMethod ()
{
lock (this) {
}
}
}";
var output = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
object locker = new object ();
public void TestMethod ()
{
lock (locker) {
lock (locker) {
}
}
}
}";
Test<LockThisAnalyzer>(input, 2, output, 0);
}
[Test]
public void TestDelegateLocking()
{
var input = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
public void TestMethod ()
{
Action action = delegate {
lock (this) {
}
};
}
}";
var output = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
object locker = new object ();
public void TestMethod ()
{
lock (locker) {
Action action = delegate {
lock (locker) {
}
};
}
}
}";
Test<LockThisAnalyzer>(input, 2, output, 0);
}
[Test]
public void TestLambdaLocking()
{
var input = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
public void TestMethod ()
{
Action action = () => {
lock (this) {
}
};
}
}";
var output = @"
using System.Runtime.CompilerServices;
abstract class TestClass
{
object locker = new object ();
public void TestMethod ()
{
lock (locker) {
Action action = () => {
lock (locker) {
}
};
}
}
}";
Test<LockThisAnalyzer>(input, 2, output, 0);
}
[Test]
public void TestStaticMethod()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
public static void TestMethod ()
{
Console.WriteLine ();
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
static object locker = new object ();
public static void TestMethod ()
{
lock (locker) {
Console.WriteLine ();
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestStaticProperty()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
public static int TestProperty
{
[MethodImpl (MethodImplOptions.Synchronized)]
set {
Console.WriteLine (value);
}
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
static object locker = new object ();
public static int TestProperty
{
set {
lock (locker) {
Console.WriteLine (value);
}
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
[Test]
public void TestMixedStaticMethod()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
[MethodImpl (MethodImplOptions.Synchronized)]
public void TestMethod ()
{
Console.WriteLine ();
}
[MethodImpl (MethodImplOptions.Synchronized)]
public static void TestStaticMethod ()
{
Console.WriteLine ();
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
object locker = new object ();
public void TestMethod ()
{
lock (locker) {
Console.WriteLine ();
}
}
[MethodImpl (MethodImplOptions.Synchronized)]
public static void TestStaticMethod ()
{
Console.WriteLine ();
}
}";
Test<LockThisAnalyzer>(input, 2, output, 0);
}
[Test]
public void TestNewNameLock()
{
var input = @"
using System.Runtime.CompilerServices;
class TestClass
{
int locker;
[MethodImpl (MethodImplOptions.Synchronized)]
public void TestMethod ()
{
Console.WriteLine ();
}
}";
var output = @"
using System.Runtime.CompilerServices;
class TestClass
{
int locker;
object locker1 = new object ();
public void TestMethod ()
{
lock (locker1) {
Console.WriteLine ();
}
}
}";
Test<LockThisAnalyzer>(input, 1, output);
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEditor.XCodeEditor;
#endif
using System.IO;
public static class XCodePostProcess
{
#if UNITY_EDITOR
private const string key_Capability_InAppPurchase = "com.apple.InAppPurchase";
private const string key_Capability_Keychain = "com.apple.Keychain";
private const string key_Capability_GameCenter = "com.apple.GameCenter";
[PostProcessBuild(999)]
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
{
#if UNITY_5
if (target != BuildTarget.iOS)
{
#else
if (target != BuildTarget.iPhone)
{
#endif
Debug.LogWarning("Target is not iPhone. XCodePostProcess will not run");
return;
}
Debug.Log("pathToBuiltProject:" + pathToBuiltProject);
string path = Path.GetFullPath(pathToBuiltProject);
Debug.Log("pathToBuiltProject full path:" + path);
// Create a new project object from build target
XCProject project = new XCProject(path);
// Find and run through all projmods files to patch the project.Please pay attention that ALL projmods files in your project folder will be excuted!
string[] files = null;
if (isV5())
{
project.AddFrameworkSearchPaths("$(SRCROOT)/Frameworks/Plugins/iOS");
files = Directory.GetFiles(Application.dataPath, "*.projmods", SearchOption.AllDirectories);
}
else
{
files = Directory.GetFiles(Application.dataPath, "*.projmods", SearchOption.AllDirectories);
}
foreach (string file in files)
{
UnityEngine.Debug.Log("ProjMod File: " + file);
project.ApplyMod(file);
}
System.IO.File.Copy(Application.dataPath + "/../fxq.entitlements", pathToBuiltProject + "/Unity-iPhone/fxq.entitlements", true);
project.project.SetSystemCapabilities(key_Capability_InAppPurchase, "1");
project.project.SetSystemCapabilities(key_Capability_Keychain, "1");
project.project.SetSystemCapabilities(key_Capability_GameCenter, "0");
project.AddFile(Application.dataPath + "/../TSDKConfig", null, "SOURCE_ROOT", true, false);
project.overwriteBuildSetting("CODE_SIGN_IDENTITY", "iPhone Distribution: Shenzhen Tencent Computer Systems Company Limited (9TV4ZYSS4J)", "Release");
project.overwriteBuildSetting("CODE_SIGN_IDENTITY[sdk=iphoneos*]", "iPhone Distribution: Shenzhen Tencent Computer Systems Company Limited (9TV4ZYSS4J)", "Release");
project.overwriteBuildSetting("CODE_SIGN_IDENTITY", "iPhone Developer: txjsj Agent (87N52B8C25)", "Debug");
project.overwriteBuildSetting("CODE_SIGN_IDENTITY[sdk=iphoneos*]", "iPhone Developer: txjsj Agent (87N52B8C25)", "Debug");
project.overwriteBuildSetting("CODE_SIGN_ENTITLEMENTS", "Unity-iPhone/fxq.entitlements", "Debug");
project.overwriteBuildSetting("CODE_SIGN_ENTITLEMENTS", "Unity-iPhone/fxq.entitlements", "Release");
project.overwriteBuildSetting("ARCHS", "$(ARCHS_STANDARD)", "Debug");
project.overwriteBuildSetting("ARCHS", "$(ARCHS_STANDARD)", "Release");
project.overwriteBuildSetting("ENABLE_BITCODE", "NO", "Debug");
project.overwriteBuildSetting("ENABLE_BITCODE", "NO", "Release");
//TODO implement generic settings as a module option
//project.overwriteBuildSetting("CODE_SIGN_IDENTITY[sdk=iphoneos*]", "iPhone Distribution", "Release");
EditorPlist(path);
EditorCode(path);
// Finally save the xcode project
project.Save();
}
static bool isV5()
{
return Application.unityVersion[0] == '5';
}
private static void EditorPlist(string filePath)
{
XCPlist list = new XCPlist(filePath);
string PlistAdd = @"
<key>APPKEY_DENGTA</key>
<string>0I200A6H7A04ZKTA</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>weixin</string>
<key>CFBundleURLSchemes</key>
<array>
<string>" + "WXAPP_ID" + @"</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>tencentopenapi</string>
<key>CFBundleURLSchemes</key>
<array>
<string>tencent" + "QQ_APPID" + @"</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>QQ</string>
<key>CFBundleURLSchemes</key>
<array>
<string>QQ" + "QQ_APPID_x8" + @"</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>QQLaunch</string>
<key>CFBundleURLSchemes</key>
<array>
<string>QQ" + "QQ_APPID" + @"</string>
</array>
</dict>
</array>
<key>CHANNEL_DENGTA</key>
<string>10001</string>
<key>LSApplicationCategoryType</key>
<string></string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>mqq</string>
<string>mqqapi</string>
<string>wtloginmqq2</string>
<string>mqqopensdkapiV3</string>
<string>mqqopensdkapiV2</string>
<string>mqqwpa</string>
<string>mqqOpensdkSSoLogin</string>
<string>mqqgamebindinggroup</string>
<string>mqqopensdkfriend</string>
<string>mqzone</string>
<string>weixin</string>
<string>wechat</string>
</array>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>MSDKKey</key>
<string>" + "MSDKKey" + @"</string>
<key>MSDK_OfferId</key>
<string>" + "OfferID" + @"</string>
<key>MSDK_URL</key>
<string>" + "MsdkUrl" + @"</string>
<key>QQAppID</key>
<string>" + "QQ_APPID" + @"</string>
<key>QQAppKey</key>
<string>" + "QQ_KEY" + @"</string>
<key>WXAppID</key>
<string>" + "WX_APPID" + @"</string>
<key>WXAppKey</key>
<string>" + "WX_Key" + @"</string>
<key>NeedNotice</key>
<true/>
<key>NoticeTime</key>
<integer>600</integer>";
list.AddKey(PlistAdd);
list.Save();
}
private static void EditorCode(string filePath)
{
XClass UnityAppController = new XClass(filePath + "/Classes/UnityAppController.mm");
UnityAppController.WriteBelow("#include \"PluginBase/AppDelegateListener.h\"", "#include <apollo/ApolloApplication.h>");
UnityAppController.WriteBelow("UnityCleanup();\n", " [[ApolloApplication sharedInstance] applicationWillTerminate:application];");
UnityAppController.WriteBelow("- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation\n{", " [[ApolloApplication sharedInstance] handleOpenURL:url];");
if (isV5() == true)
{
UnityAppController.WriteBelow("::printf(\"-> applicationWillEnterForeground()\\n\");", " [[ApolloApplication sharedInstance] applicationWillEnterForeground:application];");
UnityAppController.WriteBelow("::printf(\"-> applicationWillResignActive()\\n\");", " [[ApolloApplication sharedInstance] applicationWillResignActive:application];");
UnityAppController.WriteBelow("::printf(\"-> applicationDidEnterBackground()\\n\");", " [[ApolloApplication sharedInstance] applicationDidEnterBackground:application];");
UnityAppController.WriteBelow("::printf(\"-> applicationDidBecomeActive()\\n\");", " [[ApolloApplication sharedInstance] applicationDidBecomeActive:application];");
UnityAppController.WriteBelow("::printf(\"-> applicationWillTerminate()\\n\");", " [[ApolloApplication sharedInstance] applicationWillTerminate:application];");
UnityAppController.WriteBelow("\treturn YES;\n}", "- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url\r{\r return [[ApolloApplication sharedInstance] handleOpenURL:url];\r} \n\n");
UnityAppController.WriteBelow("[[NSNotificationCenter defaultCenter] postNotificationName:name object:UnityGetGLViewController()];\n",
"\r[[ApolloApplication sharedInstance]setRootVC:UnityGetGLViewController()];");
}
else
{
UnityAppController.WriteBelow("printf_console(\"-> applicationWillEnterForeground()\\n\");", " [[ApolloApplication sharedInstance] applicationWillEnterForeground:application];");
UnityAppController.WriteBelow("printf_console(\"-> applicationWillResignActive()\\n\");", " [[ApolloApplication sharedInstance] applicationWillResignActive:application];");
UnityAppController.WriteBelow("UnityInitApplicationNoGraphics([[[NSBundle mainBundle] bundlePath]UTF8String]);\n", " [[ApolloApplication sharedInstance] setRootVC:UnityGetGLViewController()];");
UnityAppController.WriteBelow("[[ApolloApplication sharedInstance] applicationWillTerminate:application];\n\n}", "- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url\r{\r return [[ApolloApplication sharedInstance] handleOpenURL:url];\r}");
}
}
#endif
public static void Log(string message)
{
UnityEngine.Debug.Log("PostProcess: " + message);
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI41;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI41
{
/// <summary>
/// OpenSession, CloseSession, CloseAllSessions and GetSessionInfo tests.
/// </summary>
[TestClass]
public class _06_SessionTest
{
/// <summary>
/// Basic OpenSession and CloseSession test.
/// </summary>
[TestMethod]
public void _01_BasicSessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
// Close session
session.CloseSession();
}
}
/// <summary>
/// Using statement test.
/// </summary>
[TestMethod]
public void _02_UsingSessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Session class can be used in using statement which defines a scope
// at the end of which the session will be closed automatically.
using (Session session = slot.OpenSession(true))
{
// Do something interesting in RO session
}
}
}
/// <summary>
/// CloseSession via slot test.
/// </summary>
[TestMethod]
public void _03_CloseSessionViaSlotTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
// Alternatively session can be closed with CloseSession method of Slot class.
slot.CloseSession(session);
}
}
/// <summary>
/// CloseAllSessions test.
/// </summary>
[TestMethod]
public void _04_CloseAllSessionsTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
Assert.IsNotNull(session);
// All sessions can be closed with CloseAllSessions method of Slot class.
slot.CloseAllSessions();
}
}
/// <summary>
/// Read-only session test.
/// </summary>
[TestMethod]
public void _05_ReadOnlySessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Do something interesting in RO session
}
}
}
/// <summary>
/// Read-write session test.
/// </summary>
[TestMethod]
public void _06_ReadWriteSessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW (read-write) session
using (Session session = slot.OpenSession(false))
{
// Do something interesting in RW session
}
}
}
/// <summary>
/// GetSessionInfo test.
/// </summary>
[TestMethod]
public void _07_SessionInfoTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 1)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Get session details
SessionInfo sessionInfo = session.GetSessionInfo();
// Do something interesting with session info
Assert.IsTrue(sessionInfo.SlotId == slot.SlotId);
Assert.IsNotNull(sessionInfo.SessionFlags);
}
}
}
}
}
| |
using NUnit.Framework;
namespace Braintree.Tests
{
[TestFixture]
public class SubscriptionSearchRequestTest
{
[Test]
public void ToXml_BillingCyclesRemainingIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.Is(1);
var xml = "<search><billing-cycles-remaining><is>1</is></billing-cycles-remaining></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_BillingCyclesRemainingBetween()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.Between(1, 2);
var xml = "<search><billing-cycles-remaining><min>1</min><max>2</max></billing-cycles-remaining></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_BillingCyclesRemainingGreaterThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.GreaterThanOrEqualTo(12.34);
var xml = "<search><billing-cycles-remaining><min>12.34</min></billing-cycles-remaining></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_BillingCyclesRemainingLessThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().BillingCyclesRemaining.LessThanOrEqualTo(12.34);
var xml = "<search><billing-cycles-remaining><max>12.34</max></billing-cycles-remaining></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_IdIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.Is("30");
var xml = "<search><id><is>30</is></id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_IdIsNot()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.IsNot("30");
var xml = "<search><id><is-not>30</is-not></id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_IdStartsWith()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.StartsWith("30");
var xml = "<search><id><starts-with>30</starts-with></id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_IdEndsWith()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.EndsWith("30");
var xml = "<search><id><ends-with>30</ends-with></id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_IdContains()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Id.Contains("30");
var xml = "<search><id><contains>30</contains></id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_MerchantAccountIdIncludedIn()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().MerchantAccountId.IncludedIn("abc", "def");
var xml = "<search><merchant-account-id type=\"array\"><item>abc</item><item>def</item></merchant-account-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_MerchantAccountIdIncludedInWithExplicitArray()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().MerchantAccountId.IncludedIn(new string[] {"abc", "def"});
var xml = "<search><merchant-account-id type=\"array\"><item>abc</item><item>def</item></merchant-account-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_MerchantAccountIdIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().MerchantAccountId.Is("abc");
var xml = "<search><merchant-account-id type=\"array\"><item>abc</item></merchant-account-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PlanIdIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.Is("abc");
var xml = "<search><plan-id><is>abc</is></plan-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PlanIdIsNot()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.IsNot("30");
var xml = "<search><plan-id><is-not>30</is-not></plan-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PlanIdStartsWith()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.StartsWith("30");
var xml = "<search><plan-id><starts-with>30</starts-with></plan-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PlanIdEndsWith()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.EndsWith("30");
var xml = "<search><plan-id><ends-with>30</ends-with></plan-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PlanIdContains()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.Contains("30");
var xml = "<search><plan-id><contains>30</contains></plan-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PlanIdIncludedIn()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().PlanId.IncludedIn("abc", "def");
var xml = "<search><plan-id type=\"array\"><item>abc</item><item>def</item></plan-id></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_CreatedAtIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().CreatedAt.Is("1/1/2015");
var xml = "<search><created-at><is>1/1/2015</is></created-at></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_CreatedAtBetween()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().CreatedAt.Between("1/1/2015", "1/2/2015");
var xml = "<search><created-at><min>1/1/2015</min><max>1/2/2015</max></created-at></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_CreatedAtThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().CreatedAt.GreaterThanOrEqualTo("1/1/2015");
var xml = "<search><created-at><min>1/1/2015</min></created-at></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_CreatedAtLessThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().CreatedAt.LessThanOrEqualTo("1/1/2015");
var xml = "<search><created-at><max>1/1/2015</max></created-at></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_DaysPastDueIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.Is("30");
var xml = "<search><days-past-due><is>30</is></days-past-due></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_DaysPastDueBetween()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.Between(2, 3);
var xml = "<search><days-past-due><min>2</min><max>3</max></days-past-due></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_DaysPastDueGreaterThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.GreaterThanOrEqualTo(3);
var xml = "<search><days-past-due><min>3</min></days-past-due></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_DaysPastDueLessThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().DaysPastDue.LessThanOrEqualTo(4);
var xml = "<search><days-past-due><max>4</max></days-past-due></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PriceIs()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.Is(1M);
var xml = "<search><price><is>1</is></price></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PriceBetween()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.Between(1M, 2M);
var xml = "<search><price><min>1</min><max>2</max></price></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PriceGreaterThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.GreaterThanOrEqualTo(12.34M);
var xml = "<search><price><min>12.34</min></price></search>";
Assert.AreEqual(xml, request.ToXml());
}
[Test]
public void ToXml_PriceLessThanOrEqualTo()
{
SubscriptionSearchRequest request = new SubscriptionSearchRequest().Price.LessThanOrEqualTo(12.34M);
var xml = "<search><price><max>12.34</max></price></search>";
Assert.AreEqual(xml, request.ToXml());
}
}
}
| |
using System.Collections.Generic;
namespace SharpKit.JavaScript.Ast
{
partial class JsNode
{
public virtual IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsExpression
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsNodeList
{
public override IEnumerable<JsNode> Children()
{
if (Nodes != null) foreach (var x in Nodes) yield return x;
}
}
partial class JsUnit
{
public override IEnumerable<JsNode> Children()
{
if (Statements != null) foreach (var x in Statements) yield return x;
}
}
partial class JsStatement
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsSwitchStatement
{
public override IEnumerable<JsNode> Children()
{
if (Expression != null) yield return Expression;
if (Sections != null) foreach (var x in Sections) yield return x;
}
}
partial class JsSwitchSection
{
public override IEnumerable<JsNode> Children()
{
if (Labels != null) foreach (var x in Labels) yield return x;
if (Statements != null) foreach (var x in Statements) yield return x;
}
}
partial class JsSwitchLabel
{
public override IEnumerable<JsNode> Children()
{
if (Expression != null) yield return Expression;
}
}
partial class JsWhileStatement
{
public override IEnumerable<JsNode> Children()
{
if (Condition != null) yield return Condition;
if (Statement != null) yield return Statement;
}
}
partial class JsDoWhileStatement
{
public override IEnumerable<JsNode> Children()
{
if (Condition != null) yield return Condition;
if (Statement != null) yield return Statement;
}
}
partial class JsIfStatement
{
public override IEnumerable<JsNode> Children()
{
if (Condition != null) yield return Condition;
if (IfStatement != null) yield return IfStatement;
if (ElseStatement != null) yield return ElseStatement;
}
}
partial class JsForStatement
{
public override IEnumerable<JsNode> Children()
{
if (Initializers != null)
foreach (var x in Initializers)
yield return x;
if (Condition != null) yield return Condition;
if (Iterators != null)
foreach (var x in Iterators)
yield return x;
if (Statement != null) yield return Statement;
}
}
partial class JsForInStatement
{
public override IEnumerable<JsNode> Children()
{
if (Initializer != null) yield return Initializer;
if (Member != null) yield return Member;
if (Statement != null) yield return Statement;
}
}
partial class JsContinueStatement
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsBlock
{
public override IEnumerable<JsNode> Children()
{
if (Statements != null) foreach (var x in Statements) yield return x;
}
}
partial class JsThrowStatement
{
public override IEnumerable<JsNode> Children()
{
if (Expression != null) yield return Expression;
}
}
partial class JsTryStatement
{
public override IEnumerable<JsNode> Children()
{
if (TryBlock != null) yield return TryBlock;
if (CatchClause != null) yield return CatchClause;
if (FinallyBlock != null) yield return FinallyBlock;
}
}
partial class JsBreakStatement
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsExpressionStatement
{
public override IEnumerable<JsNode> Children()
{
if (Expression != null) yield return Expression;
}
}
partial class JsReturnStatement
{
public override IEnumerable<JsNode> Children()
{
if (Expression != null) yield return Expression;
}
}
partial class JsVariableDeclarationStatement
{
public override IEnumerable<JsNode> Children()
{
if (Declaration != null) yield return Declaration;
}
}
partial class JsCommentStatement
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsConditionalExpression
{
public override IEnumerable<JsNode> Children()
{
if (Condition != null) yield return Condition;
if (TrueExpression != null) yield return TrueExpression;
if (FalseExpression != null) yield return FalseExpression;
}
}
partial class JsAssignmentExpression
{
public override IEnumerable<JsNode> Children()
{
if (Left != null) yield return Left;
if (Right != null) yield return Right;
}
}
partial class JsParenthesizedExpression
{
public override IEnumerable<JsNode> Children()
{
if (Expression != null) yield return Expression;
}
}
partial class JsBinaryExpression
{
public override IEnumerable<JsNode> Children()
{
if (Left != null) yield return Left;
if (Right != null) yield return Right;
}
}
partial class JsPostUnaryExpression
{
public override IEnumerable<JsNode> Children()
{
if (Left != null) yield return Left;
}
}
partial class JsPreUnaryExpression
{
public override IEnumerable<JsNode> Children()
{
if (Right != null) yield return Right;
}
}
partial class JsJsonObjectExpression
{
public override IEnumerable<JsNode> Children()
{
if (NamesValues != null) foreach (var x in NamesValues) yield return x;
}
}
partial class JsStringExpression
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsNumberExpression
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsRegexExpression
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsNullExpression
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsVariableDeclarationExpression
{
public override IEnumerable<JsNode> Children()
{
if (Declarators != null) foreach (var x in Declarators) yield return x;
}
}
partial class JsVariableDeclarator
{
public override IEnumerable<JsNode> Children()
{
if (Initializer != null) yield return Initializer;
}
}
partial class JsNewObjectExpression
{
public override IEnumerable<JsNode> Children()
{
if (Invocation != null) yield return Invocation;
}
}
partial class JsFunction
{
public override IEnumerable<JsNode> Children()
{
if (Block != null) yield return Block;
}
}
partial class JsInvocationExpression
{
public override IEnumerable<JsNode> Children()
{
if (Member != null) yield return Member;
if (Arguments != null) foreach (var x in Arguments) yield return x;
}
}
partial class JsIndexerAccessExpression
{
public override IEnumerable<JsNode> Children()
{
if (Member != null) yield return Member;
if (Arguments != null) foreach (var x in Arguments) yield return x;
}
}
partial class JsMemberExpression
{
public override IEnumerable<JsNode> Children()
{
if (PreviousMember != null) yield return PreviousMember;
}
}
partial class JsThis
{
public override IEnumerable<JsNode> Children()
{
if (PreviousMember != null) yield return PreviousMember;
}
}
partial class JsJsonArrayExpression
{
public override IEnumerable<JsNode> Children()
{
if (Items != null) foreach (var x in Items) yield return x;
}
}
partial class JsStatementExpressionList
{
public override IEnumerable<JsNode> Children()
{
if (Expressions != null) foreach (var x in Expressions) yield return x;
}
}
partial class JsCatchClause
{
public override IEnumerable<JsNode> Children()
{
if (Block != null) yield return Block;
}
}
partial class JsJsonMember
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsCodeExpression
{
public override IEnumerable<JsNode> Children()
{
yield break;
}
}
partial class JsJsonNameValue
{
public override IEnumerable<JsNode> Children()
{
if (Name != null) yield return Name;
if (Value != null) yield return Value;
}
}
partial class JsExternalFileUnit
{
public override IEnumerable<JsNode> Children()
{
if (Statements != null) foreach (var x in Statements) yield return x;
}
}
}
| |
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 WebApiSample.Mvvm.WebApi.Areas.HelpPage.ModelDescriptions;
using WebApiSample.Mvvm.WebApi.Areas.HelpPage.Models;
namespace WebApiSample.Mvvm.WebApi.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) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Scheduler;
using Microsoft.WindowsAzure.Management.Scheduler.Models;
namespace Microsoft.WindowsAzure.Management.Scheduler
{
internal partial class JobCollectionOperations : IServiceOperations<SchedulerManagementClient>, Microsoft.WindowsAzure.Management.Scheduler.IJobCollectionOperations
{
/// <summary>
/// Initializes a new instance of the JobCollectionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal JobCollectionOperations(SchedulerManagementClient client)
{
this._client = client;
}
private SchedulerManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Scheduler.SchedulerManagementClient.
/// </summary>
public SchedulerManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Job Collection
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Create Job Collection operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.JobCollectionCreateResponse> BeginCreatingAsync(string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (jobCollectionName.Length > 100)
{
throw new ArgumentOutOfRangeException("jobCollectionName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + cloudServiceName.Trim() + "/resources/scheduler/JobCollections/" + jobCollectionName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
if (parameters.SchemaVersion != null)
{
XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
schemaVersionElement.Value = parameters.SchemaVersion;
resourceElement.Add(schemaVersionElement);
}
if (parameters.IntrinsicSettings != null)
{
XElement intrinsicSettingsElement = new XElement(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure"));
resourceElement.Add(intrinsicSettingsElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.IntrinsicSettings.Plan.ToString();
intrinsicSettingsElement.Add(planElement);
if (parameters.IntrinsicSettings.Quota != null)
{
XElement quotaElement = new XElement(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure"));
intrinsicSettingsElement.Add(quotaElement);
if (parameters.IntrinsicSettings.Quota.MaxJobCount != null)
{
XElement maxJobCountElement = new XElement(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure"));
maxJobCountElement.Value = parameters.IntrinsicSettings.Quota.MaxJobCount.ToString();
quotaElement.Add(maxJobCountElement);
}
if (parameters.IntrinsicSettings.Quota.MaxJobOccurrence != null)
{
XElement maxJobOccurrenceElement = new XElement(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure"));
maxJobOccurrenceElement.Value = parameters.IntrinsicSettings.Quota.MaxJobOccurrence.ToString();
quotaElement.Add(maxJobOccurrenceElement);
}
if (parameters.IntrinsicSettings.Quota.MaxRecurrence != null)
{
XElement maxRecurrenceElement = new XElement(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure"));
quotaElement.Add(maxRecurrenceElement);
XElement frequencyElement = new XElement(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure"));
frequencyElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString();
maxRecurrenceElement.Add(frequencyElement);
XElement intervalElement = new XElement(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure"));
intervalElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString();
maxRecurrenceElement.Add(intervalElement);
}
}
}
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = TypeConversion.ToBase64String(parameters.Label);
resourceElement.Add(labelElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionCreateResponse result = null;
result = new JobCollectionCreateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> BeginDeletingAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + cloudServiceName.Trim() + "/resources/scheduler/JobCollections/" + jobCollectionName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Job Collection
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Update Job Collection operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.JobCollectionUpdateResponse> BeginUpdatingAsync(string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (jobCollectionName.Length > 100)
{
throw new ArgumentOutOfRangeException("jobCollectionName");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.ETag == null)
{
throw new ArgumentNullException("parameters.ETag");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + cloudServiceName.Trim() + "/resources/scheduler/JobCollections/" + jobCollectionName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.TryAddWithoutValidation("If-Match", parameters.ETag);
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
XDocument requestDoc = new XDocument();
XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
requestDoc.Add(resourceElement);
if (parameters.SchemaVersion != null)
{
XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
schemaVersionElement.Value = parameters.SchemaVersion;
resourceElement.Add(schemaVersionElement);
}
XElement eTagElement = new XElement(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
resourceElement.Add(eTagElement);
if (parameters.IntrinsicSettings != null)
{
XElement intrinsicSettingsElement = new XElement(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure"));
resourceElement.Add(intrinsicSettingsElement);
XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
planElement.Value = parameters.IntrinsicSettings.Plan.ToString();
intrinsicSettingsElement.Add(planElement);
if (parameters.IntrinsicSettings.Quota != null)
{
XElement quotaElement = new XElement(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure"));
intrinsicSettingsElement.Add(quotaElement);
if (parameters.IntrinsicSettings.Quota.MaxJobCount != null)
{
XElement maxJobCountElement = new XElement(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure"));
maxJobCountElement.Value = parameters.IntrinsicSettings.Quota.MaxJobCount.ToString();
quotaElement.Add(maxJobCountElement);
}
if (parameters.IntrinsicSettings.Quota.MaxJobOccurrence != null)
{
XElement maxJobOccurrenceElement = new XElement(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure"));
maxJobOccurrenceElement.Value = parameters.IntrinsicSettings.Quota.MaxJobOccurrence.ToString();
quotaElement.Add(maxJobOccurrenceElement);
}
if (parameters.IntrinsicSettings.Quota.MaxRecurrence != null)
{
XElement maxRecurrenceElement = new XElement(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure"));
quotaElement.Add(maxRecurrenceElement);
XElement frequencyElement = new XElement(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure"));
frequencyElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString();
maxRecurrenceElement.Add(frequencyElement);
XElement intervalElement = new XElement(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure"));
intervalElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString();
maxRecurrenceElement.Add(intervalElement);
}
}
}
if (parameters.Label != null)
{
XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
labelElement.Value = TypeConversion.ToBase64String(parameters.Label);
resourceElement.Add(labelElement);
}
requestContent = requestDoc.ToString();
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionUpdateResponse result = null;
result = new JobCollectionUpdateResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("ETag"))
{
result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault();
}
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Determine if the JobCollection name is available to be used.
/// JobCollection names must be unique within a cloud-service.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. A name for the JobCollection. The name must be unique as
/// scoped within the CloudService. The name can be up to 100
/// characters in length.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Check Name Availability operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.JobCollectionCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
if (jobCollectionName.Length > 100)
{
throw new ArgumentOutOfRangeException("jobCollectionName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "CheckNameAvailabilityAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + cloudServiceName.Trim() + "/resources/scheduler/JobCollections/?";
url = url + "op=checknameavailability";
url = url + "&resourceName=" + Uri.EscapeDataString(jobCollectionName.Trim());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionCheckNameAvailabilityResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobCollectionCheckNameAvailabilityResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement resourceNameAvailabilityResponseElement = responseDoc.Element(XName.Get("ResourceNameAvailabilityResponse", "http://schemas.microsoft.com/windowsazure"));
if (resourceNameAvailabilityResponseElement != null)
{
XElement isAvailableElement = resourceNameAvailabilityResponseElement.Element(XName.Get("IsAvailable", "http://schemas.microsoft.com/windowsazure"));
if (isAvailableElement != null)
{
bool isAvailableInstance = bool.Parse(isAvailableElement.Value);
result.IsAvailable = isAvailableInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Create a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to create.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Create Job Collection
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.SchedulerOperationStatusResponse> CreateAsync(string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters, CancellationToken cancellationToken)
{
SchedulerManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
JobCollectionCreateResponse response = await client.JobCollections.BeginCreatingAsync(cloudServiceName, jobCollectionName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != SchedulerOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != SchedulerOperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
}
result.ETag = response.ETag;
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// Deletes a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to delete.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.SchedulerOperationStatusResponse> DeleteAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
SchedulerManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
OperationResponse response = await client.JobCollections.BeginDeletingAsync(cloudServiceName, jobCollectionName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != SchedulerOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != SchedulerOperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
/// <summary>
/// Retreive a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. Name of the cloud service.
/// </param>
/// <param name='jobCollectionName'>
/// Required. Name of the job collection.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Job Collection operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.JobCollectionGetResponse> GetAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken)
{
// Validate
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (jobCollectionName == null)
{
throw new ArgumentNullException("jobCollectionName");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/cloudservices/" + cloudServiceName.Trim() + "/resources/scheduler/~/JobCollections/" + jobCollectionName.Trim();
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
JobCollectionGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new JobCollectionGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement resourceElement = responseDoc.Element(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure"));
if (resourceElement != null)
{
XElement nameElement = resourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
string nameInstance = nameElement.Value;
result.Name = nameInstance;
}
XElement eTagElement = resourceElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure"));
if (eTagElement != null)
{
string eTagInstance = eTagElement.Value;
result.ETag = eTagInstance;
}
XElement stateElement = resourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
JobCollectionState stateInstance = ((JobCollectionState)Enum.Parse(typeof(JobCollectionState), stateElement.Value, true));
result.State = stateInstance;
}
XElement schemaVersionElement = resourceElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure"));
if (schemaVersionElement != null)
{
string schemaVersionInstance = schemaVersionElement.Value;
result.SchemaVersion = schemaVersionInstance;
}
XElement promotionCodeElement = resourceElement.Element(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure"));
if (promotionCodeElement != null)
{
string promotionCodeInstance = promotionCodeElement.Value;
result.PromotionCode = promotionCodeInstance;
}
XElement intrinsicSettingsElement = resourceElement.Element(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure"));
if (intrinsicSettingsElement != null)
{
JobCollectionIntrinsicSettings intrinsicSettingsInstance = new JobCollectionIntrinsicSettings();
result.IntrinsicSettings = intrinsicSettingsInstance;
XElement planElement = intrinsicSettingsElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure"));
if (planElement != null)
{
JobCollectionPlan planInstance = ((JobCollectionPlan)Enum.Parse(typeof(JobCollectionPlan), planElement.Value, true));
intrinsicSettingsInstance.Plan = planInstance;
}
XElement quotaElement = intrinsicSettingsElement.Element(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure"));
if (quotaElement != null)
{
JobCollectionQuota quotaInstance = new JobCollectionQuota();
intrinsicSettingsInstance.Quota = quotaInstance;
XElement maxJobCountElement = quotaElement.Element(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure"));
if (maxJobCountElement != null && string.IsNullOrEmpty(maxJobCountElement.Value) == false)
{
int maxJobCountInstance = int.Parse(maxJobCountElement.Value, CultureInfo.InvariantCulture);
quotaInstance.MaxJobCount = maxJobCountInstance;
}
XElement maxJobOccurrenceElement = quotaElement.Element(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure"));
if (maxJobOccurrenceElement != null && string.IsNullOrEmpty(maxJobOccurrenceElement.Value) == false)
{
int maxJobOccurrenceInstance = int.Parse(maxJobOccurrenceElement.Value, CultureInfo.InvariantCulture);
quotaInstance.MaxJobOccurrence = maxJobOccurrenceInstance;
}
XElement maxRecurrenceElement = quotaElement.Element(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure"));
if (maxRecurrenceElement != null)
{
JobCollectionMaxRecurrence maxRecurrenceInstance = new JobCollectionMaxRecurrence();
quotaInstance.MaxRecurrence = maxRecurrenceInstance;
XElement frequencyElement = maxRecurrenceElement.Element(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure"));
if (frequencyElement != null)
{
JobCollectionRecurrenceFrequency frequencyInstance = ((JobCollectionRecurrenceFrequency)Enum.Parse(typeof(JobCollectionRecurrenceFrequency), frequencyElement.Value, true));
maxRecurrenceInstance.Frequency = frequencyInstance;
}
XElement intervalElement = maxRecurrenceElement.Element(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure"));
if (intervalElement != null)
{
int intervalInstance = int.Parse(intervalElement.Value, CultureInfo.InvariantCulture);
maxRecurrenceInstance.Interval = intervalInstance;
}
}
}
}
XElement labelElement = resourceElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure"));
if (labelElement != null)
{
string labelInstance = TypeConversion.FromBase64String(labelElement.Value);
result.Label = labelInstance;
}
XElement operationStatusElement = resourceElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure"));
if (operationStatusElement != null)
{
JobCollectionGetResponse.OperationStatus operationStatusInstance = new JobCollectionGetResponse.OperationStatus();
result.LastOperationStatus = operationStatusInstance;
XElement errorElement = operationStatusElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
JobCollectionGetResponse.OperationStatusResponseDetails errorInstance = new JobCollectionGetResponse.OperationStatusResponseDetails();
operationStatusInstance.ResponseDetails = errorInstance;
XElement httpCodeElement = errorElement.Element(XName.Get("HttpCode", "http://schemas.microsoft.com/windowsazure"));
if (httpCodeElement != null)
{
HttpStatusCode httpCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpCodeElement.Value, true));
errorInstance.StatusCode = httpCodeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure"));
if (resultElement != null)
{
SchedulerOperationStatus resultInstance = ((SchedulerOperationStatus)Enum.Parse(typeof(SchedulerOperationStatus), resultElement.Value, true));
operationStatusInstance.Status = resultInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a job collection.
/// </summary>
/// <param name='cloudServiceName'>
/// Required. The name of the cloud service containing the job
/// collection.
/// </param>
/// <param name='jobCollectionName'>
/// Required. The name of the job collection to update.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Update Job Collection
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.SchedulerOperationStatusResponse> UpdateAsync(string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters, CancellationToken cancellationToken)
{
SchedulerManagementClient client = this.Client;
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cloudServiceName", cloudServiceName);
tracingParameters.Add("jobCollectionName", jobCollectionName);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters);
}
try
{
if (shouldTrace)
{
client = this.Client.WithHandler(new ClientRequestTrackingHandler(invocationId));
}
cancellationToken.ThrowIfCancellationRequested();
JobCollectionUpdateResponse response = await client.JobCollections.BeginUpdatingAsync(cloudServiceName, jobCollectionName, parameters, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 15;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while ((result.Status != SchedulerOperationStatus.InProgress) == false)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 10;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
if (result.Status != SchedulerOperationStatus.Succeeded)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.ErrorCode = result.Error.Code;
ex.ErrorMessage = result.Error.Message;
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
}
result.ETag = response.ETag;
return result;
}
finally
{
if (client != null && shouldTrace)
{
client.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.NetworkInformation.Tests
{
public class NetworkInterfaceBasicTest
{
private readonly ITestOutputHelper _log;
public NetworkInterfaceBasicTest()
{
_log = TestLogging.GetInstance();
}
[Fact]
public void BasicTest_GetNetworkInterfaces_AtLeastOne()
{
Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX
public void BasicTest_AccessInstanceProperties_NoExceptions()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
_log.WriteLine("Description: " + nic.Description);
_log.WriteLine("ID: " + nic.Id);
_log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
_log.WriteLine("Speed: " + nic.Speed);
// Validate NIC speed overflow.
// We've found that certain WiFi adapters will return speed of -1 when not connected.
// We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up.
Assert.InRange(nic.Speed, -1, long.MaxValue);
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux
public void BasicTest_AccessInstanceProperties_NoExceptions_Linux()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
string description = nic.Description;
Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty.");
_log.WriteLine("Description: " + description);
string id = nic.Id;
Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty.");
_log.WriteLine("ID: " + id);
Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
try
{
_log.WriteLine("Speed: " + nic.Speed);
Assert.InRange(nic.Speed, -1, long.MaxValue);
}
// We cannot guarantee this works on all devices.
catch (PlatformNotSupportedException pnse)
{
_log.WriteLine(pnse.ToString());
}
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)]
public void BasicTest_AccessInstanceProperties_NoExceptions_Bsd()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
_log.WriteLine("- NetworkInterface -");
_log.WriteLine("Name: " + nic.Name);
string description = nic.Description;
Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty.");
_log.WriteLine("Description: " + description);
string id = nic.Id;
Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty.");
_log.WriteLine("ID: " + id);
Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly);
_log.WriteLine("Type: " + nic.NetworkInterfaceType);
_log.WriteLine("Status: " + nic.OperationalStatus);
_log.WriteLine("Speed: " + nic.Speed);
Assert.InRange(nic.Speed, 0, long.MaxValue);
_log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast);
_log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress());
if (nic.Name.StartsWith("en") || nic.Name == "lo0")
{
// Ethernet, WIFI and loopback should have known status.
Assert.True((nic.OperationalStatus == OperationalStatus.Up) || (nic.OperationalStatus == OperationalStatus.Down));
}
}
}
[Fact]
[Trait("IPv4", "true")]
public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.Loopback))
{
Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index,
NetworkInterface.LoopbackInterfaceIndex);
return; // Only check IPv4 loopback
}
}
}
}
[Fact]
[Trait("IPv4", "true")]
public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported()
{
Assert.True(Capability.IPv4Support());
_log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex);
}
[Fact]
[Trait("IPv6", "true")]
public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.Equals(IPAddress.IPv6Loopback))
{
Assert.Equal<int>(
nic.GetIPProperties().GetIPv6Properties().Index,
NetworkInterface.IPv6LoopbackInterfaceIndex);
return; // Only check IPv6 loopback.
}
}
}
}
[Fact]
[Trait("IPv6", "true")]
public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported()
{
Assert.True(Capability.IPv6Support());
_log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX
public void BasicTest_GetIPInterfaceStatistics_Success()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
_log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
_log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent);
_log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 and https://github.com/Microsoft/WSL/issues/3561
[PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux
public void BasicTest_GetIPInterfaceStatistics_Success_Linux()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent);
_log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)]
public void BasicTest_GetIPInterfaceStatistics_Success_Bsd()
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceStatistics stats = nic.GetIPStatistics();
_log.WriteLine("- Stats for : " + nic.Name);
_log.WriteLine("BytesReceived: " + stats.BytesReceived);
_log.WriteLine("BytesSent: " + stats.BytesSent);
_log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded);
_log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors);
_log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets);
_log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived);
_log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent);
Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded);
_log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors);
_log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength);
_log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived);
_log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent);
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 and https://github.com/Microsoft/WSL/issues/3561
public void BasicTest_GetIsNetworkAvailable_Success()
{
Assert.True(NetworkInterface.GetIsNetworkAvailable());
}
[Theory]
[PlatformSpecific(~(TestPlatforms.OSX|TestPlatforms.FreeBSD))]
[InlineData(false)]
[InlineData(true)]
public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6)
{
using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp))
using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp))
{
server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
var serverEndPoint = (IPEndPoint)server.LocalEndPoint;
Task<SocketReceiveMessageFromResult> receivedTask =
server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint);
while (!receivedTask.IsCompleted)
{
client.SendTo(new byte[] { 42 }, serverEndPoint);
await Task.Delay(1);
}
Assert.Equal(
(await receivedTask).PacketInformation.Interface,
ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex);
}
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[ActiveIssue(20470, TargetFrameworkMonikers.UapAot)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "NetEventSource is only part of .NET Core.")]
public class DiagnosticsTest : RemoteExecutorTestBase
{
[Fact]
public static void EventSource_ExistsWithCorrectId()
{
Type esType = typeof(HttpClient).GetTypeInfo().Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false);
Assert.NotNull(esType);
Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType));
Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType));
Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest"));
}
// Diagnostic tests are each invoked in their own process as they enable/disable
// process-wide EventSource-based tracing, and other tests in the same process
// could interfere with the tests, as well as the enabling of tracing interfering
// with those tests.
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
Guid requestGuid = Guid.Empty;
bool responseLogged = false;
Guid responseGuid = Guid.Empty;
bool exceptionLogged = false;
bool activityLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
exceptionLogged = true;
}
else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut"))
{
activityLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable( s => !s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
Assert.True(requestLogged, "Request was not logged.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
Assert.Equal(requestGuid, responseGuid);
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNoLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
Task<HttpResponseMessage> response = client.GetAsync(url);
await Task.WhenAll(response, requestLines);
AssertNoHeadersAreInjected(requestLines.Result);
response.Result.Dispose();
}).Wait();
}
Assert.False(requestLogged, "Request was logged while logging disabled.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled.");
WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled.");
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled.");
}
return SuccessExitCode;
}).Dispose();
}
[ActiveIssue(23771, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_HttpTracingEnabled_Succeeds()
{
RemoteInvoke(async () =>
{
using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose))
{
var events = new ConcurrentQueue<EventWrittenEventArgs>();
await listener.RunWithCallbackAsync(events.Enqueue, async () =>
{
// Exercise various code paths to get coverage of tracing
using (var client = new HttpClient())
{
// Do a get to a loopback server
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
LoopbackServer.ReadRequestAndSendResponseAsync(server),
client.GetAsync(url));
});
// Do a post to a remote server
byte[] expectedData = Enumerable.Range(0, 20000).Select(i => unchecked((byte)i)).ToArray();
HttpContent content = new ByteArrayContent(expectedData);
content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData);
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.RemoteEchoServer, content))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
// We don't validate receiving specific events, but rather that we do at least
// receive some events, and that enabling tracing doesn't cause other failures
// in processing.
Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages
Assert.InRange(events.Count, 1, int.MaxValue);
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionLogging()
{
RemoteInvoke(() =>
{
bool exceptionLogged = false;
bool responseLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
responseLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledLogging()
{
RemoteInvoke(() =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
Volatile.Write(ref cancelLogged, true);
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
CancellationTokenSource tcs = new CancellationTokenSource();
Task request = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) =>
{
tcs.Cancel();
return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
});
Task response = client.GetAsync(url, tcs.Token);
await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request));
}).Wait();
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceActivityLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
bool exceptionLogged = false;
Activity parentActivity = new Activity("parent");
parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString());
parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString());
parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request
parentActivity.Start();
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
activityStartLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
Assert.NotNull(Activity.Current);
Assert.Equal(parentActivity, Activity.Current.Parent);
Assert.True(Activity.Current.Duration != TimeSpan.Zero);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.RanToCompletion, requestStatus);
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut"));
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
Task<List<string>> requestLines = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) => LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer));
Task<HttpResponseMessage> response = client.GetAsync(url);
await Task.WhenAll(response, requestLines);
AssertHeadersAreInjected(requestLines.Result, parentActivity);
response.Result.Dispose();
}).Wait();
}
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
Assert.False(requestLogged, "Request was logged when Activity logging was enabled.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.False(exceptionLogged, "Exception was logged for successful request");
Assert.False(responseLogged, "Response was logged when Activity logging was enabled.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging()
{
RemoteInvoke(() =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")){activityStartLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) {activityStopLogged = true;}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable((s, r, _) =>
{
if (s.StartsWith("System.Net.Http.HttpRequestOut"))
{
var request = r as HttpRequestMessage;
if (request != null)
return !request.RequestUri.Equals(Configuration.Http.RemoteEchoServer);
}
return true;
});
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled.");
// Poll with a timeout since logging response is not synchronized with returning a response.
Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionActivityLogging()
{
RemoteInvoke(() =>
{
bool exceptionLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Faulted, requestStatus);
activityStopLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"Response with exception was not logged within 1 second timeout.");
Assert.True(exceptionLogged, "Exception was not logged");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging()
{
RemoteInvoke(() =>
{
bool requestLogged = false;
bool responseLogged = false;
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true;}
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; }
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged.");
Assert.True(requestLogged, "Request was not logged.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.True(responseLogged, "Response was not logged.");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging()
{
RemoteInvoke(() =>
{
bool exceptionLogged = false;
bool activityLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.Exception"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception");
exceptionLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception"));
using (var client = new HttpClient())
{
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://{Guid.NewGuid()}.com")).Wait();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1),
"Exception was not logged within 1 second timeout.");
Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging()
{
RemoteInvoke(() =>
{
bool activityStartLogged = false;
bool activityStopLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; }
else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop"))
{
Assert.NotNull(Activity.Current);
activityStopLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut"));
using (var client = new HttpClient())
{
client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose();
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1),
"HttpRequestOut.Stop was not logged within 1 second timeout.");
Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled");
diagnosticListenerObserver.Disable();
}
return SuccessExitCode;
}).Dispose();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SendAsync_ExpectedDiagnosticCancelledActivityLogging()
{
RemoteInvoke(() =>
{
bool cancelLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp =>
{
if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop")
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus");
Assert.Equal(TaskStatus.Canceled, status);
Volatile.Write(ref cancelLogged, true);
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
LoopbackServer.CreateServerAsync(async (server, url) =>
{
CancellationTokenSource tcs = new CancellationTokenSource();
Task request = LoopbackServer.AcceptSocketAsync(server,
(s, stream, reader, writer) =>
{
tcs.Cancel();
return LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer);
});
Task response = client.GetAsync(url, tcs.Token);
await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request));
}).Wait();
}
}
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1),
"Cancellation was not logged within 1 second timeout.");
diagnosticListenerObserver.Disable();
return SuccessExitCode;
}).Dispose();
}
private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName)
{
Type t = obj.GetType();
PropertyInfo p = t.GetRuntimeProperty(propertyName);
object propertyValue = p.GetValue(obj);
Assert.NotNull(propertyValue);
Assert.IsAssignableFrom<T>(propertyValue);
return (T)propertyValue;
}
private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin doesn't time out.
Assert.True(SpinWait.SpinUntil(p, timeout), message);
}
private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin times out.
Assert.False(SpinWait.SpinUntil(p, timeout), message);
}
private void AssertHeadersAreInjected(List<string> requestLines, Activity parent)
{
string requestId = null;
var correlationContext = new List<NameValueHeaderValue>();
foreach (var line in requestLines)
{
if (line.StartsWith("Request-Id"))
{
requestId = line.Substring("Request-Id".Length).Trim(' ', ':');
}
if (line.StartsWith("Correlation-Context"))
{
var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':');
foreach (var kvp in corrCtxString.Split(','))
{
correlationContext.Add(NameValueHeaderValue.Parse(kvp));
}
}
}
Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled");
Assert.True(requestId.StartsWith(parent.Id));
Assert.NotEqual(parent.Id, requestId);
List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList();
Assert.Equal(baggage.Count, correlationContext.Count);
foreach (var kvp in baggage)
{
Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext);
}
}
private void AssertNoHeadersAreInjected(List<string> requestLines)
{
foreach (var line in requestLines)
{
Assert.False(line.StartsWith("Request-Id"),
"Request-Id header was injected when instrumentation was disabled");
Assert.False(line.StartsWith("Correlation-Context"),
"Correlation-Context header was injected when instrumentation was disabled");
}
}
}
}
| |
// 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.Runtime.Serialization
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Runtime.CompilerServices;
using System.Text;
using System.Security;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
public abstract class XmlObjectSerializer
{
public abstract void WriteStartObject(XmlDictionaryWriter writer, object graph);
public abstract void WriteObjectContent(XmlDictionaryWriter writer, object graph);
public abstract void WriteEndObject(XmlDictionaryWriter writer);
public virtual void WriteObject(Stream stream, object graph)
{
CheckNull(stream, nameof(stream));
XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/);
WriteObject(writer, graph);
writer.Flush();
}
public virtual void WriteObject(XmlWriter writer, object graph)
{
CheckNull(writer, nameof(writer));
WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
}
public virtual void WriteStartObject(XmlWriter writer, object graph)
{
CheckNull(writer, nameof(writer));
WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
}
public virtual void WriteObjectContent(XmlWriter writer, object graph)
{
CheckNull(writer, nameof(writer));
WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph);
}
public virtual void WriteEndObject(XmlWriter writer)
{
CheckNull(writer, nameof(writer));
WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer));
}
public virtual void WriteObject(XmlDictionaryWriter writer, object graph)
{
WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph);
}
internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph)
{
WriteObjectHandleExceptions(writer, graph, null);
}
internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
try
{
CheckNull(writer, nameof(writer));
{
InternalWriteObject(writer, graph, dataContractResolver);
}
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
}
internal virtual DataContractDictionary KnownDataContracts
{
get
{
return null;
}
}
internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph)
{
WriteStartObject(writer.Writer, graph);
WriteObjectContent(writer.Writer, graph);
WriteEndObject(writer.Writer);
}
internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver)
{
InternalWriteObject(writer, graph);
}
internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object graph)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteStartObject should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object graph)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteObjectContent should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
internal virtual void InternalWriteEndObject(XmlWriterDelegator writer)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteEndObject should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object graph)
{
try
{
CheckNull(writer, nameof(writer));
InternalWriteStartObject(writer, graph);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteStartObject, GetSerializeType(graph), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteStartObject, GetSerializeType(graph), ex), ex));
}
}
internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object graph)
{
try
{
CheckNull(writer, nameof(writer));
{
if (writer.WriteState != WriteState.Element)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlWriterMustBeInElement, writer.WriteState)));
InternalWriteObjectContent(writer, graph);
}
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorSerializing, GetSerializeType(graph), ex), ex));
}
}
internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer)
{
try
{
CheckNull(writer, nameof(writer));
InternalWriteEndObject(writer);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteEndObject, null, ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorWriteEndObject, null, ex), ex));
}
}
internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns, bool needsContractNsAtRoot)
{
if (name == null) // root name not set explicitly
{
if (!contract.HasRoot)
return;
contract.WriteRootElement(writer, contract.TopLevelElementName, contract.TopLevelElementNamespace);
}
else
{
contract.WriteRootElement(writer, name, ns);
if (needsContractNsAtRoot)
{
writer.WriteNamespaceDecl(contract.Namespace);
}
}
}
internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract)
{
if (name == null)
return false;
if (contract.IsBuiltInDataContract || !contract.CanContainReferences)
{
return false;
}
string contractNs = XmlDictionaryString.GetString(contract.Namespace);
if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns))
return false;
return true;
}
internal static void WriteNull(XmlWriterDelegator writer)
{
writer.WriteAttributeBool(Globals.XsiPrefix, DictionaryGlobals.XsiNilLocalName, DictionaryGlobals.SchemaInstanceNamespace, true);
}
internal static bool IsContractDeclared(DataContract contract, DataContract declaredContract)
{
return (object.ReferenceEquals(contract.Name, declaredContract.Name) && object.ReferenceEquals(contract.Namespace, declaredContract.Namespace))
|| (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value);
}
public virtual object ReadObject(Stream stream)
{
CheckNull(stream, nameof(stream));
return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max));
}
public virtual object ReadObject(XmlReader reader)
{
CheckNull(reader, nameof(reader));
return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader));
}
public virtual object ReadObject(XmlDictionaryReader reader)
{
return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/);
}
public virtual object ReadObject(XmlReader reader, bool verifyObjectName)
{
CheckNull(reader, nameof(reader));
return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName);
}
public abstract object ReadObject(XmlDictionaryReader reader, bool verifyObjectName);
public virtual bool IsStartObject(XmlReader reader)
{
CheckNull(reader, nameof(reader));
return IsStartObject(XmlDictionaryReader.CreateDictionaryReader(reader));
}
public abstract bool IsStartObject(XmlDictionaryReader reader);
internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName)
{
return ReadObject(reader.UnderlyingReader, verifyObjectName);
}
internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
return InternalReadObject(reader, verifyObjectName);
}
internal virtual bool InternalIsStartObject(XmlReaderDelegator reader)
{
DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalIsStartObject should never get called");
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName)
{
return ReadObjectHandleExceptions(reader, verifyObjectName, null);
}
internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver)
{
try
{
CheckNull(reader, nameof(reader));
return InternalReadObject(reader, verifyObjectName, dataContractResolver);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorDeserializing, GetDeserializeType(), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorDeserializing, GetDeserializeType(), ex), ex));
}
}
internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader)
{
try
{
CheckNull(reader, nameof(reader));
return InternalIsStartObject(reader);
}
catch (XmlException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorIsStartObject, GetDeserializeType(), ex), ex));
}
catch (FormatException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(GetTypeInfoError(SR.ErrorIsStartObject, GetDeserializeType(), ex), ex));
}
}
internal bool IsRootXmlAny(XmlDictionaryString rootName, DataContract contract)
{
return (rootName == null) && !contract.HasRoot;
}
internal bool IsStartElement(XmlReaderDelegator reader)
{
return (reader.MoveToElement() || reader.IsStartElement());
}
internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns)
{
reader.MoveToElement();
if (name != null) // root name set explicitly
{
return reader.IsStartElement(name, ns);
}
else
{
if (!contract.HasRoot)
return reader.IsStartElement();
if (reader.IsStartElement(contract.TopLevelElementName, contract.TopLevelElementNamespace))
return true;
ClassDataContract classContract = contract as ClassDataContract;
if (classContract != null)
classContract = classContract.BaseContract;
while (classContract != null)
{
if (reader.IsStartElement(classContract.TopLevelElementName, classContract.TopLevelElementNamespace))
return true;
classContract = classContract.BaseContract;
}
if (classContract == null)
{
DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject);
if (reader.IsStartElement(objectContract.TopLevelElementName, objectContract.TopLevelElementNamespace))
return true;
}
return false;
}
}
internal static void CheckNull(object obj, string name)
{
if (obj == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(name));
}
internal static string TryAddLineInfo(XmlReaderDelegator reader, string errorMessage)
{
if (reader.HasLineInfo())
return string.Format(CultureInfo.InvariantCulture, "{0} {1}", SR.Format(SR.ErrorInLine, reader.LineNumber, reader.LinePosition), errorMessage);
return errorMessage;
}
internal static Exception CreateSerializationExceptionWithReaderDetails(string errorMessage, XmlReaderDelegator reader)
{
return XmlObjectSerializer.CreateSerializationException(TryAddLineInfo(reader, SR.Format(SR.EncounteredWithNameNamespace, errorMessage, reader.NodeType, reader.LocalName, reader.NamespaceURI)));
}
internal static SerializationException CreateSerializationException(string errorMessage)
{
return XmlObjectSerializer.CreateSerializationException(errorMessage, null);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static SerializationException CreateSerializationException(string errorMessage, Exception innerException)
{
return new SerializationException(errorMessage, innerException);
}
internal static string GetTypeInfoError(string errorMessage, Type type, Exception innerException)
{
string typeInfo = (type == null) ? string.Empty : SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type));
string innerExceptionMessage = (innerException == null) ? string.Empty : innerException.Message;
return SR.Format(errorMessage, typeInfo, innerExceptionMessage);
}
internal virtual Type GetSerializeType(object graph)
{
return (graph == null) ? null : graph.GetType();
}
internal virtual Type GetDeserializeType()
{
return null;
}
private static IFormatterConverter s_formatterConverter;
internal static IFormatterConverter FormatterConverter
{
get
{
if (s_formatterConverter == null)
{
s_formatterConverter = new FormatterConverter();
}
return s_formatterConverter;
}
}
}
}
| |
//! \file ArcPD.cs
//! \date Thu Aug 14 19:10:02 2014
//! \brief PD archive format implementation.
//
// Copyright (C) 2014-2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Text;
using GameRes.Formats.Strings;
using GameRes.Utility;
namespace GameRes.Formats.Fs
{
internal class PackPlusArchive : ArcFile
{
public PackPlusArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir)
: base (arc, impl, dir)
{
}
}
public class PdOptions : ResourceOptions
{
public bool ScrambleContents { get; set; }
}
[Export(typeof(ArchiveFormat))]
public class PdOpener : ArchiveFormat
{
public override string Tag { get { return "PD"; } }
public override string Description { get { return arcStrings.PDDescription; } }
public override uint Signature { get { return 0x6b636150; } } // Pack
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return true; } }
public override ArcFile TryOpen (ArcView file)
{
uint version = file.View.ReadUInt32 (4);
if (0x796c6e4f != version && 0x73756c50 != version) // 'Only' || 'Plus'
return null;
int count = file.View.ReadInt32 (0x40);
if (!IsSaneCount (count) || count * 0x90 >= file.MaxOffset)
return null;
bool encrypted = 0x73756c50 == version;
long cur_offset = 0x48;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
string name = file.View.ReadString (cur_offset, 0x80);
var entry = FormatCatalog.Instance.Create<Entry> (name);
entry.Offset = file.View.ReadInt64 (cur_offset+0x80);
entry.Size = file.View.ReadUInt32 (cur_offset+0x88);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
if (name.HasExtension (".dsf"))
entry.Type = "script";
dir.Add (entry);
cur_offset += 0x90;
}
return encrypted ? new PackPlusArchive (file, this, dir) : new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
Stream input = arc.File.CreateStream (entry.Offset, entry.Size);
if (arc is PackPlusArchive)
input = new XoredStream (input, 0xFF);
return input;
}
public override ResourceOptions GetDefaultOptions ()
{
return new PdOptions { ScrambleContents = Properties.Settings.Default.PDScrambleContents };
}
public override object GetCreationWidget ()
{
return new GUI.CreatePDWidget();
}
public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options,
EntryCallback callback)
{
int file_count = list.Count();
if (file_count > 0x4000)
throw new InvalidFormatException (arcStrings.MsgTooManyFiles);
if (null != callback)
callback (file_count+2, null, null);
int callback_count = 0;
var pd_options = GetOptions<PdOptions> (options);
using (var writer = new BinaryWriter (output, Encoding.ASCII, true))
{
writer.Write (Signature);
if (pd_options.ScrambleContents)
writer.Write ((uint)0x73756c50);
else
writer.Write ((uint)0x796c6e4f);
output.Seek (0x38, SeekOrigin.Current);
writer.Write (file_count);
writer.Write ((int)0);
long dir_offset = output.Position;
if (null != callback)
callback (callback_count++, null, arcStrings.MsgWritingIndex);
var encoding = Encodings.cp932.WithFatalFallback();
byte[] name_buf = new byte[0x80];
int previous_size = 0;
// first, write names only
foreach (var entry in list)
{
string name = Path.GetFileName (entry.Name);
try
{
int size = encoding.GetBytes (name, 0, name.Length, name_buf, 0);
for (int i = size; i < previous_size; ++i)
name_buf[i] = 0;
previous_size = size;
}
catch (EncoderFallbackException X)
{
throw new InvalidFileName (entry.Name, arcStrings.MsgIllegalCharacters, X);
}
catch (ArgumentException X)
{
throw new InvalidFileName (entry.Name, arcStrings.MsgFileNameTooLong, X);
}
writer.Write (name_buf);
writer.BaseStream.Seek (16, SeekOrigin.Current);
}
// now, write files and remember offset/sizes
long current_offset = 0x240000 + dir_offset;
output.Seek (current_offset, SeekOrigin.Begin);
foreach (var entry in list)
{
if (null != callback)
callback (callback_count++, entry, arcStrings.MsgAddingFile);
entry.Offset = current_offset;
using (var input = File.OpenRead (entry.Name))
{
var size = input.Length;
if (size > uint.MaxValue)
throw new FileSizeException();
current_offset += size;
entry.Size = (uint)size;
if (pd_options.ScrambleContents)
CopyScrambled (input, output);
else
input.CopyTo (output);
}
}
if (null != callback)
callback (callback_count++, null, arcStrings.MsgUpdatingIndex);
// at last, go back to directory and write offset/sizes
dir_offset += 0x80;
foreach (var entry in list)
{
writer.BaseStream.Position = dir_offset;
writer.Write (entry.Offset);
writer.Write ((long)entry.Size);
dir_offset += 0x90;
}
}
}
void CopyScrambled (Stream input, Stream output)
{
byte[] buffer = new byte[81920];
for (;;)
{
int read = input.Read (buffer, 0, buffer.Length);
if (0 == read)
break;
for (int i = 0; i < read; ++i)
buffer[i] = (byte)~buffer[i];
output.Write (buffer, 0, read);
}
}
}
[Export(typeof(ArchiveFormat))]
public class FlyingShinePdOpener : ArchiveFormat
{
public override string Tag { get { return "PD/2"; } }
public override string Description { get { return "Flying Shine resource archive version 2"; } }
public override uint Signature { get { return 0x69796c46; } } // 'Flyi'
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
if (!file.View.AsciiEqual (4, "ngShinePDFile\0"))
return null;
uint crc = file.View.ReadUInt16 (0x12);
byte key = file.View.ReadByte (0x14);
int count = file.View.ReadInt32 (0x1c);
if (!IsSaneCount (count))
return null;
uint index_size = (uint)(0x30 * count);
if (index_size > file.View.Reserve (0x20, index_size))
return null;
var enc = Encodings.cp932;
var buf = new byte[0x30];
long index_offset = 0x20;
var dir = new List<Entry> (count);
for (uint i = 0; i < count; ++i)
{
file.View.Read (index_offset, buf, 0, 0x30);
DecodeEntry (buf, key);
int len = Array.IndexOf (buf, (byte)0);
if (len <= 0 || len >= 0x24)
return null;
string name = enc.GetString (buf, 0, len);
var entry = Create<Entry> (name);
uint shift = LittleEndian.ToUInt32 (buf, 0x24);
entry.Offset = LittleEndian.ToUInt32 (buf, 0x28) - shift;
entry.Size = LittleEndian.ToUInt32 (buf, 0x2c) - shift;
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
index_offset += 0x30;
}
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
if (entry.Name.HasExtension (".ogg") && entry.Size > 0x22)
return OpenOgg (arc, entry);
if (!entry.Name.HasAnyOfExtensions (".def", ".dsf") || entry.Size < 2)
return base.OpenEntry (arc, entry);
var data = arc.File.View.ReadBytes (entry.Offset, entry.Size);
byte key = (byte)(data[data.Length-1] ^ 0xA);
if (0xD == (data[data.Length-2] ^ key))
{
DecodeEntry (data, key);
}
return new BinMemoryStream (data);
}
Stream OpenOgg (ArcFile arc, Entry entry)
{
const uint header_length = 0x23;
var header = arc.File.View.ReadBytes (entry.Offset, header_length);
if (!(header.AsciiEqual (0, "OggS") &&
header[0x1A] != 1 && header[0x1B] == 0x1E && header[0x1C] == 1 &&
header.AsciiEqual (0x1D, "vorbis")))
return base.OpenEntry (arc, entry);
header[0x1A] = 1;
var rest = arc.File.CreateStream (entry.Offset+header_length, entry.Size-header_length);
return new PrefixStream (header, rest);
}
void DecodeEntry (byte[] buf, byte key)
{
for (int i = 0; i < buf.Length; ++i)
buf[i] ^= key;
}
}
[Export(typeof(ArchiveFormat))]
public class Pd3Opener : ArchiveFormat
{
public override string Tag { get { return "PD/3"; } }
public override string Description { get { return "Flying Shine resource archive version 3"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
int index_count = file.View.ReadInt32 (0);
int count = file.View.ReadInt32 (4);
uint total_size = file.View.ReadUInt32 (0xC);
if (index_count < count || !IsSaneCount (index_count) || !IsSaneCount (count))
return null;
uint index_size = 0x11C * (uint)index_count;
if (index_size >= file.MaxOffset - 0x18)
return null;
uint index_offset = 0x18;
long base_offset = index_size + index_offset;
if (base_offset + total_size != file.MaxOffset)
return null;
var dir = new List<Entry> (count);
for (int i = 0; i < index_count; ++i)
{
if (0 != file.View.ReadByte (index_offset))
{
var name = file.View.ReadString (index_offset, 0x104);
var entry = FormatCatalog.Instance.Create<Entry> (name);
entry.Size = file.View.ReadUInt32 (index_offset+0x108);
entry.Offset = base_offset + file.View.ReadUInt32 (index_offset+0x10C);
if (!entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
}
index_offset += 0x11C;
}
if (0 == dir.Count)
return null;
return new ArcFile (file, this, dir);
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
if (!entry.Name.HasAnyOfExtensions (".def", ".dsf"))
return base.OpenEntry (arc, entry);
var data = arc.File.View.ReadBytes (entry.Offset, entry.Size);
for (int i = 0; i < data.Length; ++i)
data[i] = Binary.RotByteR (data[i], 4);
return new BinMemoryStream (data);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type float with 3 columns and 2 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct mat3x2 : IEnumerable<float>, IEquatable<mat3x2>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public float m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public float m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public float m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public float m11;
/// <summary>
/// Column 2, Rows 0
/// </summary>
public float m20;
/// <summary>
/// Column 2, Rows 1
/// </summary>
public float m21;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public mat3x2(float m00, float m01, float m10, float m11, float m20, float m21)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
this.m20 = m20;
this.m21 = m21;
}
/// <summary>
/// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = 0f;
this.m21 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = 0f;
this.m21 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = 0f;
this.m21 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(mat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(vec2 c0, vec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = 0f;
this.m21 = 0f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat3x2(vec2 c0, vec2 c1, vec2 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = c2.x;
this.m21 = c2.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public float[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public float[] Values1D => new[] { m00, m01, m10, m11, m20, m21 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public vec2 Column0
{
get
{
return new vec2(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public vec2 Column1
{
get
{
return new vec2(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 2
/// </summary>
public vec2 Column2
{
get
{
return new vec2(m20, m21);
}
set
{
m20 = value.x;
m21 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public vec3 Row0
{
get
{
return new vec3(m00, m10, m20);
}
set
{
m00 = value.x;
m10 = value.y;
m20 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public vec3 Row1
{
get
{
return new vec3(m01, m11, m21);
}
set
{
m01 = value.x;
m11 = value.y;
m21 = value.z;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static mat3x2 Zero { get; } = new mat3x2(0f, 0f, 0f, 0f, 0f, 0f);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static mat3x2 Ones { get; } = new mat3x2(1f, 1f, 1f, 1f, 1f, 1f);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static mat3x2 Identity { get; } = new mat3x2(1f, 0f, 0f, 1f, 0f, 0f);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static mat3x2 AllMaxValue { get; } = new mat3x2(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static mat3x2 DiagonalMaxValue { get; } = new mat3x2(float.MaxValue, 0f, 0f, float.MaxValue, 0f, 0f);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static mat3x2 AllMinValue { get; } = new mat3x2(float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static mat3x2 DiagonalMinValue { get; } = new mat3x2(float.MinValue, 0f, 0f, float.MinValue, 0f, 0f);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static mat3x2 AllEpsilon { get; } = new mat3x2(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static mat3x2 DiagonalEpsilon { get; } = new mat3x2(float.Epsilon, 0f, 0f, float.Epsilon, 0f, 0f);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static mat3x2 AllNaN { get; } = new mat3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static mat3x2 DiagonalNaN { get; } = new mat3x2(float.NaN, 0f, 0f, float.NaN, 0f, 0f);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static mat3x2 AllNegativeInfinity { get; } = new mat3x2(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static mat3x2 DiagonalNegativeInfinity { get; } = new mat3x2(float.NegativeInfinity, 0f, 0f, float.NegativeInfinity, 0f, 0f);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static mat3x2 AllPositiveInfinity { get; } = new mat3x2(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static mat3x2 DiagonalPositiveInfinity { get; } = new mat3x2(float.PositiveInfinity, 0f, 0f, float.PositiveInfinity, 0f, 0f);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<float> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
yield return m20;
yield return m21;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (3 x 2 = 6).
/// </summary>
public int Count => 6;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public float this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
case 4: return m20;
case 5: return m21;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
case 4: this.m20 = value; break;
case 5: this.m21 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public float this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(mat3x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m10.Equals(rhs.m10)) && ((m11.Equals(rhs.m11) && m20.Equals(rhs.m20)) && m21.Equals(rhs.m21)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is mat3x2 && Equals((mat3x2) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(mat3x2 lhs, mat3x2 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(mat3x2 lhs, mat3x2 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public mat2x3 Transposed => new mat2x3(m00, m10, m20, m01, m11, m21);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public float MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public float MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public float Sum => (((m00 + m01) + m10) + ((m11 + m20) + m21));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + Math.Abs(m10)) + ((Math.Abs(m11) + Math.Abs(m20)) + Math.Abs(m21)));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public float NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m20)), Math.Abs(m21));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + Math.Pow((double)Math.Abs(m10), p)) + ((Math.Pow((double)Math.Abs(m11), p) + Math.Pow((double)Math.Abs(m20), p)) + Math.Pow((double)Math.Abs(m21), p))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication mat3x2 * mat2x3 -> mat2.
/// </summary>
public static mat2 operator*(mat3x2 lhs, mat2x3 rhs) => new mat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12));
/// <summary>
/// Executes a matrix-matrix-multiplication mat3x2 * mat3 -> mat3x2.
/// </summary>
public static mat3x2 operator*(mat3x2 lhs, mat3 rhs) => new mat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22));
/// <summary>
/// Executes a matrix-matrix-multiplication mat3x2 * mat4x3 -> mat4x2.
/// </summary>
public static mat4x2 operator*(mat3x2 lhs, mat4x3 rhs) => new mat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static vec2 operator*(mat3x2 m, vec3 v) => new vec2(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static mat3x2 CompMul(mat3x2 A, mat3x2 B) => new mat3x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static mat3x2 CompDiv(mat3x2 A, mat3x2 B) => new mat3x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat3x2 CompAdd(mat3x2 A, mat3x2 B) => new mat3x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat3x2 CompSub(mat3x2 A, mat3x2 B) => new mat3x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat3x2 operator+(mat3x2 lhs, mat3x2 rhs) => new mat3x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat3x2 operator+(mat3x2 lhs, float rhs) => new mat3x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat3x2 operator+(float lhs, mat3x2 rhs) => new mat3x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat3x2 operator-(mat3x2 lhs, mat3x2 rhs) => new mat3x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat3x2 operator-(mat3x2 lhs, float rhs) => new mat3x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat3x2 operator-(float lhs, mat3x2 rhs) => new mat3x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat3x2 operator/(mat3x2 lhs, float rhs) => new mat3x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat3x2 operator/(float lhs, mat3x2 rhs) => new mat3x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat3x2 operator*(mat3x2 lhs, float rhs) => new mat3x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat3x2 operator*(float lhs, mat3x2 rhs) => new mat3x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat3x2 operator<(mat3x2 lhs, mat3x2 rhs) => new bmat3x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator<(mat3x2 lhs, float rhs) => new bmat3x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator<(float lhs, mat3x2 rhs) => new bmat3x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat3x2 operator<=(mat3x2 lhs, mat3x2 rhs) => new bmat3x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator<=(mat3x2 lhs, float rhs) => new bmat3x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator<=(float lhs, mat3x2 rhs) => new bmat3x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat3x2 operator>(mat3x2 lhs, mat3x2 rhs) => new bmat3x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator>(mat3x2 lhs, float rhs) => new bmat3x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator>(float lhs, mat3x2 rhs) => new bmat3x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat3x2 operator>=(mat3x2 lhs, mat3x2 rhs) => new bmat3x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator>=(mat3x2 lhs, float rhs) => new bmat3x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator>=(float lhs, mat3x2 rhs) => new bmat3x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21);
}
}
| |
/*
* 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;
namespace XenAPI
{
/// <summary>
/// A console
/// First published in XenServer 4.0.
/// </summary>
public partial class Console : XenObject<Console>
{
public Console()
{
}
public Console(string uuid,
console_protocol protocol,
string location,
XenRef<VM> VM,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.protocol = protocol;
this.location = location;
this.VM = VM;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Console from a Proxy_Console.
/// </summary>
/// <param name="proxy"></param>
public Console(Proxy_Console proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Console update)
{
uuid = update.uuid;
protocol = update.protocol;
location = update.location;
VM = update.VM;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Console proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
protocol = proxy.protocol == null ? (console_protocol) 0 : (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), (string)proxy.protocol);
location = proxy.location == null ? null : (string)proxy.location;
VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Console ToProxy()
{
Proxy_Console result_ = new Proxy_Console();
result_.uuid = uuid ?? "";
result_.protocol = console_protocol_helper.ToString(protocol);
result_.location = location ?? "";
result_.VM = VM ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Console from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Console(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
protocol = (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), Marshalling.ParseString(table, "protocol"));
location = Marshalling.ParseString(table, "location");
VM = Marshalling.ParseRef<VM>(table, "VM");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Console other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._protocol, other._protocol) &&
Helper.AreEqual2(this._location, other._location) &&
Helper.AreEqual2(this._VM, other._VM) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Console server)
{
if (opaqueRef == null)
{
Proxy_Console p = this.ToProxy();
return session.proxy.console_create(session.uuid, p).parse();
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Console.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static Console get_record(Session session, string _console)
{
return new Console((Proxy_Console)session.proxy.console_get_record(session.uuid, _console ?? "").parse());
}
/// <summary>
/// Get a reference to the console 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<Console> get_by_uuid(Session session, string _uuid)
{
return XenRef<Console>.Create(session.proxy.console_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Create a new console 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<Console> create(Session session, Console _record)
{
return XenRef<Console>.Create(session.proxy.console_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Create a new console 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, Console _record)
{
return XenRef<Task>.Create(session.proxy.async_console_create(session.uuid, _record.ToProxy()).parse());
}
/// <summary>
/// Destroy the specified console instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static void destroy(Session session, string _console)
{
session.proxy.console_destroy(session.uuid, _console ?? "").parse();
}
/// <summary>
/// Destroy the specified console instance.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static XenRef<Task> async_destroy(Session session, string _console)
{
return XenRef<Task>.Create(session.proxy.async_console_destroy(session.uuid, _console ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static string get_uuid(Session session, string _console)
{
return (string)session.proxy.console_get_uuid(session.uuid, _console ?? "").parse();
}
/// <summary>
/// Get the protocol field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static console_protocol get_protocol(Session session, string _console)
{
return (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), (string)session.proxy.console_get_protocol(session.uuid, _console ?? "").parse());
}
/// <summary>
/// Get the location field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static string get_location(Session session, string _console)
{
return (string)session.proxy.console_get_location(session.uuid, _console ?? "").parse();
}
/// <summary>
/// Get the VM field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static XenRef<VM> get_VM(Session session, string _console)
{
return XenRef<VM>.Create(session.proxy.console_get_vm(session.uuid, _console ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
public static Dictionary<string, string> get_other_config(Session session, string _console)
{
return Maps.convert_from_proxy_string_string(session.proxy.console_get_other_config(session.uuid, _console ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _console, Dictionary<string, string> _other_config)
{
session.proxy.console_set_other_config(session.uuid, _console ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given console.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _console, string _key, string _value)
{
session.proxy.console_add_to_other_config(session.uuid, _console ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given console. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_console">The opaque_ref of the given console</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _console, string _key)
{
session.proxy.console_remove_from_other_config(session.uuid, _console ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the consoles known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Console>> get_all(Session session)
{
return XenRef<Console>.Create(session.proxy.console_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the console Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Console>, Console> get_all_records(Session session)
{
return XenRef<Console>.Create<Proxy_Console>(session.proxy.console_get_all_records(session.uuid).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 protocol used by this console
/// </summary>
public virtual console_protocol protocol
{
get { return _protocol; }
set
{
if (!Helper.AreEqual(value, _protocol))
{
_protocol = value;
Changed = true;
NotifyPropertyChanged("protocol");
}
}
}
private console_protocol _protocol;
/// <summary>
/// URI for the console service
/// </summary>
public virtual string location
{
get { return _location; }
set
{
if (!Helper.AreEqual(value, _location))
{
_location = value;
Changed = true;
NotifyPropertyChanged("location");
}
}
}
private string _location;
/// <summary>
/// VM to which this console is attached
/// </summary>
public virtual XenRef<VM> VM
{
get { return _VM; }
set
{
if (!Helper.AreEqual(value, _VM))
{
_VM = value;
Changed = true;
NotifyPropertyChanged("VM");
}
}
}
private XenRef<VM> _VM;
/// <summary>
/// additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Globalization;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Language;
using System.Reflection;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The get-command cmdlet. It uses the command discovery APIs to find one or more
/// commands of the given name. It returns an instance of CommandInfo for each
/// command that is found.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Command", DefaultParameterSetName = "CmdletSet", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113309")]
[OutputType(typeof(AliasInfo), typeof(ApplicationInfo), typeof(FunctionInfo),
typeof(CmdletInfo), typeof(ExternalScriptInfo), typeof(FilterInfo),
typeof(string), typeof(PSObject))]
public sealed class GetCommandCommand : PSCmdlet
{
#region Definitions of cmdlet parameters
/// <summary>
/// Gets or sets the path(s) or name(s) of the commands to retrieve.
/// </summary>
[Parameter(
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "AllCommandSet")]
[ValidateNotNullOrEmpty]
public string[] Name
{
get
{
return _names;
}
set
{
_nameContainsWildcard = false;
_names = value;
if (value != null)
{
foreach (string commandName in value)
{
if (WildcardPattern.ContainsWildcardCharacters(commandName))
{
_nameContainsWildcard = true;
break;
}
}
}
}
}
private string[] _names;
private bool _nameContainsWildcard;
/// <summary>
/// Gets or sets the verb parameter to the cmdlet.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "CmdletSet")]
public string[] Verb
{
get
{
return _verbs;
}
set
{
if (value == null)
{
value = Utils.EmptyArray<string>();
}
_verbs = value;
_verbPatterns = null;
}
}
private string[] _verbs = Utils.EmptyArray<string>();
/// <summary>
/// Gets or sets the noun parameter to the cmdlet.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "CmdletSet")]
[ArgumentCompleter(typeof(NounArgumentCompleter))]
public string[] Noun
{
get
{
return _nouns;
}
set
{
if (value == null)
{
value = Utils.EmptyArray<string>();
}
_nouns = value;
_nounPatterns = null;
}
}
private string[] _nouns = Utils.EmptyArray<string>();
/// <summary>
/// Gets or sets the PSSnapin/Module parameter to the cmdlet.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
[Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("PSSnapin")]
public string[] Module
{
get
{
return _modules;
}
set
{
if (value == null)
{
value = Utils.EmptyArray<string>();
}
_modules = value;
_modulePatterns = null;
_isModuleSpecified = true;
}
}
private string[] _modules = Utils.EmptyArray<string>();
private bool _isModuleSpecified = false;
/// <summary>
/// Gets or sets the FullyQualifiedModule parameter to the cmdlet.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
[Parameter(ValueFromPipelineByPropertyName = true)]
public ModuleSpecification[] FullyQualifiedModule
{
get
{
return _moduleSpecifications;
}
set
{
if (value != null)
{
_moduleSpecifications = value;
}
_isFullyQualifiedModuleSpecified = true;
}
}
private ModuleSpecification[] _moduleSpecifications = Utils.EmptyArray<ModuleSpecification>();
private bool _isFullyQualifiedModuleSpecified = false;
/// <summary>
/// Gets or sets the type of the command to get.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "AllCommandSet")]
[Alias("Type")]
public CommandTypes CommandType
{
get
{
return _commandType;
}
set
{
_commandType = value;
_isCommandTypeSpecified = true;
}
}
private CommandTypes _commandType = CommandTypes.All;
private bool _isCommandTypeSpecified = false;
/// <summary>
/// The parameter representing the total number of commands that will
/// be returned. If negative, all matching commands that are found will
/// be returned.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public int TotalCount { get; set; } = -1;
/// <summary>
/// The parameter that determines if the CommandInfo or the string
/// definition of the command is output.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Syntax
{
get
{
return _usage;
}
set
{
_usage = value;
}
}
private bool _usage;
/// <summary>
/// This parameter causes the output to be packaged into ShowCommandInfo PSObject types
/// needed to display GUI command information.
/// </summary>
[Parameter()]
public SwitchParameter ShowCommandInfo { get; set; }
/// <summary>
/// The parameter that all additional arguments get bound to. These arguments are used
/// when retrieving dynamic parameters from cmdlets that support them.
/// </summary>
[Parameter(Position = 1, ValueFromRemainingArguments = true)]
[AllowNull]
[AllowEmptyCollection]
[Alias("Args")]
public object[] ArgumentList { get; set; }
/// <summary>
/// The parameter that determines if additional matching commands should be returned.
/// (Additional matching functions and aliases are returned from module tables)
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter All
{
get { return _all; }
set { _all = value; }
}
private bool _all;
/// <summary>
/// The parameter that determines if additional matching commands from available modules should be returned.
/// If set to true, only those commands currently in the session are returned.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter ListImported
{
get
{
return _listImported;
}
set
{
_listImported = value;
}
}
private bool _listImported;
/// <summary>
/// The parameter that filters commands returned to only include commands that have a parameter with a name that matches one of the ParameterName's arguments.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ParameterName
{
get { return _parameterNames; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_parameterNames = value;
_parameterNameWildcards = SessionStateUtilities.CreateWildcardsFromStrings(
_parameterNames,
WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
}
}
private Collection<WildcardPattern> _parameterNameWildcards;
private string[] _parameterNames;
private HashSet<string> _matchedParameterNames;
/// <summary>
/// The parameter that filters commands returned to only include commands that have a parameter of a type that matches one of the ParameterType's arguments.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public PSTypeName[] ParameterType
{
get
{
return _parameterTypes;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// if '...CimInstance#Win32_Process' is specified, then exclude '...CimInstance'
List<PSTypeName> filteredParameterTypes = new List<PSTypeName>(value.Length);
for (int i = 0; i < value.Length; i++)
{
PSTypeName ptn = value[i];
if (value.Any(otherPtn => otherPtn.Name.StartsWith(ptn.Name + "#", StringComparison.OrdinalIgnoreCase)))
{
continue;
}
if ((i != 0) && (ptn.Type != null) && (ptn.Type.Equals(typeof(object))))
{
continue;
}
filteredParameterTypes.Add(ptn);
}
_parameterTypes = filteredParameterTypes.ToArray();
}
}
private PSTypeName[] _parameterTypes;
/// <summary>
/// Gets or sets the parameter that enables using fuzzy matching.
/// </summary>
[Parameter(ParameterSetName = "AllCommandSet")]
public SwitchParameter UseFuzzyMatching { get; set; }
private List<CommandScore> _commandScores = new List<CommandScore>();
/// <summary>
/// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion.
/// This means it matches cmdlets where the uppercase characters for the noun match
/// the given characters. i.e., g-sgc would match Get-SomeGreatCmdlet.
/// </summary>
[Experimental("PSUseAbbreviationExpansion", ExperimentAction.Show)]
[Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "AllCommandSet")]
public SwitchParameter UseAbbreviationExpansion { get; set; }
#endregion Definitions of cmdlet parameters
#region Overrides
/// <summary>
/// Begin Processing.
/// </summary>
protected override void BeginProcessing()
{
_timer.Start();
base.BeginProcessing();
if (ShowCommandInfo.IsPresent && Syntax.IsPresent)
{
ThrowTerminatingError(
new ErrorRecord(
new PSArgumentException(DiscoveryExceptions.GetCommandShowCommandInfoParamError),
"GetCommandCannotSpecifySyntaxAndShowCommandInfoTogether",
ErrorCategory.InvalidArgument,
null));
}
}
/// <summary>
/// Method that implements get-command.
/// </summary>
protected override void ProcessRecord()
{
// Module and FullyQualifiedModule should not be specified at the same time.
// Throw out terminating error if this is the case.
if (_isModuleSpecified && _isFullyQualifiedModuleSpecified)
{
string errMsg = string.Format(CultureInfo.InvariantCulture, SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "Module", "FullyQualifiedModule");
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "ModuleAndFullyQualifiedModuleCannotBeSpecifiedTogether", ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(error);
}
// Initialize the module patterns
if (_modulePatterns == null)
{
_modulePatterns = SessionStateUtilities.CreateWildcardsFromStrings(Module, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
}
switch (ParameterSetName)
{
case "CmdletSet":
AccumulateMatchingCmdlets();
break;
case "AllCommandSet":
AccumulateMatchingCommands();
break;
default:
Dbg.Assert(
false,
"Only the valid parameter set names should be used");
break;
}
}
/// <summary>
/// Writes out the accumulated matching commands.
/// </summary>
protected override void EndProcessing()
{
// We do not show the pithy aliases (not of the format Verb-Noun) and applications by default.
// We will show them only if the Name, All and totalCount are not specified.
if ((this.Name == null) && (!_all) && TotalCount == -1 && !UseFuzzyMatching)
{
CommandTypes commandTypesToIgnore = 0;
if (((this.CommandType & CommandTypes.Alias) != CommandTypes.Alias) || (!_isCommandTypeSpecified))
{
commandTypesToIgnore |= CommandTypes.Alias;
}
if (((_commandType & CommandTypes.Application) != CommandTypes.Application) ||
(!_isCommandTypeSpecified))
{
commandTypesToIgnore |= CommandTypes.Application;
}
_accumulatedResults =
_accumulatedResults.Where(
commandInfo =>
(((commandInfo.CommandType & commandTypesToIgnore) == 0) ||
(commandInfo.Name.IndexOf('-') > 0))).ToList();
}
// report not-found errors for ParameterName and ParameterType if needed
if ((_matchedParameterNames != null) && (ParameterName != null))
{
foreach (string requestedParameterName in ParameterName)
{
if (WildcardPattern.ContainsWildcardCharacters(requestedParameterName))
{
continue;
}
if (_matchedParameterNames.Contains(requestedParameterName))
{
continue;
}
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
DiscoveryExceptions.CommandParameterNotFound,
requestedParameterName);
var exception = new ArgumentException(errorMessage, requestedParameterName);
var errorRecord = new ErrorRecord(exception, "CommandParameterNotFound",
ErrorCategory.ObjectNotFound, requestedParameterName);
WriteError(errorRecord);
}
}
// Only sort if they didn't fully specify a name)
if ((_names == null) || (_nameContainsWildcard))
{
// Use the stable sorting to sort the result list
_accumulatedResults = _accumulatedResults.OrderBy(a => a, new CommandInfoComparer()).ToList();
}
OutputResultsHelper(_accumulatedResults);
object pssenderInfo = Context.GetVariableValue(SpecialVariables.PSSenderInfoVarPath);
if ((pssenderInfo != null) && (pssenderInfo is System.Management.Automation.Remoting.PSSenderInfo))
{
// Win8: 593295. Exchange has around 1000 cmdlets. During Import-PSSession,
// Get-Command | select-object ..,HelpURI,... is run. HelpURI is a script property
// which in turn runs Get-Help. Get-Help loads the help content and caches it in the process.
// This caching is using around 190 MB. During V3, we have implemented HelpURI attribute
// and this should solve it. In V2, we dont have this attribute and hence 3rd parties
// run into the same issue. The fix here is to reset help cache whenever get-command is run on
// a remote endpoint. In the worst case, this will affect get-help to run a little longer
// after get-command is run..but that should be OK because get-help is used mainly for
// document reading purposes and not in production.
Context.HelpSystem.ResetHelpProviders();
}
}
#endregion
#region Private Methods
private void OutputResultsHelper(IEnumerable<CommandInfo> results)
{
CommandOrigin origin = this.MyInvocation.CommandOrigin;
if (UseFuzzyMatching)
{
results = _commandScores.OrderBy(x => x.Score).Select(x => x.Command).ToList();
}
int count = 0;
foreach (CommandInfo result in results)
{
count += 1;
// Only write the command if it is visible to the requestor
if (SessionState.IsVisible(origin, result))
{
// If the -syntax flag was specified, write the definition as a string
// otherwise just return the object...
if (Syntax)
{
if (!string.IsNullOrEmpty(result.Syntax))
{
PSObject syntax = PSObject.AsPSObject(result.Syntax);
syntax.IsHelpObject = true;
WriteObject(syntax);
}
}
else
{
if (ShowCommandInfo.IsPresent)
{
// Write output as ShowCommandCommandInfo object.
WriteObject(
ConvertToShowCommandInfo(result));
}
else
{
// Write output as normal command info object.
WriteObject(result);
}
}
}
}
_timer.Stop();
#if LEGACYTELEMETRY
// We want telementry on commands people look for but don't exist - this should give us an idea
// what sort of commands people expect but either don't exist, or maybe should be installed by default.
// The StartsWith is to avoid logging telemetry when suggestion mode checks the
// current directory for scripts/exes in the current directory and '.' is not in the path.
if (count == 0 && Name != null && Name.Length > 0 && !Name[0].StartsWith(".\\", StringComparison.OrdinalIgnoreCase))
{
Telemetry.Internal.TelemetryAPI.ReportGetCommandFailed(Name, _timer.ElapsedMilliseconds);
}
#endif
}
/// <summary>
/// The comparer to sort CommandInfo objects in the result list.
/// </summary>
private class CommandInfoComparer : IComparer<CommandInfo>
{
/// <summary>
/// Compare two CommandInfo objects first by their command types, and if they
/// are with the same command type, then we compare their names.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public int Compare(CommandInfo x, CommandInfo y)
{
if ((int)x.CommandType < (int)y.CommandType)
{
return -1;
}
else if ((int)x.CommandType > (int)y.CommandType)
{
return 1;
}
else
{
return string.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase);
}
}
}
private void AccumulateMatchingCmdlets()
{
_commandType = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Filter | CommandTypes.Alias | CommandTypes.Configuration;
Collection<string> commandNames = new Collection<string>();
commandNames.Add("*");
AccumulateMatchingCommands(commandNames);
}
private bool IsNounVerbMatch(CommandInfo command)
{
bool result = false;
do // false loop
{
if (_verbPatterns == null)
{
_verbPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Verb, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
}
if (_nounPatterns == null)
{
_nounPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Noun, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
}
if (!string.IsNullOrEmpty(command.ModuleName))
{
if (_isFullyQualifiedModuleSpecified)
{
if (!_moduleSpecifications.Any(
moduleSpecification =>
ModuleIntrinsics.IsModuleMatchingModuleSpec(command.Module, moduleSpecification)))
{
break;
}
}
else if (!SessionStateUtilities.MatchesAnyWildcardPattern(command.ModuleName, _modulePatterns, true))
{
break;
}
}
else
{
if (_modulePatterns.Count > 0 || _moduleSpecifications.Any())
{
// Its not a match if we are filtering on a PSSnapin/Module name but the cmdlet doesn't have one.
break;
}
}
// Get the noun and verb to check...
string verb;
string noun;
CmdletInfo cmdlet = command as CmdletInfo;
if (cmdlet != null)
{
verb = cmdlet.Verb;
noun = cmdlet.Noun;
}
else
{
if (!CmdletInfo.SplitCmdletName(command.Name, out verb, out noun))
break;
}
if (!SessionStateUtilities.MatchesAnyWildcardPattern(verb, _verbPatterns, true))
{
break;
}
if (!SessionStateUtilities.MatchesAnyWildcardPattern(noun, _nounPatterns, true))
{
break;
}
result = true;
} while (false);
return result;
}
/// <summary>
/// Writes out the commands for the AllCommandSet using the specified CommandType.
/// </summary>
private void AccumulateMatchingCommands()
{
Collection<string> commandNames =
SessionStateUtilities.ConvertArrayToCollection<string>(this.Name);
if (commandNames.Count == 0)
{
commandNames.Add("*");
}
AccumulateMatchingCommands(commandNames);
}
private void AccumulateMatchingCommands(IEnumerable<string> commandNames)
{
// First set the search options
SearchResolutionOptions options = SearchResolutionOptions.None;
if (All)
{
options = SearchResolutionOptions.SearchAllScopes;
}
if (UseAbbreviationExpansion)
{
options |= SearchResolutionOptions.UseAbbreviationExpansion;
}
if (UseFuzzyMatching)
{
options |= SearchResolutionOptions.FuzzyMatch;
}
if ((this.CommandType & CommandTypes.Alias) != 0)
{
options |= SearchResolutionOptions.ResolveAliasPatterns;
}
if ((this.CommandType & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0)
{
options |= SearchResolutionOptions.ResolveFunctionPatterns;
}
foreach (string commandName in commandNames)
{
try
{
// Determine if the command name is module-qualified, and search
// available modules for the command.
string moduleName;
string plainCommandName = Utils.ParseCommandName(commandName, out moduleName);
bool isModuleQualified = (moduleName != null);
// If they've specified a module name, we can do some smarter filtering.
// Otherwise, we have to filter everything.
if ((this.Module.Length == 1) && (!WildcardPattern.ContainsWildcardCharacters(this.Module[0])))
{
moduleName = this.Module[0];
}
bool isPattern = WildcardPattern.ContainsWildcardCharacters(plainCommandName) || UseAbbreviationExpansion || UseFuzzyMatching;
if (isPattern)
{
options |= SearchResolutionOptions.CommandNameIsPattern;
}
// Try to initially find the command in the available commands
int count = 0;
bool isDuplicate;
bool resultFound = FindCommandForName(options, commandName, isPattern, true, ref count, out isDuplicate);
// If we didn't find the command, or if it had a wildcard, also see if it
// is in an available module
if (!resultFound || isPattern)
{
// If the command name had no wildcards or was module-qualified,
// import the module so that we can return the fully structured data.
// This uses the same code path as module auto-loading.
if ((!isPattern) || (!string.IsNullOrEmpty(moduleName)))
{
string tempCommandName = commandName;
if ((!isModuleQualified) && (!string.IsNullOrEmpty(moduleName)))
{
tempCommandName = moduleName + "\\" + commandName;
}
try
{
CommandDiscovery.LookupCommandInfo(tempCommandName, this.MyInvocation.CommandOrigin, this.Context);
}
catch (CommandNotFoundException)
{
// Ignore, LookupCommandInfo doesn't handle wildcards.
}
resultFound = FindCommandForName(options, commandName, isPattern, false, ref count, out isDuplicate);
}
// Show additional commands from available modules only if ListImported is not specified
else if (!ListImported)
{
if (TotalCount < 0 || count < TotalCount)
{
IEnumerable<CommandInfo> commands;
if (UseFuzzyMatching)
{
foreach (var commandScore in System.Management.Automation.Internal.ModuleUtils.GetFuzzyMatchingCommands(
plainCommandName,
this.Context,
this.MyInvocation.CommandOrigin,
rediscoverImportedModules: true,
moduleVersionRequired: _isFullyQualifiedModuleSpecified))
{
_commandScores.Add(commandScore);
}
commands = _commandScores.Select(x => x.Command).ToList();
}
else
{
commands = System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands(
plainCommandName,
this.Context,
this.MyInvocation.CommandOrigin,
rediscoverImportedModules: true,
moduleVersionRequired: _isFullyQualifiedModuleSpecified,
useAbbreviationExpansion: UseAbbreviationExpansion);
}
foreach (CommandInfo command in commands)
{
// Cannot pass in "command" by ref (foreach iteration variable)
CommandInfo current = command;
if (IsCommandMatch(ref current, out isDuplicate) && (!IsCommandInResult(current)) && IsParameterMatch(current))
{
_accumulatedResults.Add(current);
// Make sure we don't exceed the TotalCount parameter
++count;
if (TotalCount >= 0 && count >= TotalCount)
{
break;
}
}
}
}
}
}
// If we are trying to match a single specific command name (no glob characters)
// then we need to write an error if we didn't find it.
if (!isDuplicate)
{
if (!resultFound && !isPattern)
{
CommandNotFoundException e =
new CommandNotFoundException(
commandName,
null,
"CommandNotFoundException",
DiscoveryExceptions.CommandNotFoundException);
WriteError(
new ErrorRecord(
e.ErrorRecord,
e));
continue;
}
}
}
catch (CommandNotFoundException exception)
{
WriteError(
new ErrorRecord(
exception.ErrorRecord,
exception));
}
}
}
private bool FindCommandForName(SearchResolutionOptions options, string commandName, bool isPattern, bool emitErrors, ref int currentCount, out bool isDuplicate)
{
CommandSearcher searcher =
new CommandSearcher(
commandName,
options,
this.CommandType,
this.Context);
bool resultFound = false;
isDuplicate = false;
do
{
try
{
if (!searcher.MoveNext())
{
break;
}
}
catch (ArgumentException argumentException)
{
if (emitErrors)
{
WriteError(new ErrorRecord(argumentException, "GetCommandInvalidArgument", ErrorCategory.SyntaxError, null));
}
continue;
}
catch (PathTooLongException pathTooLong)
{
if (emitErrors)
{
WriteError(new ErrorRecord(pathTooLong, "GetCommandInvalidArgument", ErrorCategory.SyntaxError, null));
}
continue;
}
catch (FileLoadException fileLoadException)
{
if (emitErrors)
{
WriteError(new ErrorRecord(fileLoadException, "GetCommandFileLoadError", ErrorCategory.ReadError, null));
}
continue;
}
catch (MetadataException metadataException)
{
if (emitErrors)
{
WriteError(new ErrorRecord(metadataException, "GetCommandMetadataError", ErrorCategory.MetadataError, null));
}
continue;
}
catch (FormatException formatException)
{
if (emitErrors)
{
WriteError(new ErrorRecord(formatException, "GetCommandBadFileFormat", ErrorCategory.InvalidData, null));
}
continue;
}
CommandInfo current = ((IEnumerator<CommandInfo>)searcher).Current;
// skip private commands as early as possible
// (i.e. before setting "result found" flag and before trying to use ArgumentList parameter)
// see bugs Windows 7: #520498 and #520470
CommandOrigin origin = this.MyInvocation.CommandOrigin;
if (!SessionState.IsVisible(origin, current))
{
continue;
}
bool tempResultFound = IsCommandMatch(ref current, out isDuplicate);
if (tempResultFound && (!IsCommandInResult(current)))
{
resultFound = true;
if (IsParameterMatch(current))
{
// Make sure we don't exceed the TotalCount parameter
++currentCount;
if (TotalCount >= 0 && currentCount > TotalCount)
{
break;
}
if (UseFuzzyMatching)
{
int score = FuzzyMatcher.GetDamerauLevenshteinDistance(current.Name, commandName);
_commandScores.Add(new CommandScore(current, score));
}
_accumulatedResults.Add(current);
if (ArgumentList != null)
{
// Don't iterate the enumerator any more. If -arguments was specified, then we stop at the first match
break;
}
}
// Only for this case, the loop should exit
// Get-Command Foo
if (isPattern || All || TotalCount != -1 || _isCommandTypeSpecified || _isModuleSpecified || _isFullyQualifiedModuleSpecified)
{
continue;
}
else
{
break;
}
}
} while (true);
if (All)
{
// Get additional matching commands from module tables.
foreach (CommandInfo command in GetMatchingCommandsFromModules(commandName))
{
CommandInfo c = command;
bool tempResultFound = IsCommandMatch(ref c, out isDuplicate);
if (tempResultFound)
{
resultFound = true;
if (!IsCommandInResult(command) && IsParameterMatch(c))
{
++currentCount;
if (TotalCount >= 0 && currentCount > TotalCount)
{
break;
}
_accumulatedResults.Add(c);
}
// Make sure we don't exceed the TotalCount parameter
}
}
}
return resultFound;
}
/// <summary>
/// Determines if the specific command information has already been
/// written out based on the path or definition.
/// </summary>
/// <param name="info">
/// The command information to check for duplication.
/// </param>
/// <returns>
/// true if the command has already been written out.
/// </returns>
private bool IsDuplicate(CommandInfo info)
{
bool result = false;
string key = null;
do // false loop
{
ApplicationInfo appInfo = info as ApplicationInfo;
if (appInfo != null)
{
key = appInfo.Path;
break;
}
CmdletInfo cmdletInfo = info as CmdletInfo;
if (cmdletInfo != null)
{
key = cmdletInfo.FullName;
break;
}
ScriptInfo scriptInfo = info as ScriptInfo;
if (scriptInfo != null)
{
key = scriptInfo.Definition;
break;
}
ExternalScriptInfo externalScriptInfo = info as ExternalScriptInfo;
if (externalScriptInfo != null)
{
key = externalScriptInfo.Path;
break;
}
} while (false);
if (key != null)
{
if (_commandsWritten.ContainsKey(key))
{
result = true;
}
else
{
_commandsWritten.Add(key, info);
}
}
return result;
}
private bool IsParameterMatch(CommandInfo commandInfo)
{
if ((this.ParameterName == null) && (this.ParameterType == null))
{
return true;
}
if (_matchedParameterNames == null)
{
_matchedParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
IEnumerable<ParameterMetadata> commandParameters = null;
try
{
IDictionary<string, ParameterMetadata> tmp = commandInfo.Parameters;
if (tmp != null)
{
commandParameters = tmp.Values;
}
}
catch (Exception)
{
// ignore all exceptions when getting parameter metadata (i.e. parse exceptions, dangling alias exceptions)
// and proceed as if there was no parameter metadata
}
if (commandParameters == null)
{
// do not match commands which have not been imported yet / for which we don't have parameter metadata yet
return false;
}
else
{
bool foundMatchingParameter = false;
foreach (ParameterMetadata parameterMetadata in commandParameters)
{
if (IsParameterMatch(parameterMetadata))
{
foundMatchingParameter = true;
// not breaking out of the loop early, to ensure that _matchedParameterNames gets populated for all command parameters
}
}
return foundMatchingParameter;
}
}
private bool IsParameterMatch(ParameterMetadata parameterMetadata)
{
//
// ParameterName matching
//
bool nameIsDirectlyMatching = SessionStateUtilities.MatchesAnyWildcardPattern(parameterMetadata.Name, _parameterNameWildcards, true);
bool oneOfAliasesIsMatching = false;
foreach (string alias in parameterMetadata.Aliases ?? Enumerable.Empty<string>())
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(alias, _parameterNameWildcards, true))
{
_matchedParameterNames.Add(alias);
oneOfAliasesIsMatching = true;
// don't want to break out of the loop early (need to fully populate _matchedParameterNames hashset)
}
}
bool nameIsMatching = nameIsDirectlyMatching || oneOfAliasesIsMatching;
if (nameIsMatching)
{
_matchedParameterNames.Add(parameterMetadata.Name);
}
//
// ParameterType matching
//
bool typeIsMatching;
if ((_parameterTypes == null) || (_parameterTypes.Length == 0))
{
typeIsMatching = true;
}
else
{
typeIsMatching = false;
if (_parameterTypes != null &&
_parameterTypes.Length > 0)
{
typeIsMatching |= _parameterTypes.Any(parameterMetadata.IsMatchingType);
}
}
return nameIsMatching && typeIsMatching;
}
private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate)
{
bool isCommandMatch = false;
isDuplicate = false;
// Be sure we haven't already found this command before
if (!IsDuplicate(current))
{
if ((current.CommandType & this.CommandType) != 0)
{
isCommandMatch = true;
}
// If the command in question is a cmdlet or (a function/filter/configuration/alias and we are filtering on nouns or verbs),
// then do the verb/noun check
if (current.CommandType == CommandTypes.Cmdlet ||
((_verbs.Length > 0 || _nouns.Length > 0) &&
(current.CommandType == CommandTypes.Function ||
current.CommandType == CommandTypes.Filter ||
current.CommandType == CommandTypes.Configuration ||
current.CommandType == CommandTypes.Alias)))
{
if (!IsNounVerbMatch(current))
{
isCommandMatch = false;
}
}
else
{
if (_isFullyQualifiedModuleSpecified)
{
bool foundModuleMatch = false;
foreach (var moduleSpecification in _moduleSpecifications)
{
if (ModuleIntrinsics.IsModuleMatchingModuleSpec(current.Module, moduleSpecification))
{
foundModuleMatch = true;
break;
}
}
if (!foundModuleMatch)
{
isCommandMatch = false;
}
}
else if (_modulePatterns != null && _modulePatterns.Count > 0)
{
if (!SessionStateUtilities.MatchesAnyWildcardPattern(current.ModuleName, _modulePatterns, true))
{
isCommandMatch = false;
}
}
}
if (isCommandMatch)
{
if (ArgumentList != null)
{
AliasInfo ai = current as AliasInfo;
if (ai != null)
{
// If the matching command was an alias, then use the resolved command
// instead of the alias...
current = ai.ResolvedCommand;
if (current == null)
{
return false;
}
}
else if (!(current is CmdletInfo || current is IScriptCommandInfo))
{
// If current is not a cmdlet or script, we need to throw a terminating error.
ThrowTerminatingError(
new ErrorRecord(
PSTraceSource.NewArgumentException(
"ArgumentList",
DiscoveryExceptions.CommandArgsOnlyForSingleCmdlet),
"CommandArgsOnlyForSingleCmdlet",
ErrorCategory.InvalidArgument,
current));
}
}
// If the command implements dynamic parameters
// then we must make a copy of the CommandInfo which merges the
// dynamic parameter metadata with the statically defined parameter
// metadata
bool needCopy = false;
try
{
// We can ignore some errors that occur when checking if
// the command implements dynamic parameters.
needCopy = current.ImplementsDynamicParameters;
}
catch (PSSecurityException)
{
// Ignore execution policies in get-command, those will get
// raised when trying to run the real command
}
catch (RuntimeException)
{
// Ignore parse/runtime exceptions. Again, they will get
// raised again if the script is actually run.
}
if (needCopy)
{
try
{
CommandInfo newCurrent = current.CreateGetCommandCopy(ArgumentList);
if (ArgumentList != null)
{
// We need to prepopulate the parameter metadata in the CmdletInfo to
// ensure there are no errors. Getting the ParameterSets property
// triggers the parameter metadata to be generated
ReadOnlyCollection<CommandParameterSetInfo> parameterSets =
newCurrent.ParameterSets;
}
current = newCurrent;
}
catch (MetadataException metadataException)
{
// A metadata exception can be thrown if the dynamic parameters duplicates a parameter
// of the cmdlet.
WriteError(new ErrorRecord(metadataException, "GetCommandMetadataError",
ErrorCategory.MetadataError, current));
}
catch (ParameterBindingException parameterBindingException)
{
// if the exception is thrown when retrieving dynamic parameters, ignore it and
// the static parameter info will be used.
if (!parameterBindingException.ErrorRecord.FullyQualifiedErrorId.StartsWith(
"GetDynamicParametersException", StringComparison.Ordinal))
{
throw;
}
}
}
}
}
else
{
isDuplicate = true;
}
return isCommandMatch;
}
/// <summary>
/// Gets matching commands from the module tables.
/// </summary>
/// <param name="commandName">
/// The commandname to look for
/// </param>
/// <returns>
/// IEnumerable of CommandInfo objects
/// </returns>
private IEnumerable<CommandInfo> GetMatchingCommandsFromModules(string commandName)
{
WildcardPattern matcher = WildcardPattern.Get(
commandName,
WildcardOptions.IgnoreCase);
// Use ModuleTableKeys list in reverse order
for (int i = Context.EngineSessionState.ModuleTableKeys.Count - 1; i >= 0; i--)
{
PSModuleInfo module = null;
if (Context.EngineSessionState.ModuleTable.TryGetValue(Context.EngineSessionState.ModuleTableKeys[i], out module) == false)
{
Dbg.Assert(false, "ModuleTableKeys should be in sync with ModuleTable");
}
else
{
bool isModuleMatch = false;
if (!_isFullyQualifiedModuleSpecified)
{
isModuleMatch = SessionStateUtilities.MatchesAnyWildcardPattern(module.Name, _modulePatterns, true);
}
else if (_moduleSpecifications.Any(moduleSpecification => ModuleIntrinsics.IsModuleMatchingModuleSpec(module, moduleSpecification)))
{
isModuleMatch = true;
}
if (isModuleMatch)
{
if (module.SessionState != null)
{
// Look in function table
if ((this.CommandType & (CommandTypes.Function | CommandTypes.Filter | CommandTypes.Configuration)) != 0)
{
foreach (DictionaryEntry function in module.SessionState.Internal.GetFunctionTable())
{
FunctionInfo func = (FunctionInfo)function.Value;
if (matcher.IsMatch((string)function.Key) && func.IsImported)
{
// make sure function doesn't come from the current module's nested module
if (func.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
yield return (CommandInfo)function.Value;
}
}
}
// Look in alias table
if ((this.CommandType & CommandTypes.Alias) != 0)
{
foreach (var alias in module.SessionState.Internal.GetAliasTable())
{
if (matcher.IsMatch(alias.Key) && alias.Value.IsImported)
{
// make sure alias doesn't come from the current module's nested module
if (alias.Value.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase))
yield return alias.Value;
}
}
}
}
}
}
}
}
/// <summary>
/// Determines if the specific command information has already been
/// added to the result from CommandSearcher.
/// </summary>
/// <param name="command">
/// The command information to check for duplication.
/// </param>
/// <returns>
/// true if the command is present in the result.
/// </returns>
private bool IsCommandInResult(CommandInfo command)
{
bool isPresent = false;
bool commandHasModule = command.Module != null;
foreach (CommandInfo commandInfo in _accumulatedResults)
{
if ((command.CommandType == commandInfo.CommandType &&
(string.Compare(command.Name, commandInfo.Name, StringComparison.OrdinalIgnoreCase) == 0 ||
// If the command has been imported with a prefix, then just checking the names for duplication will not be enough.
// Hence, an additional check is done with the prefix information
string.Compare(ModuleCmdletBase.RemovePrefixFromCommandName(commandInfo.Name, commandInfo.Prefix), command.Name, StringComparison.OrdinalIgnoreCase) == 0)
) && commandInfo.Module != null && commandHasModule &&
( // We do reference equal comparison if both command are imported. If either one is not imported, we compare the module path
(commandInfo.IsImported && command.IsImported && commandInfo.Module.Equals(command.Module)) ||
((!commandInfo.IsImported || !command.IsImported) && commandInfo.Module.Path.Equals(command.Module.Path, StringComparison.OrdinalIgnoreCase))
))
{
isPresent = true;
break;
}
}
return isPresent;
}
#endregion
#region Members
private Dictionary<string, CommandInfo> _commandsWritten =
new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase);
private List<CommandInfo> _accumulatedResults = new List<CommandInfo>();
// These members are the collection of wildcard patterns for the "CmdletSet"
private Collection<WildcardPattern> _verbPatterns;
private Collection<WildcardPattern> _nounPatterns;
private Collection<WildcardPattern> _modulePatterns;
private Stopwatch _timer = new Stopwatch();
#endregion
#region ShowCommandInfo support
// Converts to PSObject containing ShowCommand information.
private static PSObject ConvertToShowCommandInfo(CommandInfo cmdInfo)
{
PSObject showCommandInfo = new PSObject();
showCommandInfo.Properties.Add(new PSNoteProperty("Name", cmdInfo.Name));
showCommandInfo.Properties.Add(new PSNoteProperty("ModuleName", cmdInfo.ModuleName));
showCommandInfo.Properties.Add(new PSNoteProperty("Module", GetModuleInfo(cmdInfo)));
showCommandInfo.Properties.Add(new PSNoteProperty("CommandType", cmdInfo.CommandType));
showCommandInfo.Properties.Add(new PSNoteProperty("Definition", cmdInfo.Definition));
showCommandInfo.Properties.Add(new PSNoteProperty("ParameterSets", GetParameterSets(cmdInfo)));
return showCommandInfo;
}
private static PSObject GetModuleInfo(CommandInfo cmdInfo)
{
PSObject moduleInfo = new PSObject();
string moduleName = (cmdInfo.Module != null) ? cmdInfo.Module.Name : string.Empty;
moduleInfo.Properties.Add(new PSNoteProperty("Name", moduleName));
return moduleInfo;
}
private static PSObject[] GetParameterSets(CommandInfo cmdInfo)
{
ReadOnlyCollection<CommandParameterSetInfo> parameterSets = null;
try
{
if (cmdInfo.ParameterSets != null)
{
parameterSets = cmdInfo.ParameterSets;
}
}
catch (InvalidOperationException) { }
catch (PSNotSupportedException) { }
catch (PSNotImplementedException) { }
if (parameterSets == null)
{
return Utils.EmptyArray<PSObject>();
}
List<PSObject> returnParameterSets = new List<PSObject>(cmdInfo.ParameterSets.Count);
foreach (CommandParameterSetInfo parameterSetInfo in parameterSets)
{
PSObject parameterSetObj = new PSObject();
parameterSetObj.Properties.Add(new PSNoteProperty("Name", parameterSetInfo.Name));
parameterSetObj.Properties.Add(new PSNoteProperty("IsDefault", parameterSetInfo.IsDefault));
parameterSetObj.Properties.Add(new PSNoteProperty("Parameters", GetParameterInfo(parameterSetInfo.Parameters)));
returnParameterSets.Add(parameterSetObj);
}
return returnParameterSets.ToArray();
}
private static PSObject[] GetParameterInfo(ReadOnlyCollection<CommandParameterInfo> parameters)
{
List<PSObject> parameterObjs = new List<PSObject>(parameters.Count);
foreach (CommandParameterInfo parameter in parameters)
{
PSObject parameterObj = new PSObject();
parameterObj.Properties.Add(new PSNoteProperty("Name", parameter.Name));
parameterObj.Properties.Add(new PSNoteProperty("IsMandatory", parameter.IsMandatory));
parameterObj.Properties.Add(new PSNoteProperty("ValueFromPipeline", parameter.ValueFromPipeline));
parameterObj.Properties.Add(new PSNoteProperty("Position", parameter.Position));
parameterObj.Properties.Add(new PSNoteProperty("ParameterType", GetParameterType(parameter.ParameterType)));
bool hasParameterSet = false;
IList<string> validValues = new List<string>();
var validateSetAttribute = parameter.Attributes.Where(x => (x is ValidateSetAttribute)).Cast<ValidateSetAttribute>().LastOrDefault();
if (validateSetAttribute != null)
{
hasParameterSet = true;
validValues = validateSetAttribute.ValidValues;
}
parameterObj.Properties.Add(new PSNoteProperty("HasParameterSet", hasParameterSet));
parameterObj.Properties.Add(new PSNoteProperty("ValidParamSetValues", validValues));
parameterObjs.Add(parameterObj);
}
return parameterObjs.ToArray();
}
private static PSObject GetParameterType(Type parameterType)
{
PSObject returnParameterType = new PSObject();
bool isEnum = parameterType.IsEnum;
bool isArray = parameterType.IsArray;
returnParameterType.Properties.Add(new PSNoteProperty("FullName", parameterType.FullName));
returnParameterType.Properties.Add(new PSNoteProperty("IsEnum", isEnum));
returnParameterType.Properties.Add(new PSNoteProperty("IsArray", isArray));
ArrayList enumValues = (isEnum) ?
new ArrayList(Enum.GetValues(parameterType)) : new ArrayList();
returnParameterType.Properties.Add(new PSNoteProperty("EnumValues", enumValues));
bool hasFlagAttribute = (isArray) ?
((parameterType.GetCustomAttributes(typeof(FlagsAttribute), true)).Count() > 0) : false;
returnParameterType.Properties.Add(new PSNoteProperty("HasFlagAttribute", hasFlagAttribute));
// Recurse into array elements.
object elementType = (isArray) ?
GetParameterType(parameterType.GetElementType()) : null;
returnParameterType.Properties.Add(new PSNoteProperty("ElementType", elementType));
bool implementsDictionary = (!isEnum && !isArray && (parameterType is IDictionary));
returnParameterType.Properties.Add(new PSNoteProperty("ImplementsDictionary", implementsDictionary));
return returnParameterType;
}
#endregion
}
/// <summary>
/// </summary>
public class NounArgumentCompleter : IArgumentCompleter
{
/// <summary>
/// </summary>
public IEnumerable<CompletionResult> CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters)
{
if (fakeBoundParameters == null)
{
throw PSTraceSource.NewArgumentNullException("fakeBoundParameters");
}
var commandInfo = new CmdletInfo("Get-Command", typeof(GetCommandCommand));
var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)
.AddCommand(commandInfo)
.AddParameter("Noun", wordToComplete + "*");
if (fakeBoundParameters.Contains("Module"))
{
ps.AddParameter("Module", fakeBoundParameters["Module"]);
}
HashSet<string> nouns = new HashSet<string>();
var results = ps.Invoke<CommandInfo>();
foreach (var result in results)
{
var dash = result.Name.IndexOf('-');
if (dash != -1)
{
nouns.Add(result.Name.Substring(dash + 1));
}
}
return nouns.OrderBy(noun => noun).Select(noun => new CompletionResult(noun, noun, CompletionResultType.Text, noun));
}
}
}
| |
using System;
using System.Text;
using Xunit;
using Medo.Security.Checksum;
namespace Tests.Medo.Security.Checksum {
public class Crc16Tests {
[Fact(DisplayName = "Crc16: Default")]
public void Default() {
string expected = "0x178C";
var crc = new Crc16();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: ARC")]
public void Arc() {
string expected = "0x178C";
var crc = Crc16.GetArc();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: ARC (2)")]
public void Arc_2() {
var crc = Crc16.GetArc();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xBB3D, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: ARC / LHA (A)")]
public void Lha_A() {
var crc = Crc16.GetLha();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xBB3D, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: ARC / IEEE-802.3 (A)")]
public void Ieee8023_A() {
var crc = Crc16.GetIeee8023();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xBB3D, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: CDMA2000")]
public void Cdma2000() {
string expected = "0x4A2D";
var crc = Crc16.GetCdma2000();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: CDMA2000 (2)")]
public void Cdma2000_2() {
var crc = Crc16.GetCdma2000();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x4C06, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: CMS")]
public void Cms() {
string expected = "0x2A12";
var crc = Crc16.GetCms();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: CMS (2)")]
public void Cms_2() {
var crc = Crc16.GetCms();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xAEE7, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: DDS-110")]
public void Dds110() {
string expected = "0x242A";
var crc = Crc16.GetDds110();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: DDS-110 (2)")]
public void Dds110_2() {
var crc = Crc16.GetDds110();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x9ECF, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: DECT-R")]
public void DectR() {
string expected = "0x55C3";
var crc = Crc16.GetDectR();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: DECT-R (2)")]
public void DectR_2() {
var crc = Crc16.GetDectR();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x007E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: DECT-X")]
public void DectX() {
string expected = "0x55C3";
var crc = Crc16.GetDectR();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: DECT-X (2)")]
public void DectX_2() {
var crc = Crc16.GetDectX();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x007F, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: DNP")]
public void Dnp() {
string expected = "0xE7BC";
var crc = Crc16.GetDnp();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: DNP (2)")]
public void Dnp_2() {
var crc = Crc16.GetDnp();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xEA82, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: EN-13757")]
public void En13757() {
string expected = "0x7458";
var crc = Crc16.GetEn13757();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: EN-13757 (2)")]
public void En13757_2() {
var crc = Crc16.GetEn13757();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xC2B7, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: GENIBUS")]
public void Genibus() {
string expected = "0x20D1";
var crc = Crc16.GetGenibus();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: GENIBUS (2)")]
public void Genibus_2() {
var crc = Crc16.GetGenibus();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xD64E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: GENIBUS / DARC (A)")]
public void Darc_A() {
var crc = Crc16.GetDarc();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xD64E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: GENIBUS / EPC (A)")]
public void Epc_A() {
var crc = Crc16.GetEpc();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xD64E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: GENIBUS / EPC-C1G2 (A)")]
public void EpcC1G2_A() {
var crc = Crc16.GetEpcC1G2();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xD64E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: GSM")]
public void Gsm() {
string expected = "0xA1E4";
var crc = Crc16.GetGsm();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: GSM (2)")]
public void Gsm_2() {
var crc = Crc16.GetGsm();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xCE3C, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-3740")]
public void Ibm3740() {
string expected = "0xDF2E";
var crc = Crc16.GetIbm3740();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: IBM-3740 (2)")]
public void Ibm3740_2() {
var crc = Crc16.GetIbm3740();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x29B1, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-3740 / AUTOSAR (A)")]
public void Autosar_A() {
var crc = Crc16.GetAutosar();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x29B1, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-3740 / CCITT-FALSE (A)")]
public void CcittFalse_A() {
var crc = Crc16.GetCcittFalse();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x29B1, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-SDLC")]
public void IbmSdlc() {
string expected = "0xCB47";
var crc = Crc16.GetIbmSdlc();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: IBM-SDLC (2)")]
public void IbmSdlc_2() {
var crc = Crc16.GetIbmSdlc();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x906E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-SDLC / ISO-HDLC (2)")]
public void IsoHdld_A() {
var crc = Crc16.GetIsoHdld();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x906E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-SDLC / ISO-IEC-14443-3-B (2)")]
public void IsoIec144433B_A() {
var crc = Crc16.GetIsoIec144433B();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x906E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: IBM-SDLC / X-25 (2)")]
public void X25_A() {
var crc = Crc16.GetX25();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x906E, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: I-CODE")]
public void ICode() {
string expected = "0xCB47";
var crc = Crc16.GetIbmSdlc();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: I-CODE (2)")]
public void ICode_2() {
var crc = Crc16.GetICode();
crc.ComputeHash(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x64, 0x32 });
Assert.Equal(0x1D0F, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: KERMIT")]
public void Kermit() {
string expected = "0x9839";
var crc = Crc16.GetKermit();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: KERMIT (2)")]
public void Kermit_2() {
var crc = Crc16.GetKermit();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x2189, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: KERMIT / CCITT (A)")]
public void Ccitt_A() {
var crc = Crc16.GetCcitt();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x2189, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: KERMIT / CCITT-TRUE (A)")]
public void CcittTrue_A() {
var crc = Crc16.GetCcittTrue();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x2189, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: KERMIT / V-41-LSB (A)")]
public void V41Lsb_A() {
var crc = Crc16.GetV41Lsb();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x2189, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: LJ1200")]
public void Lj1200() {
string expected = "0x1507";
var crc = Crc16.GetLj1200();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: LJ1200 (2)")]
public void Lj1200_2() {
var crc = Crc16.GetLj1200();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xBDF4, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: MAXIM-DOW")]
public void MaximDow() {
string expected = "0xE873";
var crc = Crc16.GetMaximDow();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: MAXIM-DOW (2)")]
public void MaximDow_2() {
var crc = Crc16.GetMaximDow();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x44C2, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: MAXIM-DOW / MAXIM (A)")]
public void Maxim_A() {
var crc = Crc16.GetMaxim();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x44C2, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: MCRF4XX")]
public void Mcrf4xx() {
string expected = "0x34B8";
var crc = Crc16.GetMcrf4xx();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: MCRF4XX (2)")]
public void Mcrf4xx_2() {
var crc = Crc16.GetMcrf4xx();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x6F91, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: MODBUS")]
public void Modbus() {
string expected = "0x07CC";
var crc = Crc16.GetModbus();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: MODBUS (2)")]
public void Modbus_2() {
var crc = Crc16.GetModbus();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x4B37, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: NRSC-5")]
public void Nrsc5() {
string expected = "0x8793";
var crc = Crc16.GetNrsc5();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: NRSC-5 (2)")]
public void Nrsc5_2() {
var crc = Crc16.GetNrsc5();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA066, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: OPENSAFETY-A")]
public void OpenSafetyA() {
string expected = "0xCE51";
var crc = Crc16.GetOpenSafetyA();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: OPENSAFETY-A (2)")]
public void OpenSafetyA_2() {
var crc = Crc16.GetOpenSafetyA();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x5D38, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: OPENSAFETY-B")]
public void OpenSafetyB() {
string expected = "0xDE12";
var crc = Crc16.GetOpenSafetyB();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: OPENSAFETY-B (2)")]
public void OpenSafetyB_2() {
var crc = Crc16.GetOpenSafetyB();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x20FE, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: PROFIBUS")]
public void Profibus() {
string expected = "0xD338";
var crc = Crc16.GetProfibus();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: PROFIBUS (2)")]
public void Profibus_2() {
var crc = Crc16.GetProfibus();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA819, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: PROFIBUS / IEC-61158-2 (A)")]
public void Iec611582_A() {
var crc = Crc16.GetIec611582();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA819, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: RIELLO")]
public void Riello() {
string expected = "0x2231";
var crc = Crc16.GetRiello();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: RIELLO (2)")]
public void Riello_2() {
var crc = Crc16.GetRiello();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x63D0, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: SPI-FUJITSU")]
public void SpiFujitsu() {
string expected = "0x1044";
var crc = Crc16.GetSpiFujitsu();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: SPI-FUJITSU (2)")]
public void SpiFujitsu_2() {
var crc = Crc16.GetSpiFujitsu();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xE5CC, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: SPI-FUJITSU / AUG-CCITT (A)")]
public void SpiAugCcitt_A() {
var crc = Crc16.GetSpiFujitsu();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xE5CC, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: T10-DIF")]
public void T10Dif() {
string expected = "0x4C2F";
var crc = Crc16.GetT10Dif();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: T10-DIF (2)")]
public void T10Dif_2() {
var crc = Crc16.GetT10Dif();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xD0DB, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: TELEDISK")]
public void Teledisk() {
string expected = "0x4CBD";
var crc = Crc16.GetTeledisk();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: TELEDISK (2)")]
public void Teledisk_2() {
var crc = Crc16.GetTeledisk();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x0FB3, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: TMS37157")]
public void Tms37157() {
string expected = "0x7DB6";
var crc = Crc16.GetTms37157();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: TMS37157 (2)")]
public void Tms37157_2() {
var crc = Crc16.GetTms37157();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x26B1, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: UMTS")]
public void Umts() {
string expected = "0x281A";
var crc = Crc16.GetUmts();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: UMTS (2)")]
public void Umts_2() {
var crc = Crc16.GetUmts();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xFEE8, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: UMTS / BUYPASS (A)")]
public void Buypass_2() {
var crc = Crc16.GetBuypass();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xFEE8, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: UMTS / VERIFONE (A)")]
public void Verifone_2() {
var crc = Crc16.GetVerifone();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xFEE8, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: USB")]
public void Usb() {
string expected = "0xF833";
var crc = Crc16.GetUsb();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: USB (2)")]
public void Usb_2() {
var crc = Crc16.GetUsb();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xB4C8, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: XMODEM")]
public void XModem() {
string expected = "0x5E1B";
var crc = Crc16.GetXModem();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsInt16:X4}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc16: XMODEM (2)")]
public void XModem_2() {
var crc = Crc16.GetXModem();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x31C3, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: XMODEM / ACORN (A)")]
public void Acorn_A() {
var crc = Crc16.GetAcorn();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x31C3, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: XMODEM / LTE (A)")]
public void Lte_A() {
var crc = Crc16.GetLte();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x31C3, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: XMODEM / V-41-MSB (A)")]
public void V41Msb_A() {
var crc = Crc16.GetV41Msb();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x31C3, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: XMODEM / ZMODEM (A)")]
public void ZModem_A() {
var crc = Crc16.GetZModem();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x31C3, (ushort)crc.HashAsInt16);
}
[Fact(DisplayName = "Crc16: Reuse same instance")]
public void Reuse() {
var checksum = Crc16.GetIeee8023();
checksum.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal("178C", checksum.HashAsInt16.ToString("X4"));
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using System.IO;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
//using OpenSim.Framework.Console;
namespace OpenSim.Framework
{
[Serializable]
public class RegionLightShareData : ICloneable
{
public bool valid = false;
public UUID regionID = UUID.Zero;
public Vector3 waterColor = new Vector3(4.0f,38.0f,64.0f);
public float waterFogDensityExponent = 4.0f;
public float underwaterFogModifier = 0.25f;
public Vector3 reflectionWaveletScale = new Vector3(2.0f,2.0f,2.0f);
public float fresnelScale = 0.40f;
public float fresnelOffset = 0.50f;
public float refractScaleAbove = 0.03f;
public float refractScaleBelow = 0.20f;
public float blurMultiplier = 0.040f;
public Vector2 bigWaveDirection = new Vector2(1.05f,-0.42f);
public Vector2 littleWaveDirection = new Vector2(1.11f,-1.16f);
public UUID normalMapTexture = new UUID("822ded49-9a6c-f61c-cb89-6df54f42cdf4");
public Vector4 horizon = new Vector4(0.25f, 0.25f, 0.32f, 0.32f);
public float hazeHorizon = 0.19f;
public Vector4 blueDensity = new Vector4(0.12f, 0.22f, 0.38f, 0.38f);
public float hazeDensity = 0.70f;
public float densityMultiplier = 0.18f;
public float distanceMultiplier = 0.8f;
public UInt16 maxAltitude = 1605;
public Vector4 sunMoonColor = new Vector4(0.24f, 0.26f, 0.30f, 0.30f);
public float sunMoonPosition = 0.317f;
public Vector4 ambient = new Vector4(0.35f,0.35f,0.35f,0.35f);
public float eastAngle = 0.0f;
public float sunGlowFocus = 0.10f;
public float sunGlowSize = 1.75f;
public float sceneGamma = 1.0f;
public float starBrightness = 0.0f;
public Vector4 cloudColor = new Vector4(0.41f, 0.41f, 0.41f, 0.41f);
public Vector3 cloudXYDensity = new Vector3(1.00f, 0.53f, 1.00f);
public float cloudCoverage = 0.27f;
public float cloudScale = 0.42f;
public Vector3 cloudDetailXYDensity = new Vector3(1.00f, 0.53f, 0.12f);
public float cloudScrollX = 0.20f;
public bool cloudScrollXLock = false;
public float cloudScrollY = 0.01f;
public bool cloudScrollYLock = false;
public bool drawClassicClouds = true;
public delegate void SaveDelegate(RegionLightShareData wl);
public event SaveDelegate OnSave;
public void Save()
{
if (OnSave != null)
OnSave(this);
}
public object Clone()
{
return this.MemberwiseClone(); // call clone method
}
}
public class RegionInfo
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly string LogHeader = "[REGION INFO]";
public bool commFailTF = false;
public ConfigurationMember configMember;
public string DataStore = String.Empty;
public string RegionFile = String.Empty;
public bool isSandbox = false;
public bool Persistent = true;
private EstateSettings m_estateSettings;
private RegionSettings m_regionSettings;
// private IConfigSource m_configSource = null;
public UUID originRegionID = UUID.Zero;
public string proxyUrl = "";
public int ProxyOffset = 0;
public string regionSecret = UUID.Random().ToString();
public string osSecret;
public UUID lastMapUUID = UUID.Zero;
public string lastMapRefresh = "0";
private float m_nonphysPrimMin = 0;
private int m_nonphysPrimMax = 0;
private float m_physPrimMin = 0;
private int m_physPrimMax = 0;
private bool m_clampPrimSize = false;
private int m_objectCapacity = 0;
private int m_maxPrimsPerUser = -1;
private int m_linksetCapacity = 0;
private string m_regionType = String.Empty;
private RegionLightShareData m_windlight = new RegionLightShareData();
protected uint m_httpPort;
protected string m_serverURI;
protected string m_regionName = String.Empty;
protected bool Allow_Alternate_Ports;
public bool m_allow_alternate_ports;
protected string m_externalHostName;
protected IPEndPoint m_internalEndPoint;
protected uint m_remotingPort;
public UUID RegionID = UUID.Zero;
public string RemotingAddress;
public UUID ScopeID = UUID.Zero;
private UUID m_maptileStaticUUID = UUID.Zero;
public uint WorldLocX = 0;
public uint WorldLocY = 0;
public uint WorldLocZ = 0;
/// <summary>
/// X dimension of the region.
/// </summary>
/// <remarks>
/// If this is a varregion then the default size set here will be replaced when we load the region config.
/// </remarks>
public uint RegionSizeX = Constants.RegionSize;
/// <summary>
/// X dimension of the region.
/// </summary>
/// <remarks>
/// If this is a varregion then the default size set here will be replaced when we load the region config.
/// </remarks>
public uint RegionSizeY = Constants.RegionSize;
/// <summary>
/// Z dimension of the region.
/// </summary>
/// <remarks>
/// XXX: Unknown if this accounts for regions with negative Z.
/// </remarks>
public uint RegionSizeZ = Constants.RegionHeight;
private Dictionary<String, String> m_extraSettings = new Dictionary<string, string>();
// Apparently, we're applying the same estatesettings regardless of whether it's local or remote.
// MT: Yes. Estates can't span trust boundaries. Therefore, it can be
// assumed that all instances belonging to one estate are able to
// access the same database server. Since estate settings are lodaed
// from there, that should be sufficient for full remote administration
// File based loading
//
public RegionInfo(string description, string filename, bool skipConsoleConfig, IConfigSource configSource) : this(description, filename, skipConsoleConfig, configSource, String.Empty)
{
}
public RegionInfo(string description, string filename, bool skipConsoleConfig, IConfigSource configSource, string configName)
{
// m_configSource = configSource;
if (filename.ToLower().EndsWith(".ini"))
{
if (!File.Exists(filename)) // New region config request
{
IniConfigSource newFile = new IniConfigSource();
ReadNiniConfig(newFile, configName);
newFile.Save(filename);
RegionFile = filename;
return;
}
IniConfigSource source = new IniConfigSource(filename);
bool saveFile = false;
if (source.Configs[configName] == null)
saveFile = true;
ReadNiniConfig(source, configName);
if (configName != String.Empty && saveFile)
source.Save(filename);
RegionFile = filename;
return;
}
try
{
// This will throw if it's not legal Nini XML format
//
IConfigSource xmlsource = new XmlConfigSource(filename);
ReadNiniConfig(xmlsource, configName);
RegionFile = filename;
return;
}
catch (Exception)
{
}
}
// The web loader uses this
//
public RegionInfo(string description, XmlNode xmlNode, bool skipConsoleConfig, IConfigSource configSource)
{
XmlElement elem = (XmlElement)xmlNode;
string name = elem.GetAttribute("Name");
string xmlstr = "<Nini>" + xmlNode.OuterXml + "</Nini>";
XmlConfigSource source = new XmlConfigSource(XmlReader.Create(new StringReader(xmlstr)));
ReadNiniConfig(source, name);
m_serverURI = string.Empty;
}
public RegionInfo(uint legacyRegionLocX, uint legacyRegionLocY, IPEndPoint internalEndPoint, string externalUri)
{
RegionLocX = legacyRegionLocX;
RegionLocY = legacyRegionLocY;
RegionSizeX = Constants.RegionSize;
RegionSizeY = Constants.RegionSize;
m_internalEndPoint = internalEndPoint;
m_externalHostName = externalUri;
m_serverURI = string.Empty;
}
public RegionInfo()
{
m_serverURI = string.Empty;
}
public EstateSettings EstateSettings
{
get
{
if (m_estateSettings == null)
{
m_estateSettings = new EstateSettings();
}
return m_estateSettings;
}
set { m_estateSettings = value; }
}
public RegionSettings RegionSettings
{
get
{
if (m_regionSettings == null)
{
m_regionSettings = new RegionSettings();
}
return m_regionSettings;
}
set { m_regionSettings = value; }
}
public RegionLightShareData WindlightSettings
{
get
{
if (m_windlight == null)
{
m_windlight = new RegionLightShareData();
}
return m_windlight;
}
set { m_windlight = value; }
}
public float NonphysPrimMin
{
get { return m_nonphysPrimMin; }
}
public int NonphysPrimMax
{
get { return m_nonphysPrimMax; }
}
public float PhysPrimMin
{
get { return m_physPrimMin; }
}
public int PhysPrimMax
{
get { return m_physPrimMax; }
}
public bool ClampPrimSize
{
get { return m_clampPrimSize; }
}
public int ObjectCapacity
{
get { return m_objectCapacity; }
}
public int MaxPrimsPerUser
{
get { return m_maxPrimsPerUser; }
}
public int LinksetCapacity
{
get { return m_linksetCapacity; }
}
public int AgentCapacity { get; set; }
public byte AccessLevel
{
get { return (byte)Util.ConvertMaturityToAccessLevel((uint)RegionSettings.Maturity); }
}
public string RegionType
{
get { return m_regionType; }
}
public UUID MaptileStaticUUID
{
get { return m_maptileStaticUUID; }
}
public string MaptileStaticFile { get; private set; }
/// <summary>
/// The port by which http communication occurs with the region (most noticeably, CAPS communication)
/// </summary>
public uint HttpPort
{
get { return m_httpPort; }
set { m_httpPort = value; }
}
/// <summary>
/// A well-formed URI for the host region server (namely "http://" + ExternalHostName)
/// </summary>
public string ServerURI
{
get {
if ( m_serverURI != string.Empty ) {
return m_serverURI;
} else {
return "http://" + m_externalHostName + ":" + m_httpPort + "/";
}
}
set {
if ( value.EndsWith("/") ) {
m_serverURI = value;
} else {
m_serverURI = value + '/';
}
}
}
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
public uint RemotingPort
{
get { return m_remotingPort; }
set { m_remotingPort = value; }
}
/// <value>
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
/// XXX Isn't this really doing too much to be a simple getter, rather than an explict method?
/// </value>
public IPEndPoint ExternalEndPoint
{
get
{
// Old one defaults to IPv6
//return new IPEndPoint(Dns.GetHostAddresses(m_externalHostName)[0], m_internalEndPoint.Port);
IPAddress ia = null;
// If it is already an IP, don't resolve it - just return directly
if (IPAddress.TryParse(m_externalHostName, out ia))
return new IPEndPoint(ia, m_internalEndPoint.Port);
// Reset for next check
ia = null;
try
{
foreach (IPAddress Adr in Dns.GetHostAddresses(m_externalHostName))
{
if (ia == null)
ia = Adr;
if (Adr.AddressFamily == AddressFamily.InterNetwork)
{
ia = Adr;
break;
}
}
}
catch (SocketException e)
{
throw new Exception(
"Unable to resolve local hostname " + m_externalHostName + " innerException of type '" +
e + "' attached to this exception", e);
}
return new IPEndPoint(ia, m_internalEndPoint.Port);
}
set { m_externalHostName = value.ToString(); }
}
public string ExternalHostName
{
get { return m_externalHostName; }
set { m_externalHostName = value; }
}
public IPEndPoint InternalEndPoint
{
get { return m_internalEndPoint; }
set { m_internalEndPoint = value; }
}
/// <summary>
/// The x co-ordinate of this region in map tiles (e.g. 1000).
/// Coordinate is scaled as world coordinates divided by the legacy region size
/// and is thus is the number of legacy regions.
/// </summary>
public uint RegionLocX
{
get { return WorldLocX / Constants.RegionSize; }
set { WorldLocX = value * Constants.RegionSize; }
}
/// <summary>
/// The y co-ordinate of this region in map tiles (e.g. 1000).
/// Coordinate is scaled as world coordinates divided by the legacy region size
/// and is thus is the number of legacy regions.
/// </summary>
public uint RegionLocY
{
get { return WorldLocY / Constants.RegionSize; }
set { WorldLocY = value * Constants.RegionSize; }
}
public void SetDefaultRegionSize()
{
WorldLocX = 0;
WorldLocY = 0;
WorldLocZ = 0;
RegionSizeX = Constants.RegionSize;
RegionSizeY = Constants.RegionSize;
RegionSizeZ = Constants.RegionHeight;
}
// A unique region handle is created from the region's world coordinates.
// This cannot be changed because some code expects to receive the region handle and then
// compute the region coordinates from it.
public ulong RegionHandle
{
get { return Util.UIntsToLong(WorldLocX, WorldLocY); }
}
public void SetEndPoint(string ipaddr, int port)
{
IPAddress tmpIP = IPAddress.Parse(ipaddr);
IPEndPoint tmpEPE = new IPEndPoint(tmpIP, port);
m_internalEndPoint = tmpEPE;
}
public string GetSetting(string key)
{
string val;
string keylower = key.ToLower();
if (m_extraSettings.TryGetValue(keylower, out val))
return val;
m_log.DebugFormat("[RegionInfo] Could not locate value for parameter {0}", key);
return null;
}
public void SetExtraSetting(string key, string value)
{
string keylower = key.ToLower();
m_extraSettings[keylower] = value;
}
private void ReadNiniConfig(IConfigSource source, string name)
{
// bool creatingNew = false;
if (source.Configs.Count == 0)
{
MainConsole.Instance.Output("=====================================\n");
MainConsole.Instance.Output("We are now going to ask a couple of questions about your region.\n");
MainConsole.Instance.Output("You can press 'enter' without typing anything to use the default\n");
MainConsole.Instance.Output("the default is displayed between [ ] brackets.\n");
MainConsole.Instance.Output("=====================================\n");
if (name == String.Empty)
{
while (name.Trim() == string.Empty)
{
name = MainConsole.Instance.CmdPrompt("New region name", name);
if (name.Trim() == string.Empty)
{
MainConsole.Instance.Output("Cannot interactively create region with no name");
}
}
}
source.AddConfig(name);
// creatingNew = true;
}
if (name == String.Empty)
name = source.Configs[0].Name;
if (source.Configs[name] == null)
{
source.AddConfig(name);
}
RegionName = name;
IConfig config = source.Configs[name];
// Track all of the keys in this config and remove as they are processed
// The remaining keys will be added to generic key-value storage for
// whoever might need it
HashSet<String> allKeys = new HashSet<String>();
foreach (string s in config.GetKeys())
{
allKeys.Add(s);
}
// RegionUUID
//
allKeys.Remove("RegionUUID");
string regionUUID = config.GetString("RegionUUID", string.Empty);
if (!UUID.TryParse(regionUUID.Trim(), out RegionID))
{
UUID newID = UUID.Random();
while (RegionID == UUID.Zero)
{
regionUUID = MainConsole.Instance.CmdPrompt("RegionUUID", newID.ToString());
if (!UUID.TryParse(regionUUID.Trim(), out RegionID))
{
MainConsole.Instance.Output("RegionUUID must be a valid UUID");
}
}
config.Set("RegionUUID", regionUUID);
}
originRegionID = RegionID; // What IS this?! (Needed for RegionCombinerModule?)
// Location
//
allKeys.Remove("Location");
string location = config.GetString("Location", String.Empty);
if (location == String.Empty)
{
location = MainConsole.Instance.CmdPrompt("Region Location", "1000,1000");
config.Set("Location", location);
}
string[] locationElements = location.Split(new char[] {','});
RegionLocX = Convert.ToUInt32(locationElements[0]);
RegionLocY = Convert.ToUInt32(locationElements[1]);
// Region size
// Default to legacy region size if not specified.
allKeys.Remove("SizeX");
string configSizeX = config.GetString("SizeX", Constants.RegionSize.ToString());
config.Set("SizeX", configSizeX);
RegionSizeX = Convert.ToUInt32(configSizeX);
allKeys.Remove("SizeY");
string configSizeY = config.GetString("SizeY", Constants.RegionSize.ToString());
config.Set("SizeY", configSizeX);
RegionSizeY = Convert.ToUInt32(configSizeY);
allKeys.Remove("SizeZ");
string configSizeZ = config.GetString("SizeZ", Constants.RegionHeight.ToString());
config.Set("SizeZ", configSizeX);
RegionSizeZ = Convert.ToUInt32(configSizeZ);
DoRegionSizeSanityChecks();
// InternalAddress
//
IPAddress address;
allKeys.Remove("InternalAddress");
if (config.Contains("InternalAddress"))
{
address = IPAddress.Parse(config.GetString("InternalAddress", String.Empty));
}
else
{
address = IPAddress.Parse(MainConsole.Instance.CmdPrompt("Internal IP address", "0.0.0.0"));
config.Set("InternalAddress", address.ToString());
}
// InternalPort
//
int port;
allKeys.Remove("InternalPort");
if (config.Contains("InternalPort"))
{
port = config.GetInt("InternalPort", 9000);
}
else
{
port = Convert.ToInt32(MainConsole.Instance.CmdPrompt("Internal port", "9000"));
config.Set("InternalPort", port);
}
m_internalEndPoint = new IPEndPoint(address, port);
// AllowAlternatePorts
//
allKeys.Remove("AllowAlternatePorts");
if (config.Contains("AllowAlternatePorts"))
{
m_allow_alternate_ports = config.GetBoolean("AllowAlternatePorts", true);
}
else
{
m_allow_alternate_ports = Convert.ToBoolean(MainConsole.Instance.CmdPrompt("Allow alternate ports", "False"));
config.Set("AllowAlternatePorts", m_allow_alternate_ports.ToString());
}
// ExternalHostName
//
allKeys.Remove("ExternalHostName");
string externalName;
if (config.Contains("ExternalHostName"))
{
externalName = config.GetString("ExternalHostName", "SYSTEMIP");
}
else
{
externalName = MainConsole.Instance.CmdPrompt("External host name", "SYSTEMIP");
config.Set("ExternalHostName", externalName);
}
if (externalName == "SYSTEMIP")
{
m_externalHostName = Util.GetLocalHost().ToString();
m_log.InfoFormat(
"[REGIONINFO]: Resolving SYSTEMIP to {0} for external hostname of region {1}",
m_externalHostName, name);
}
else
{
m_externalHostName = externalName;
}
// RegionType
m_regionType = config.GetString("RegionType", String.Empty);
allKeys.Remove("RegionType");
#region Prim and map stuff
m_nonphysPrimMin = config.GetFloat("NonPhysicalPrimMin", 0);
allKeys.Remove("NonPhysicalPrimMin");
m_nonphysPrimMax = config.GetInt("NonPhysicalPrimMax", 0);
allKeys.Remove("NonPhysicalPrimMax");
m_physPrimMin = config.GetFloat("PhysicalPrimMin", 0);
allKeys.Remove("PhysicalPrimMin");
m_physPrimMax = config.GetInt("PhysicalPrimMax", 0);
allKeys.Remove("PhysicalPrimMax");
m_clampPrimSize = config.GetBoolean("ClampPrimSize", false);
allKeys.Remove("ClampPrimSize");
m_objectCapacity = config.GetInt("MaxPrims", 15000);
allKeys.Remove("MaxPrims");
m_maxPrimsPerUser = config.GetInt("MaxPrimsPerUser", -1);
allKeys.Remove("MaxPrimsPerUser");
m_linksetCapacity = config.GetInt("LinksetPrims", 0);
allKeys.Remove("LinksetPrims");
allKeys.Remove("MaptileStaticUUID");
string mapTileStaticUUID = config.GetString("MaptileStaticUUID", UUID.Zero.ToString());
if (UUID.TryParse(mapTileStaticUUID.Trim(), out m_maptileStaticUUID))
{
config.Set("MaptileStaticUUID", m_maptileStaticUUID.ToString());
}
MaptileStaticFile = config.GetString("MaptileStaticFile", String.Empty);
allKeys.Remove("MaptileStaticFile");
#endregion
AgentCapacity = config.GetInt("MaxAgents", 100);
allKeys.Remove("MaxAgents");
// Multi-tenancy
//
ScopeID = new UUID(config.GetString("ScopeID", UUID.Zero.ToString()));
allKeys.Remove("ScopeID");
foreach (String s in allKeys)
{
SetExtraSetting(s, config.GetString(s));
}
}
// Make sure user specified region sizes are sane.
// Must be multiples of legacy region size (256).
private void DoRegionSizeSanityChecks()
{
if (RegionSizeX != Constants.RegionSize || RegionSizeY != Constants.RegionSize)
{
// Doing non-legacy region sizes.
// Enforce region size to be multiples of the legacy region size (256)
uint partial = RegionSizeX % Constants.RegionSize;
if (partial != 0)
{
RegionSizeX -= partial;
if (RegionSizeX == 0)
RegionSizeX = Constants.RegionSize;
m_log.ErrorFormat("{0} Region size must be multiple of {1}. Enforcing {2}.RegionSizeX={3} instead of specified {4}",
LogHeader, Constants.RegionSize, m_regionName, RegionSizeX, RegionSizeX + partial);
}
partial = RegionSizeY % Constants.RegionSize;
if (partial != 0)
{
RegionSizeY -= partial;
if (RegionSizeY == 0)
RegionSizeY = Constants.RegionSize;
m_log.ErrorFormat("{0} Region size must be multiple of {1}. Enforcing {2}.RegionSizeY={3} instead of specified {4}",
LogHeader, Constants.RegionSize, m_regionName, RegionSizeY, RegionSizeY + partial);
}
// Because of things in the viewer, regions MUST be square.
// Remove this check when viewers have been updated.
if (RegionSizeX != RegionSizeY)
{
uint minSize = Math.Min(RegionSizeX, RegionSizeY);
RegionSizeX = minSize;
RegionSizeY = minSize;
m_log.ErrorFormat("{0} Regions must be square until viewers are updated. Forcing region {1} size to <{2},{3}>",
LogHeader, m_regionName, RegionSizeX, RegionSizeY);
}
// There is a practical limit to region size.
if (RegionSizeX > Constants.MaximumRegionSize || RegionSizeY > Constants.MaximumRegionSize)
{
RegionSizeX = Util.Clamp<uint>(RegionSizeX, Constants.RegionSize, Constants.MaximumRegionSize);
RegionSizeY = Util.Clamp<uint>(RegionSizeY, Constants.RegionSize, Constants.MaximumRegionSize);
m_log.ErrorFormat("{0} Region dimensions must be less than {1}. Clamping {2}'s size to <{3},{4}>",
LogHeader, Constants.MaximumRegionSize, m_regionName, RegionSizeX, RegionSizeY);
}
m_log.InfoFormat("{0} Region {1} size set to <{2},{3}>", LogHeader, m_regionName, RegionSizeX, RegionSizeY);
}
}
private void WriteNiniConfig(IConfigSource source)
{
IConfig config = source.Configs[RegionName];
if (config != null)
source.Configs.Remove(config);
config = source.AddConfig(RegionName);
config.Set("RegionUUID", RegionID.ToString());
string location = String.Format("{0},{1}", RegionLocX, RegionLocY);
config.Set("Location", location);
if (DataStore != String.Empty)
config.Set("Datastore", DataStore);
if (RegionSizeX != Constants.RegionSize || RegionSizeY != Constants.RegionSize)
{
config.Set("SizeX", RegionSizeX);
config.Set("SizeY", RegionSizeY);
// if (RegionSizeZ > 0)
// config.Set("SizeZ", RegionSizeZ);
}
config.Set("InternalAddress", m_internalEndPoint.Address.ToString());
config.Set("InternalPort", m_internalEndPoint.Port);
config.Set("AllowAlternatePorts", m_allow_alternate_ports.ToString());
config.Set("ExternalHostName", m_externalHostName);
if (m_nonphysPrimMin > 0)
config.Set("NonphysicalPrimMax", m_nonphysPrimMin);
if (m_nonphysPrimMax > 0)
config.Set("NonphysicalPrimMax", m_nonphysPrimMax);
if (m_physPrimMin > 0)
config.Set("PhysicalPrimMax", m_physPrimMin);
if (m_physPrimMax > 0)
config.Set("PhysicalPrimMax", m_physPrimMax);
config.Set("ClampPrimSize", m_clampPrimSize.ToString());
if (m_objectCapacity > 0)
config.Set("MaxPrims", m_objectCapacity);
if (m_maxPrimsPerUser > -1)
config.Set("MaxPrimsPerUser", m_maxPrimsPerUser);
if (m_linksetCapacity > 0)
config.Set("LinksetPrims", m_linksetCapacity);
if (AgentCapacity > 0)
config.Set("MaxAgents", AgentCapacity);
if (ScopeID != UUID.Zero)
config.Set("ScopeID", ScopeID.ToString());
if (RegionType != String.Empty)
config.Set("RegionType", RegionType);
if (m_maptileStaticUUID != UUID.Zero)
config.Set("MaptileStaticUUID", m_maptileStaticUUID.ToString());
if (MaptileStaticFile != null && MaptileStaticFile != String.Empty)
config.Set("MaptileStaticFile", MaptileStaticFile);
}
public void SaveRegionToFile(string description, string filename)
{
if (filename.ToLower().EndsWith(".ini"))
{
IniConfigSource source = new IniConfigSource();
try
{
source = new IniConfigSource(filename); // Load if it exists
}
catch (Exception)
{
}
WriteNiniConfig(source);
source.Save(filename);
return;
}
else
throw new Exception("Invalid file type for region persistence.");
}
public void loadConfigurationOptionsFromMe()
{
configMember.addConfigurationOption("sim_UUID", ConfigurationOption.ConfigurationTypes.TYPE_UUID_NULL_FREE,
"UUID of Region (Default is recommended, random UUID)",
RegionID.ToString(), true);
configMember.addConfigurationOption("sim_name", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY,
"Region Name", RegionName, true);
configMember.addConfigurationOption("sim_location_x", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Grid Location (X Axis)", RegionLocX.ToString(), true);
configMember.addConfigurationOption("sim_location_y", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Grid Location (Y Axis)", RegionLocY.ToString(), true);
configMember.addConfigurationOption("sim_size_x", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Size of region in X dimension", RegionSizeX.ToString(), true);
configMember.addConfigurationOption("sim_size_y", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Size of region in Y dimension", RegionSizeY.ToString(), true);
configMember.addConfigurationOption("sim_size_z", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Size of region in Z dimension", RegionSizeZ.ToString(), true);
//m_configMember.addConfigurationOption("datastore", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY, "Filename for local storage", "OpenSim.db", false);
configMember.addConfigurationOption("internal_ip_address",
ConfigurationOption.ConfigurationTypes.TYPE_IP_ADDRESS,
"Internal IP Address for incoming UDP client connections",
m_internalEndPoint.Address.ToString(),
true);
configMember.addConfigurationOption("internal_ip_port", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Internal IP Port for incoming UDP client connections",
m_internalEndPoint.Port.ToString(), true);
configMember.addConfigurationOption("allow_alternate_ports",
ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN,
"Allow sim to find alternate UDP ports when ports are in use?",
m_allow_alternate_ports.ToString(), true);
configMember.addConfigurationOption("external_host_name",
ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY,
"External Host Name", m_externalHostName, true);
configMember.addConfigurationOption("lastmap_uuid", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"Last Map UUID", lastMapUUID.ToString(), true);
configMember.addConfigurationOption("lastmap_refresh", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY,
"Last Map Refresh", Util.UnixTimeSinceEpoch().ToString(), true);
configMember.addConfigurationOption("nonphysical_prim_min", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"Minimum size for nonphysical prims", m_nonphysPrimMin.ToString(), true);
configMember.addConfigurationOption("nonphysical_prim_max", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Maximum size for nonphysical prims", m_nonphysPrimMax.ToString(), true);
configMember.addConfigurationOption("physical_prim_min", ConfigurationOption.ConfigurationTypes.TYPE_FLOAT,
"Minimum size for nonphysical prims", m_physPrimMin.ToString(), true);
configMember.addConfigurationOption("physical_prim_max", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Maximum size for physical prims", m_physPrimMax.ToString(), true);
configMember.addConfigurationOption("clamp_prim_size", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN,
"Clamp prims to max size", m_clampPrimSize.ToString(), true);
configMember.addConfigurationOption("object_capacity", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Max objects this sim will hold", m_objectCapacity.ToString(), true);
configMember.addConfigurationOption("linkset_capacity", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Max prims an object will hold", m_linksetCapacity.ToString(), true);
configMember.addConfigurationOption("agent_capacity", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Max avatars this sim will hold",AgentCapacity.ToString(), true);
configMember.addConfigurationOption("scope_id", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"Scope ID for this region", ScopeID.ToString(), true);
configMember.addConfigurationOption("region_type", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Free form string describing the type of region", String.Empty, true);
configMember.addConfigurationOption("region_static_maptile", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"UUID of a texture to use as the map for this region", m_maptileStaticUUID.ToString(), true);
}
public void loadConfigurationOptions()
{
configMember.addConfigurationOption("sim_UUID", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"UUID of Region (Default is recommended, random UUID)",
UUID.Random().ToString(), true);
configMember.addConfigurationOption("sim_name", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY,
"Region Name", "OpenSim Test", false);
configMember.addConfigurationOption("sim_location_x", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Grid Location (X Axis)", "1000", false);
configMember.addConfigurationOption("sim_location_y", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Grid Location (Y Axis)", "1000", false);
configMember.addConfigurationOption("sim_size_x", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Size of region in X dimension", Constants.RegionSize.ToString(), false);
configMember.addConfigurationOption("sim_size_y", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Size of region in Y dimension", Constants.RegionSize.ToString(), false);
configMember.addConfigurationOption("sim_size_z", ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
"Size of region in Z dimension", Constants.RegionHeight.ToString(), false);
//m_configMember.addConfigurationOption("datastore", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY, "Filename for local storage", "OpenSim.db", false);
configMember.addConfigurationOption("internal_ip_address",
ConfigurationOption.ConfigurationTypes.TYPE_IP_ADDRESS,
"Internal IP Address for incoming UDP client connections", "0.0.0.0",
false);
configMember.addConfigurationOption("internal_ip_port", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Internal IP Port for incoming UDP client connections",
ConfigSettings.DefaultRegionHttpPort.ToString(), false);
configMember.addConfigurationOption("allow_alternate_ports", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN,
"Allow sim to find alternate UDP ports when ports are in use?",
"false", true);
configMember.addConfigurationOption("external_host_name",
ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY,
"External Host Name", "127.0.0.1", false);
configMember.addConfigurationOption("lastmap_uuid", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"Last Map UUID", lastMapUUID.ToString(), true);
configMember.addConfigurationOption("lastmap_refresh", ConfigurationOption.ConfigurationTypes.TYPE_STRING_NOT_EMPTY,
"Last Map Refresh", Util.UnixTimeSinceEpoch().ToString(), true);
configMember.addConfigurationOption("nonphysical_prim_max", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Maximum size for nonphysical prims", "0", true);
configMember.addConfigurationOption("physical_prim_max", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Maximum size for physical prims", "0", true);
configMember.addConfigurationOption("clamp_prim_size", ConfigurationOption.ConfigurationTypes.TYPE_BOOLEAN,
"Clamp prims to max size", "false", true);
configMember.addConfigurationOption("object_capacity", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Max objects this sim will hold", "15000", true);
configMember.addConfigurationOption("agent_capacity", ConfigurationOption.ConfigurationTypes.TYPE_INT32,
"Max avatars this sim will hold", "100", true);
configMember.addConfigurationOption("scope_id", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"Scope ID for this region", UUID.Zero.ToString(), true);
configMember.addConfigurationOption("region_type", ConfigurationOption.ConfigurationTypes.TYPE_STRING,
"Region Type", String.Empty, true);
configMember.addConfigurationOption("region_static_maptile", ConfigurationOption.ConfigurationTypes.TYPE_UUID,
"UUID of a texture to use as the map for this region", String.Empty, true);
}
public bool handleIncomingConfiguration(string configuration_key, object configuration_result)
{
switch (configuration_key)
{
case "sim_UUID":
RegionID = (UUID) configuration_result;
originRegionID = (UUID) configuration_result;
break;
case "sim_name":
RegionName = (string) configuration_result;
break;
case "sim_location_x":
RegionLocX = (uint) configuration_result;
break;
case "sim_location_y":
RegionLocY = (uint) configuration_result;
break;
case "sim_size_x":
RegionSizeX = (uint) configuration_result;
break;
case "sim_size_y":
RegionSizeY = (uint) configuration_result;
break;
case "sim_size_z":
RegionSizeZ = (uint) configuration_result;
break;
case "datastore":
DataStore = (string) configuration_result;
break;
case "internal_ip_address":
IPAddress address = (IPAddress) configuration_result;
m_internalEndPoint = new IPEndPoint(address, 0);
break;
case "internal_ip_port":
m_internalEndPoint.Port = (int) configuration_result;
break;
case "allow_alternate_ports":
m_allow_alternate_ports = (bool) configuration_result;
break;
case "external_host_name":
if ((string) configuration_result != "SYSTEMIP")
{
m_externalHostName = (string) configuration_result;
}
else
{
m_externalHostName = Util.GetLocalHost().ToString();
}
break;
case "lastmap_uuid":
lastMapUUID = (UUID)configuration_result;
break;
case "lastmap_refresh":
lastMapRefresh = (string)configuration_result;
break;
case "nonphysical_prim_max":
m_nonphysPrimMax = (int)configuration_result;
break;
case "physical_prim_max":
m_physPrimMax = (int)configuration_result;
break;
case "clamp_prim_size":
m_clampPrimSize = (bool)configuration_result;
break;
case "object_capacity":
m_objectCapacity = (int)configuration_result;
break;
case "linkset_capacity":
m_linksetCapacity = (int)configuration_result;
break;
case "agent_capacity":
AgentCapacity = (int)configuration_result;
break;
case "scope_id":
ScopeID = (UUID)configuration_result;
break;
case "region_type":
m_regionType = (string)configuration_result;
break;
case "region_static_maptile":
m_maptileStaticUUID = (UUID)configuration_result;
break;
}
return true;
}
public void SaveLastMapUUID(UUID mapUUID)
{
lastMapUUID = mapUUID;
lastMapRefresh = Util.UnixTimeSinceEpoch().ToString();
}
public OSDMap PackRegionInfoData()
{
OSDMap args = new OSDMap();
args["region_id"] = OSD.FromUUID(RegionID);
if ((RegionName != null) && !RegionName.Equals(""))
args["region_name"] = OSD.FromString(RegionName);
args["external_host_name"] = OSD.FromString(ExternalHostName);
args["http_port"] = OSD.FromString(HttpPort.ToString());
args["server_uri"] = OSD.FromString(ServerURI);
args["region_xloc"] = OSD.FromString(RegionLocX.ToString());
args["region_yloc"] = OSD.FromString(RegionLocY.ToString());
args["region_size_x"] = OSD.FromString(RegionSizeX.ToString());
args["region_size_y"] = OSD.FromString(RegionSizeY.ToString());
args["region_size_z"] = OSD.FromString(RegionSizeZ.ToString());
args["internal_ep_address"] = OSD.FromString(InternalEndPoint.Address.ToString());
args["internal_ep_port"] = OSD.FromString(InternalEndPoint.Port.ToString());
if ((RemotingAddress != null) && !RemotingAddress.Equals(""))
args["remoting_address"] = OSD.FromString(RemotingAddress);
args["remoting_port"] = OSD.FromString(RemotingPort.ToString());
args["allow_alt_ports"] = OSD.FromBoolean(m_allow_alternate_ports);
if ((proxyUrl != null) && !proxyUrl.Equals(""))
args["proxy_url"] = OSD.FromString(proxyUrl);
if (RegionType != String.Empty)
args["region_type"] = OSD.FromString(RegionType);
return args;
}
public void UnpackRegionInfoData(OSDMap args)
{
if (args["region_id"] != null)
RegionID = args["region_id"].AsUUID();
if (args["region_name"] != null)
RegionName = args["region_name"].AsString();
if (args["external_host_name"] != null)
ExternalHostName = args["external_host_name"].AsString();
if (args["http_port"] != null)
UInt32.TryParse(args["http_port"].AsString(), out m_httpPort);
if (args["server_uri"] != null)
ServerURI = args["server_uri"].AsString();
if (args["region_xloc"] != null)
{
uint locx;
UInt32.TryParse(args["region_xloc"].AsString(), out locx);
RegionLocX = locx;
}
if (args["region_yloc"] != null)
{
uint locy;
UInt32.TryParse(args["region_yloc"].AsString(), out locy);
RegionLocY = locy;
}
if (args.ContainsKey("region_size_x"))
RegionSizeX = (uint)args["region_size_x"].AsInteger();
if (args.ContainsKey("region_size_y"))
RegionSizeY = (uint)args["region_size_y"].AsInteger();
if (args.ContainsKey("region_size_z"))
RegionSizeZ = (uint)args["region_size_z"].AsInteger();
IPAddress ip_addr = null;
if (args["internal_ep_address"] != null)
{
IPAddress.TryParse(args["internal_ep_address"].AsString(), out ip_addr);
}
int port = 0;
if (args["internal_ep_port"] != null)
{
Int32.TryParse(args["internal_ep_port"].AsString(), out port);
}
InternalEndPoint = new IPEndPoint(ip_addr, port);
if (args["remoting_address"] != null)
RemotingAddress = args["remoting_address"].AsString();
if (args["remoting_port"] != null)
UInt32.TryParse(args["remoting_port"].AsString(), out m_remotingPort);
if (args["allow_alt_ports"] != null)
m_allow_alternate_ports = args["allow_alt_ports"].AsBoolean();
if (args["proxy_url"] != null)
proxyUrl = args["proxy_url"].AsString();
if (args["region_type"] != null)
m_regionType = args["region_type"].AsString();
}
public static RegionInfo Create(UUID regionID, string regionName, uint regX, uint regY, string externalHostName, uint httpPort, uint simPort, uint remotingPort, string serverURI)
{
RegionInfo regionInfo;
IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(externalHostName), (int)simPort);
regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, externalHostName);
regionInfo.RemotingPort = remotingPort;
regionInfo.RemotingAddress = externalHostName;
regionInfo.HttpPort = httpPort;
regionInfo.RegionID = regionID;
regionInfo.RegionName = regionName;
regionInfo.ServerURI = serverURI;
return regionInfo;
}
public int getInternalEndPointPort()
{
return m_internalEndPoint.Port;
}
public Dictionary<string, object> ToKeyValuePairs()
{
Dictionary<string, object> kvp = new Dictionary<string, object>();
kvp["uuid"] = RegionID.ToString();
kvp["locX"] = RegionLocX.ToString();
kvp["locY"] = RegionLocY.ToString();
kvp["external_ip_address"] = ExternalEndPoint.Address.ToString();
kvp["external_port"] = ExternalEndPoint.Port.ToString();
kvp["external_host_name"] = ExternalHostName;
kvp["http_port"] = HttpPort.ToString();
kvp["internal_ip_address"] = InternalEndPoint.Address.ToString();
kvp["internal_port"] = InternalEndPoint.Port.ToString();
kvp["alternate_ports"] = m_allow_alternate_ports.ToString();
kvp["server_uri"] = ServerURI;
return kvp;
}
}
}
| |
// 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.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class HashtableTests
{
[Fact]
public static void Ctor_Empty()
{
var hash = new ComparableHashtable();
VerifyHashtable(hash, null, null);
}
[Fact]
public static void Ctor_IDictionary()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable());
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))));
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null)); // Dictionary is null
}
[Fact]
public static void Ctor_IEqualityComparer()
{
// Null comparer
var hash = new ComparableHashtable((IEqualityComparer)null);
VerifyHashtable(hash, null, null);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(comparer);
VerifyHashtable(hash, null, comparer);
});
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
public static void Ctor_Int(int capacity)
{
var hash = new ComparableHashtable(capacity);
VerifyHashtable(hash, null, null);
}
[Fact]
public static void Ctor_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1)); // Capacity < 0
Assert.Throws<ArgumentException>("capacity", () => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue
}
[Fact]
public static void Ctor_IDictionary_Int()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public static void Ctor_IDictionary_Int_Invalid()
{
Assert.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f)); // Dictionary is null
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity)); // Load factor is infinity
}
[Fact]
public static void Ctor_IDictionary_IEqualityComparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, null);
VerifyHashtable(hash1, hash2, null);
// Custom comparer
hash2 = Helpers.CreateIntHashtable(100);
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, comparer);
VerifyHashtable(hash1, hash2, comparer);
});
}
[Fact]
public static void Ctor_IDictionary_IEqualityComparer_NullDictionary_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("d", () => new Hashtable(null, null)); // Dictionary is null
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public static void Ctor_Int_Int(int capacity, float loadFactor)
{
var hash = new ComparableHashtable(capacity, loadFactor);
VerifyHashtable(hash, null, null);
}
[Fact]
public static void Ctor_Int_Int_GenerateNewPrime()
{
// The ctor for Hashtable performs the following calculation:
// rawSize = capacity / (loadFactor * 0.72)
// If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime.
// Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically
// This test makes sure this works.
int capacity = 8000000;
float loadFactor = 0.1f / 0.72f;
try
{
var hash = new ComparableHashtable(capacity, loadFactor);
}
catch (OutOfMemoryException)
{
// On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore.
}
}
[Fact]
public static void Ctor_Int_Int_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f)); // Capacity < 0
Assert.Throws<ArgumentException>("capacity", () => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity)); // Load factor is infinity
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Ctor_Int_IEqualityComparer(int capacity)
{
// Null comparer
var hash = new ComparableHashtable(capacity, null);
VerifyHashtable(hash, null, null);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacity, comparer);
VerifyHashtable(hash, null, comparer);
});
}
[Fact]
public static void Ctor_Int_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, null)); // Capacity < 0
Assert.Throws<ArgumentException>("capacity", () => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue
}
[Fact]
public static void Ctor_IDictionary_Int_IEqualityComparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f, null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(
new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f, null);
VerifyHashtable(hash1, hash2, null);
hash2 = Helpers.CreateIntHashtable(100);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, 1f, comparer);
VerifyHashtable(hash1, hash2, comparer);
});
}
[Fact]
public static void Ctor_IDictionary_LoadFactor_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f, null)); // Dictionary is null
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity, null)); // Load factor is infinity
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public static void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor)
{
// Null comparer
var hash = new ComparableHashtable(capacity, loadFactor, null);
VerifyHashtable(hash, null, null);
Assert.Null(hash.EqualityComparer);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacity, loadFactor, comparer);
VerifyHashtable(hash, null, comparer);
});
}
[Fact]
public static void Ctor_Capacity_LoadFactor_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f, null)); // Capacity < 0
Assert.Throws<ArgumentException>("capacity", () => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f, null)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN, null)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity
Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity, null)); // Load factor is infinity
}
[Fact]
public static void DebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable());
var hash = new Hashtable() { { "a", 1 }, { "b", 2 } };
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash));
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null);
}
catch (TargetInvocationException ex)
{
threwNull = ex.InnerException is ArgumentNullException;
}
Assert.True(threwNull);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void Add(int count)
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
hash2.Add(key, value);
Assert.Equal(i + 1, hash2.Count);
Assert.True(hash2.ContainsKey(key));
Assert.True(hash2.ContainsValue(value));
Assert.Equal(value, hash2[key]);
}
Assert.Equal(count, hash2.Count);
});
}
[Fact]
public static void Add_ReferenceType()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
// Value is a reference
var foo = new Foo();
hash2.Add("Key", foo);
Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue);
// Changing original object should change the object stored in the Hashtable
foo.StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue);
});
}
[Fact]
public static void Add_Invalid()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>("key", () => hash2.Add(null, 1)); // Key is null
Assert.Throws<ArgumentException>(null, () => hash2.Add("Key_1", "Value_2")); // Key already exists
});
}
[Fact]
public static void Add_ClearRepeatedly()
{
const int Iterations = 2;
const int Count = 2;
var hash = new Hashtable();
for (int i = 0; i < Iterations; i++)
{
for (int j = 0; j < Count; j++)
{
string key = "Key: i=" + i + ", j=" + j;
string value = "Value: i=" + i + ", j=" + j;
hash.Add(key, value);
}
Assert.Equal(Count, hash.Count);
hash.Clear();
}
}
[Fact]
[OuterLoop]
public static void AddRemove_LargeAmountNumbers()
{
// Generate a random 100,000 array of ints as test data
var inputData = new int[100000];
var random = new Random(341553);
for (int i = 0; i < inputData.Length; i++)
{
inputData[i] = random.Next(7500000, int.MaxValue);
}
var hash = new Hashtable();
int count = 0;
foreach (long number in inputData)
{
hash.Add(number, count++);
}
count = 0;
foreach (long number in inputData)
{
Assert.Equal(hash[number], count);
Assert.True(hash.ContainsKey(number));
count++;
}
foreach (long number in inputData)
{
hash.Remove(number);
}
Assert.Equal(0, hash.Count);
}
[Fact]
public static void DuplicatedKeysWithInitialCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable(200);
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Fact]
public static void DuplicatedKeysWithDefaultCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable();
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void Clear(int count)
{
Hashtable hash1 = Helpers.CreateIntHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
hash2.Clear();
for (int i = 0; i < hash2.Count; i++)
{
Assert.False(hash2.ContainsKey(i));
Assert.False(hash2.ContainsValue(i));
}
Assert.Equal(0, hash2.Count);
hash2.Clear();
Assert.Equal(0, hash2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void Clone(int count)
{
Hashtable hash1 = Helpers.CreateStringHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Hashtable clone = (Hashtable)hash2.Clone();
Assert.Equal(hash2.Count, clone.Count);
Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized);
Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize);
Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly);
for (int i = 0; i < clone.Count; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
Assert.True(clone.ContainsKey(key));
Assert.True(clone.ContainsValue(value));
Assert.Equal(value, clone[key]);
}
});
}
[Fact]
public static void Clone_IsShallowCopy()
{
var hash = new Hashtable();
for (int i = 0; i < 10; i++)
{
hash.Add(i, new Foo());
}
Hashtable clone = (Hashtable)hash.Clone();
for (int i = 0; i < clone.Count; i++)
{
Assert.Equal("Hello World", ((Foo)clone[i]).StringValue);
Assert.Same(hash[i], clone[i]);
}
// Change object in original hashtable
((Foo)hash[1]).StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue);
// Removing an object from the original hashtable doesn't change the clone
hash.Remove(0);
Assert.True(clone.Contains(0));
}
[Fact]
public static void Clone_HashtableCastedToInterfaces()
{
// Try to cast the returned object from Clone() to different types
Hashtable hash = Helpers.CreateIntHashtable(100);
ICollection collection = (ICollection)hash.Clone();
Assert.Equal(hash.Count, collection.Count);
IDictionary dictionary = (IDictionary)hash.Clone();
Assert.Equal(hash.Count, dictionary.Count);
}
[Fact]
public static void ContainsKey()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
Assert.True(hash2.ContainsKey(key));
Assert.True(hash2.Contains(key));
}
Assert.False(hash2.ContainsKey("Non Existent Key"));
Assert.False(hash2.Contains("Non Existent Key"));
Assert.False(hash2.ContainsKey(101));
Assert.False(hash2.Contains("Non Existent Key"));
string removedKey = "Key_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsKey(removedKey));
Assert.False(hash2.Contains(removedKey));
});
}
[Fact]
public static void ContainsKey_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(foo1, 101);
Assert.True(hash2.ContainsKey(foo2));
Assert.True(hash2.Contains(foo2));
int i1 = 0x10;
int i2 = 0x100;
long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode
long l2 = (((long)i2) << 32) + i1;
hash2.Add(l1, 101);
hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set
Assert.True(hash2.ContainsKey(l1));
Assert.True(hash2.Contains(l1));
hash2.Remove(l1); // Remove the first item
Assert.False(hash2.ContainsKey(l1));
Assert.False(hash2.Contains(l1));
Assert.True(hash2.ContainsKey(l2));
Assert.True(hash2.Contains(l2));
});
}
[Fact]
public static void ContainsKey_NullKey_ThrowsArgumentNullException()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>("key", () => hash2.ContainsKey(null)); // Key is null
Assert.Throws<ArgumentNullException>("key", () => hash2.Contains(null)); // Key is null
});
}
[Fact]
public static void ContainsValue()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string value = "Value_" + i;
Assert.True(hash2.ContainsValue(value));
}
Assert.False(hash2.ContainsValue("Non Existent Value"));
Assert.False(hash2.ContainsValue(101));
Assert.False(hash2.ContainsValue(null));
hash2.Add("Key_101", null);
Assert.True(hash2.ContainsValue(null));
string removedKey = "Key_1";
string removedValue = "Value_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsValue(removedValue));
});
}
[Fact]
public static void ContainsValue_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(101, foo1);
Assert.True(hash2.ContainsValue(foo2));
});
}
[Fact]
public static void CopyTo()
{
var hash1 = new Hashtable();
var keys = new object[]
{
new object(),
"Hello" ,
"my array" ,
new DateTime(),
new SortedList(),
typeof(Environment),
5
};
var values = new object[]
{
"Somestring" ,
new object(),
new int [] { 1, 2, 3, 4, 5 },
new Hashtable(),
new Exception(),
new Guid(),
null
};
for (int i = 0; i < values.Length; i++)
{
hash1.Add(keys[i], values[i]);
}
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var array = new object[values.Length + 2];
array[0] = "start-string";
array[values.Length + 1] = "end-string";
hash2.CopyTo(array, 1);
Assert.Equal("start-string", array[0]);
Assert.Equal("end-string", array[values.Length + 1]);
Assert.Equal(values.Length + 2, array.Length);
for (int i = 1; i < array.Length - 1; i++)
{
DictionaryEntry entry = (DictionaryEntry)array[i];
int valueIndex = Array.IndexOf(values, entry.Value);
int keyIndex = Array.IndexOf(keys, entry.Key);
Assert.NotEqual(-1, valueIndex);
Assert.NotEqual(-1, keyIndex);
Assert.Equal(valueIndex, keyIndex);
}
});
}
[Fact]
public static void CopyTo_EmptyHashtable()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var array = new object[0];
hash2.CopyTo(array, 0);
Assert.Equal(0, array.Length);
array = new object[100];
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
// Both of these should be valid
hash2.CopyTo(array, 99);
hash2.CopyTo(array, 100);
Assert.Equal(100, array.Length);
for (int i = 0; i < array.Length; i++)
{
Assert.Equal(i, array[i]);
}
});
}
[Fact]
public static void CopyTo_Invalid()
{
Hashtable hash1 = Helpers.CreateIntHashtable(10);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>("array", () => hash2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>("array", () => hash2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
Assert.Throws<InvalidCastException>(() => hash2.CopyTo(new object[10][], 0)); // Array is invalid
Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => hash2.CopyTo(new object[10], -1)); // Index < 0
Assert.Throws<ArgumentException>(null,() => hash2.CopyTo(new object[9], 0)); // Hash.Count + index > array.Length
Assert.Throws<ArgumentException>(null, () => hash2.CopyTo(new object[11], 2)); // Hash.Count + index > array.Length
Assert.Throws<ArgumentException>(null, () => hash2.CopyTo(new object[0], 0)); // Hash.Count + index > array.Length
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void GetEnumerator_IDictionaryEnumerator(int count)
{
Hashtable hash1 = Helpers.CreateIntHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IDictionaryEnumerator enumerator1 = hash2.GetEnumerator();
IDictionaryEnumerator enumerator2 = hash2.GetEnumerator();
Assert.NotSame(enumerator1, enumerator2);
Assert.NotNull(enumerator1);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator1.MoveNext())
{
DictionaryEntry entry1 = (DictionaryEntry)enumerator1.Current;
DictionaryEntry entry2 = enumerator1.Entry;
Assert.Equal(entry1.Key, entry2.Key);
Assert.Equal(entry1.Value, entry2.Value);
Assert.Equal(enumerator1.Key, entry1.Key);
Assert.Equal(enumerator1.Value, entry1.Value);
Assert.Equal(enumerator1.Value, hash2[enumerator1.Key]);
counter++;
}
Assert.Equal(hash2.Count, counter);
enumerator1.Reset();
}
});
}
[Fact]
public static void GetEnumerator_IDictionaryEnumerator_Invalid()
{
Hashtable hash1 = Helpers.CreateIntHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IDictionaryEnumerator enumerator = hash2.GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Index > dictionary.Count
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// MoveNext and Reset throw after modifying the hashtable
enumerator.MoveNext();
hash2.Add("Key", "Value");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
Assert.NotNull(enumerator.Entry);
Assert.NotNull(enumerator.Key);
Assert.NotNull(enumerator.Value);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void GetEnumerator_IEnumerator(int count)
{
Hashtable hash1 = Helpers.CreateStringHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IEnumerator enumerator1 = ((IEnumerable)hash2).GetEnumerator();
IDictionaryEnumerator enumerator2 = hash2.GetEnumerator();
Assert.NotSame(enumerator1, enumerator2);
Assert.NotNull(enumerator1);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator1.MoveNext())
{
DictionaryEntry entry = (DictionaryEntry)enumerator1.Current;
Assert.Equal(entry.Value, hash2[entry.Key]);
counter++;
}
Assert.Equal(hash2.Count, counter);
enumerator1.Reset();
}
});
}
[Fact]
public static void GetEnumerator_IEnumerator_Invalid()
{
Hashtable hash1 = Helpers.CreateIntHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IEnumerator enumerator = ((IEnumerable)hash2).GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Index >= dictionary.Count
while (enumerator.MoveNext()) ;
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// MoveNext and Reset throw after modifying the hashtable
enumerator.MoveNext();
hash2.Add("Key", "Value");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
});
}
[Fact]
public static void GetItem()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Equal(null, hash2["No_Such_Key"]);
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
Assert.Equal("Value_" + i, hash2[key]);
hash2.Remove(key);
Assert.Equal(null, hash2[key]);
}
});
}
[Fact]
public static void GetItem_NullKey_ThrowsArgumentNullException()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>("key", () => hash2[null]); // Key is null
});
}
[Fact]
public static void SetItem()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
// Non existent key
hash2[key] = "Value";
Assert.Equal("Value", hash2[key]);
// Existent key
hash2[key] = value;
Assert.Equal(value, hash2[key]);
// Null
hash2[key] = null;
Assert.Equal(null, hash2[key]);
Assert.True(hash2.ContainsKey(key));
}
});
}
[Fact]
public static void SetItem_NullKey_ThrowsArgumentNullException()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>("key", () => hash2[null] = "Value"); // Key is null
});
}
[Fact]
public static void Keys_ICollectionProperties()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys1 = hash2.Keys;
Assert.False(keys1.IsSynchronized);
Assert.Equal(hash2.SyncRoot, keys1.SyncRoot);
Assert.Equal(hash2.Count, keys1.Count);
hash2.Clear();
Assert.Equal(keys1.Count, 0);
ICollection keys2 = hash2.Keys;
Assert.Same(keys1, keys2);
});
}
[Fact]
public static void Keys_GetEnumerator()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys = hash2.Keys;
IEnumerator enum1 = keys.GetEnumerator();
IEnumerator enum2 = keys.GetEnumerator();
Assert.NotSame(enum1, enum2);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enum1.MoveNext())
{
Assert.True(hash2.ContainsKey(enum1.Current));
counter++;
}
Assert.Equal(keys.Count, counter);
enum1.Reset();
}
});
}
[Fact]
public static void Keys_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection keys = hash.Keys;
// Removing a key from the hashtable should update the Keys ICollection.
// This means that the Keys ICollection no longer contains the key.
hash.Remove("Key_0");
IEnumerator enumerator = keys.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Key_0", enumerator.Current);
}
}
[Fact]
public static void Keys_CopyTo()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys = hash2.Keys;
// Index = 0
object[] keysCopy = new object[keys.Count];
keys.CopyTo(keysCopy, 0);
Assert.Equal(keys.Count, keysCopy.Length);
for (int i = 0; i < keysCopy.Length; i++)
{
Assert.True(hash2.ContainsKey(keysCopy[i]));
}
// Index > 0
int index = 50;
keysCopy = new object[keys.Count + index];
keys.CopyTo(keysCopy, index);
Assert.Equal(keys.Count + index, keysCopy.Length);
for (int i = index; i < keysCopy.Length; i++)
{
Assert.True(hash2.ContainsKey(keysCopy[i]));
}
});
}
[Fact]
public static void Keys_CopyTo_Invalid()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys = hash2.Keys;
Assert.Throws<ArgumentNullException>("array", () => keys.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>("array", () => keys.CopyTo(new object[100, 100], 0)); // Array is multidimensional
Assert.Throws<ArgumentException>(null, () => keys.CopyTo(new object[50], 0)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentException>(null, () => keys.CopyTo(new object[100], 1)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => keys.CopyTo(new object[100], -1)); // Index < 0
});
}
[Fact]
public static void Remove()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
hash2.Remove(key);
Assert.Equal(null, hash2[key]);
Assert.False(hash2.ContainsKey(key));
}
hash2.Remove("Non_Existent_Key");
});
}
[Fact]
public static void Remove_SameHashcode()
{
// We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable
// does not expand but have to tread through collision bit set positions to insert the new elements. We do this
// by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that
// the hashtable does not expand as long as we have at most 7 elements at any given time?
var hash = new Hashtable();
var arrList = new ArrayList();
for (int i = 0; i < 7; i++)
{
var hashConfuse = new BadHashCode(i);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, i);
}
var rand = new Random(-55);
int iCount = 7;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 7; j++)
{
Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value);
}
// Delete 3 elements from the hashtable
for (int j = 0; j < 3; j++)
{
int iElement = rand.Next(6);
hash.Remove(arrList[iElement]);
Assert.False(hash.ContainsValue(null));
arrList.RemoveAt(iElement);
int testInt = iCount++;
var hashConfuse = new BadHashCode(testInt);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, testInt);
}
}
}
[Fact]
public static void Remove_NullKey_ThrowsArgumentNullException()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>("key", () => hash2.Remove(null)); // Key is null
});
}
[Fact]
public static void SynchronizedProperties()
{
// Ensure Synchronized correctly reflects a wrapped hashtable
var hash1 = Helpers.CreateStringHashtable(100);
var hash2 = Hashtable.Synchronized(hash1);
Assert.Equal(hash1.Count, hash2.Count);
Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly);
Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize);
Assert.True(hash2.IsSynchronized);
Assert.Equal(hash1.SyncRoot, hash2.SyncRoot);
for (int i = 0; i < hash2.Count; i++)
{
Assert.Equal("Value_" + i, hash2["Key_" + i]);
}
}
[Fact]
public static void Synchronized_NullTable_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("table", () => Hashtable.Synchronized(null)); // Table is null
}
[Fact]
public static void Values_ICollectionProperties()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values1 = hash2.Values;
Assert.False(values1.IsSynchronized);
Assert.Equal(hash2.SyncRoot, values1.SyncRoot);
Assert.Equal(hash2.Count, values1.Count);
hash2.Clear();
Assert.Equal(values1.Count, 0);
ICollection values2 = hash2.Values;
Assert.Same(values1, values2);
});
}
[Fact]
public static void Values_GetEnumerator()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values = hash2.Values;
IEnumerator enum1 = values.GetEnumerator();
IEnumerator enum2 = values.GetEnumerator();
Assert.NotSame(enum1, enum2);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enum1.MoveNext())
{
Assert.True(hash2.ContainsValue(enum1.Current));
counter++;
}
Assert.Equal(values.Count, counter);
enum1.Reset();
}
});
}
[Fact]
public static void Values_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection values = hash.Values;
// Removing a value from the hashtable should update the Values ICollection.
// This means that the Values ICollection no longer contains the value.
hash.Remove("Key_0");
IEnumerator enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Value_0", enumerator.Current);
}
}
[Fact]
public static void Values_CopyTo()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values = hash2.Values;
// Index = 0
object[] valuesCopy = new object[values.Count];
values.CopyTo(valuesCopy, 0);
Assert.Equal(values.Count, valuesCopy.Length);
for (int i = 0; i < valuesCopy.Length; i++)
{
Assert.True(hash2.ContainsValue(valuesCopy[i]));
}
// Index > 0
int index = 50;
valuesCopy = new object[values.Count + index];
values.CopyTo(valuesCopy, index);
Assert.Equal(values.Count + index, valuesCopy.Length);
for (int i = index; i < valuesCopy.Length; i++)
{
Assert.True(hash2.ContainsValue(valuesCopy[i]));
}
});
}
[Fact]
public static void Values_CopyTo_Invalid()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values = hash2.Values;
Assert.Throws<ArgumentNullException>("array", () => values.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>("array", () => values.CopyTo(new object[100, 100], 0)); // Array is multidimensional
Assert.Throws<ArgumentException>(null, () => values.CopyTo(new object[50], 0)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentException>(null, () => values.CopyTo(new object[100], 1)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentOutOfRangeException>("arrayIndex", () => values.CopyTo(new object[100], -1)); // Index < 0
});
}
private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc)
{
if (hash2 == null)
{
Assert.Equal(0, hash1.Count);
}
else
{
// Make sure that construtor imports all keys and values
Assert.Equal(hash2.Count, hash1.Count);
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
// Make sure the new and old hashtables are not linked
hash2.Clear();
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
Assert.Equal(ikc, hash1.EqualityComparer);
Assert.False(hash1.IsFixedSize);
Assert.False(hash1.IsReadOnly);
Assert.False(hash1.IsSynchronized);
// Make sure we can add to the hashtable
int count = hash1.Count;
for (int i = count; i < count + 100; i++)
{
hash1.Add(i, i);
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
private class ComparableHashtable : Hashtable
{
public ComparableHashtable() : base()
{
}
public ComparableHashtable(int capacity) : base(capacity)
{
}
public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor)
{
}
public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc)
{
}
public ComparableHashtable(IEqualityComparer ikc) : base(ikc)
{
}
public ComparableHashtable(IDictionary d) : base(d)
{
}
public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor)
{
}
public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc)
{
}
public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc)
{
}
public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc)
{
}
public new IEqualityComparer EqualityComparer
{
get { return base.EqualityComparer; }
}
}
private class BadHashCode
{
public BadHashCode(int value)
{
Value = value;
}
public int Value { get; private set; }
public override bool Equals(object o)
{
BadHashCode rhValue = o as BadHashCode;
if (rhValue != null)
{
return Value.Equals(rhValue.Value);
}
else
{
throw new ArgumentException("is not BadHashCode type actual " + o.GetType(), nameof(o));
}
}
public override int GetHashCode()
{
// Return 0 for everything to force hash collisions.
return 0;
}
public override string ToString() => Value.ToString();
}
private class Foo
{
public string StringValue { get; set; } = "Hello World";
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
return foo != null && StringValue == foo.StringValue;
}
public override int GetHashCode() => StringValue.GetHashCode();
}
}
/// <summary>
/// A hashtable can have a race condition:
/// A read operation on hashtable has three steps:
/// (1) calculate the hash and find the slot number.
/// (2) compare the hashcode, if equal, go to step 3. Otherwise end.
/// (3) compare the key, if equal, go to step 4. Otherwise end.
/// (4) return the value contained in the bucket.
/// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one
/// in the same bukcet. In order to make this happen easily, I created two long with same hashcode.
/// </summary>
public class Hashtable_ItemThreadSafetyTests
{
private object _key1;
private object _key2;
private object _value1 = "value1";
private object _value2 = "value2";
private Hashtable _hash;
private bool _errorOccurred = false;
private bool _timeExpired = false;
private const int MAX_TEST_TIME_MS = 10000; // 10 seconds
[Fact]
[OuterLoop]
public void GetItem_ThreadSafety()
{
int i1 = 0x10;
int i2 = 0x100;
// Setup key1 and key2 so they are different values but have the same hashcode
// To produce a hashcode long XOR's the first 32bits with the last 32 bits
long l1 = (((long)i1) << 32) + i2;
long l2 = (((long)i2) << 32) + i1;
_key1 = l1;
_key2 = l2;
_hash = new Hashtable(3); // Just one item will be in the hashtable at a time
int taskCount = 3;
var readers1 = new Task[taskCount];
var readers2 = new Task[taskCount];
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < readers1.Length; i++)
{
readers1[i] = Task.Run(new Action(ReaderFunction1));
}
for (int i = 0; i < readers2.Length; i++)
{
readers2[i] = Task.Run(new Action(ReaderFunction2));
}
Task writer = Task.Run(new Action(WriterFunction));
var spin = new SpinWait();
while (!_errorOccurred && !_timeExpired)
{
if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds)
{
_timeExpired = true;
}
spin.SpinOnce();
}
Task.WaitAll(readers1);
Task.WaitAll(readers2);
writer.Wait();
Assert.False(_errorOccurred);
}
private void ReaderFunction1()
{
while (!_timeExpired)
{
object value = _hash[_key1];
if (value != null)
{
Assert.NotEqual(value, _value2);
}
}
}
private void ReaderFunction2()
{
while (!_errorOccurred && !_timeExpired)
{
object value = _hash[_key2];
if (value != null)
{
Assert.NotEqual(value, _value1);
}
}
}
private void WriterFunction()
{
while (!_errorOccurred && !_timeExpired)
{
_hash.Add(_key1, _value1);
_hash.Remove(_key1);
_hash.Add(_key2, _value2);
_hash.Remove(_key2);
}
}
}
public class Hashtable_SynchronizedTests
{
private Hashtable _hash2;
private int _iNumberOfElements = 20;
[Fact]
[OuterLoop]
public void SynchronizedThreadSafety()
{
const int NumberOfWorkers = 3;
// Synchronized returns a hashtable that is thread safe
// We will try to test this by getting a number of threads to write some items
// to a synchronized IList
var hash1 = new Hashtable();
_hash2 = Hashtable.Synchronized(hash1);
var workers = new Task[NumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
var name = "Thread worker " + i;
var task = new Action(() => AddElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
// Check time
Assert.Equal(_hash2.Count, _iNumberOfElements * NumberOfWorkers);
for (int i = 0; i < NumberOfWorkers; i++)
{
for (int j = 0; j < _iNumberOfElements; j++)
{
string strValue = "Thread worker " + i + "_" + j;
Assert.True(_hash2.Contains(strValue));
}
}
// We cannot can make an assumption on the order of these items but
// now we are going to remove all of these
workers = new Task[NumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
string name = "Thread worker " + i;
var task = new Action(() => RemoveElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
Assert.Equal(_hash2.Count, 0);
}
private void AddElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Add(strName + "_" + i, "string_" + i);
}
}
private void RemoveElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Remove(strName + "_" + i);
}
}
}
public class Hashtable_SyncRootTests
{
private Hashtable _hashDaughter;
private Hashtable _hashGrandDaughter;
private const int NumberOfElements = 100;
[Fact]
public void SyncRoot()
{
// Different hashtables have different SyncRoots
var hash1 = new Hashtable();
var hash2 = new Hashtable();
Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot);
Assert.Equal(hash1.SyncRoot.GetType(), typeof(object));
// Cloned hashtables have different SyncRoots
hash1 = new Hashtable();
hash2 = Hashtable.Synchronized(hash1);
Hashtable hash3 = (Hashtable)hash2.Clone();
Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot);
Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot);
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenario we have in mind.
// 1) Create your Down to earth mother Hashtable
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var hashMother = new Hashtable();
for (int i = 0; i < NumberOfElements; i++)
{
hashMother.Add("Key_" + i, "Value_" + i);
}
Hashtable hashSon = Hashtable.Synchronized(hashMother);
_hashGrandDaughter = Hashtable.Synchronized(hashSon);
_hashDaughter = Hashtable.Synchronized(hashMother);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
// We are going to rumble with the Hashtables with some threads
int iNumberOfWorkers = 30;
var workers = new Task[iNumberOfWorkers];
var ts2 = new Action(RemoveElements);
for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
{
var name = "Thread_worker_" + iThreads;
var ts1 = new Action(() => AddMoreElements(name));
workers[iThreads] = Task.Run(ts1);
workers[iThreads + 1] = Task.Run(ts2);
}
Task.WaitAll(workers);
// Check:
// Either there should be some elements (the new ones we added and/or the original ones) or none
var hshPossibleValues = new Hashtable();
for (int i = 0; i < NumberOfElements; i++)
{
hshPossibleValues.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < iNumberOfWorkers; i++)
{
hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
IDictionaryEnumerator idic = hashMother.GetEnumerator();
while (idic.MoveNext())
{
Assert.True(hshPossibleValues.ContainsKey(idic.Key));
Assert.True(hshPossibleValues.ContainsValue(idic.Value));
}
}
private void AddMoreElements(string threadName)
{
_hashGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_hashDaughter.Clear();
}
}
}
| |
#region License
/*
* EndPointListener.cs
*
* This code is derived from EndPointListener.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
#region Contributors
/*
* Contributors:
* - Liryna <liryna.stark@gmail.com>
* - Nicholas Devenish
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace WebSocketSharp.Net
{
internal sealed class EndPointListener
{
#region Private Fields
private List<HttpListenerPrefix> _all; // host == '+'
private static readonly string _defaultCertFolderPath;
private IPEndPoint _endpoint;
private Dictionary<HttpListenerPrefix, HttpListener> _prefixes;
private bool _secure;
private Socket _socket;
private ServerSslConfiguration _sslConfig;
private List<HttpListenerPrefix> _unhandled; // host == '*'
private Dictionary<HttpConnection, HttpConnection> _unregistered;
private object _unregisteredSync;
#endregion
#region Static Constructor
static EndPointListener ()
{
_defaultCertFolderPath =
Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
}
#endregion
#region Internal Constructors
internal EndPointListener (
IPAddress address,
int port,
bool reuseAddress,
bool secure,
string certificateFolderPath,
ServerSslConfiguration sslConfig)
{
if (secure) {
var cert = getCertificate (port, certificateFolderPath, sslConfig.ServerCertificate);
if (cert == null)
throw new ArgumentException ("No server certificate could be found.");
_secure = secure;
_sslConfig = sslConfig;
_sslConfig.ServerCertificate = cert;
}
_prefixes = new Dictionary<HttpListenerPrefix, HttpListener> ();
_unregistered = new Dictionary<HttpConnection, HttpConnection> ();
_unregisteredSync = ((ICollection) _unregistered).SyncRoot;
_socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (reuseAddress)
_socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_endpoint = new IPEndPoint (address, port);
_socket.Bind (_endpoint);
_socket.Listen (500);
_socket.BeginAccept (onAccept, this);
}
#endregion
#region Public Properties
public IPAddress Address {
get {
return _endpoint.Address;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public int Port {
get {
return _endpoint.Port;
}
}
public ServerSslConfiguration SslConfiguration {
get {
return _sslConfig;
}
}
#endregion
#region Private Methods
private static void addSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
foreach (var pref in prefixes)
if (pref.Path == path)
throw new HttpListenerException (400, "The prefix is already in use."); // TODO: Code?
prefixes.Add (prefix);
}
private void checkIfRemove ()
{
if (_prefixes.Count > 0)
return;
var list = _unhandled;
if (list != null && list.Count > 0)
return;
list = _all;
if (list != null && list.Count > 0)
return;
EndPointManager.RemoveEndPoint (this);
}
private static RSACryptoServiceProvider createRSAFromFile (string filename)
{
byte[] pvk = null;
using (var fs = File.Open (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
pvk = new byte[fs.Length];
fs.Read (pvk, 0, pvk.Length);
}
var rsa = new RSACryptoServiceProvider ();
rsa.ImportCspBlob (pvk);
return rsa;
}
private static X509Certificate2 getCertificate (
int port, string certificateFolderPath, X509Certificate2 defaultCertificate)
{
if (certificateFolderPath == null || certificateFolderPath.Length == 0)
certificateFolderPath = _defaultCertFolderPath;
try {
var cer = Path.Combine (certificateFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certificateFolderPath, String.Format ("{0}.key", port));
if (File.Exists (cer) && File.Exists (key)) {
var cert = new X509Certificate2 (cer);
cert.PrivateKey = createRSAFromFile (key);
return cert;
}
}
catch {
}
return defaultCertificate;
}
private static HttpListener matchFromList (
string host, string path, List<HttpListenerPrefix> list, out HttpListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener bestMatch = null;
var bestLen = -1;
foreach (var pref in list) {
var ppath = pref.Path;
if (ppath.Length < bestLen)
continue;
if (path.StartsWith (ppath)) {
bestLen = ppath.Length;
bestMatch = pref.Listener;
prefix = pref;
}
}
return bestMatch;
}
private static void onAccept (IAsyncResult ar)
{
var lsnr = (EndPointListener) ar.AsyncState;
Socket sock = null;
try {
sock = lsnr._socket.EndAccept (ar);
lsnr._socket.BeginAccept (onAccept, lsnr);
}
catch {
if (sock != null)
sock.Close ();
return;
}
processAccepted (sock, lsnr);
}
private static void processAccepted (Socket socket, EndPointListener listener)
{
HttpConnection conn = null;
try {
conn = new HttpConnection (socket, listener);
lock (listener._unregisteredSync)
listener._unregistered[conn] = conn;
conn.BeginReadRequest ();
}
catch {
if (conn != null) {
conn.Close (true);
return;
}
socket.Close ();
}
}
private static bool removeSpecial (List<HttpListenerPrefix> prefixes, HttpListenerPrefix prefix)
{
var path = prefix.Path;
var cnt = prefixes.Count;
for (var i = 0; i < cnt; i++) {
if (prefixes[i].Path == path) {
prefixes.RemoveAt (i);
return true;
}
}
return false;
}
private HttpListener searchListener (Uri uri, out HttpListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
var host = uri.Host;
var dns = Uri.CheckHostName (host) == UriHostNameType.Dns;
var port = uri.Port;
var path = HttpUtility.UrlDecode (uri.AbsolutePath);
var pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener bestMatch = null;
var bestLen = -1;
if (host != null && host.Length > 0) {
foreach (var pref in _prefixes.Keys) {
var ppath = pref.Path;
if (ppath.Length < bestLen)
continue;
if (pref.Port != port)
continue;
if (dns) {
var phost = pref.Host;
if (Uri.CheckHostName (phost) == UriHostNameType.Dns && phost != host)
continue;
}
if (path.StartsWith (ppath) || pathSlash.StartsWith (ppath)) {
bestLen = ppath.Length;
bestMatch = _prefixes[pref];
prefix = pref;
}
}
if (bestLen != -1)
return bestMatch;
}
var list = _unhandled;
bestMatch = matchFromList (host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = matchFromList (host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
list = _all;
bestMatch = matchFromList (host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = matchFromList (host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
return null;
}
#endregion
#region Internal Methods
internal static bool CertificateExists (int port, string certificateFolderPath)
{
if (certificateFolderPath == null || certificateFolderPath.Length == 0)
certificateFolderPath = _defaultCertFolderPath;
var cer = Path.Combine (certificateFolderPath, String.Format ("{0}.cer", port));
var key = Path.Combine (certificateFolderPath, String.Format ("{0}.key", port));
return File.Exists (cer) && File.Exists (key);
}
internal void RemoveConnection (HttpConnection connection)
{
lock (_unregisteredSync)
_unregistered.Remove (connection);
}
#endregion
#region Public Methods
public void AddPrefix (HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
return;
}
if (prefix.Host == "+") {
do {
current = _all;
future = current != null
? new List<HttpListenerPrefix> (current)
: new List<HttpListenerPrefix> ();
prefix.Listener = listener;
addSpecial (future, prefix);
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (prefs.ContainsKey (prefix)) {
if (prefs[prefix] != listener)
throw new HttpListenerException (
400, String.Format ("There's another listener for {0}.", prefix)); // TODO: Code?
return;
}
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2[prefix] = listener;
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
}
public bool BindContext (HttpListenerContext context)
{
HttpListenerPrefix pref;
var lsnr = searchListener (context.Request.Url, out pref);
if (lsnr == null)
return false;
context.Listener = lsnr;
context.Connection.Prefix = pref;
return true;
}
public void Close ()
{
_socket.Close ();
lock (_unregisteredSync) {
var conns = new List<HttpConnection> (_unregistered.Keys);
_unregistered.Clear ();
foreach (var conn in conns)
conn.Close (true);
conns.Clear ();
}
}
public void RemovePrefix (HttpListenerPrefix prefix, HttpListener listener)
{
List<HttpListenerPrefix> current, future;
if (prefix.Host == "*") {
do {
current = _unhandled;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break; // The prefix wasn't found.
}
while (Interlocked.CompareExchange (ref _unhandled, future, current) != current);
checkIfRemove ();
return;
}
if (prefix.Host == "+") {
do {
current = _all;
if (current == null)
break;
future = new List<HttpListenerPrefix> (current);
if (!removeSpecial (future, prefix))
break; // The prefix wasn't found.
}
while (Interlocked.CompareExchange (ref _all, future, current) != current);
checkIfRemove ();
return;
}
Dictionary<HttpListenerPrefix, HttpListener> prefs, prefs2;
do {
prefs = _prefixes;
if (!prefs.ContainsKey (prefix))
break;
prefs2 = new Dictionary<HttpListenerPrefix, HttpListener> (prefs);
prefs2.Remove (prefix);
}
while (Interlocked.CompareExchange (ref _prefixes, prefs2, prefs) != prefs);
checkIfRemove ();
}
public void UnbindContext (HttpListenerContext context)
{
if (context == null || context.Listener == null)
return;
context.Listener.UnregisterContext (context);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using System.Linq;
using Android.Content;
using Android.Util;
using Android.Widget;
using Java.Lang;
namespace MonoDroid.TimesSquare
{
public class CalendarPickerView : ListView
{
public enum SelectionMode
{
Single,
Multi,
Range
};
private readonly Context _context;
internal readonly MonthAdapter MyAdapter;
internal readonly List<MonthDescriptor> Months = new List<MonthDescriptor>();
internal readonly List<List<List<MonthCellDescriptor>>> Cells =
new List<List<List<MonthCellDescriptor>>>();
internal List<MonthCellDescriptor> SelectedCells = new List<MonthCellDescriptor>();
private readonly List<MonthCellDescriptor> _highlightedCells = new List<MonthCellDescriptor>();
internal List<DateTime> SelectedCals = new List<DateTime>();
private readonly List<DateTime> _highlightedCals = new List<DateTime>();
internal readonly DateTime Today = DateTime.Now;
internal DateTime MinDate;
internal DateTime MaxDate;
private DateTime _monthCounter;
internal int DividerColor;
internal int DayBackgroundResID;
internal int DayTextColorResID;
internal int TitleTextColor;
internal int HeaderTextColor;
internal readonly string MonthNameFormat;
internal readonly string WeekdayNameFormat;
internal readonly string FullDateFormat;
internal ClickHandler ClickHandler;
public event EventHandler<DateSelectedEventArgs> OnInvalidDateSelected;
public event EventHandler<DateSelectedEventArgs> OnDateSelected;
public event EventHandler<DateSelectedEventArgs> OnDateUnselected;
public event DateSelectableHandler OnDateSelectable;
public SelectionMode Mode { get; set; }
public DateTime SelectedDate
{
get { return SelectedCals.Count > 0 ? SelectedCals[0] : DateTime.MinValue; }
}
public List<DateTime> SelectedDates
{
get
{
var selectedDates = SelectedCells.Select(cal => cal.DateTime).ToList();
selectedDates.Sort();
return selectedDates;
}
}
public CalendarPickerView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
ResourceIdManager.UpdateIdValues();
var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CalendarPickerView);
var bg = a.GetColor(Resource.Styleable.CalendarPickerView_android_background,
Resource.Color.calendar_bg);
DividerColor = a.GetColor(Resource.Styleable.CalendarPickerView_dividerColor,
Resource.Color.calendar_divider);
DayBackgroundResID = a.GetResourceId(Resource.Styleable.CalendarPickerView_dayBackground,
Resource.Drawable.calendar_bg_selector);
DayTextColorResID = a.GetResourceId(Resource.Styleable.CalendarPickerView_dayTextColor,
Resource.Color.calendar_text_selector);
TitleTextColor = a.GetColor(Resource.Styleable.CalendarPickerView_titleTextColor,
Resource.Color.calendar_text_active);
HeaderTextColor = a.GetColor(Resource.Styleable.CalendarPickerView_headerTextColor,
Resource.Color.calendar_text_active);
a.Recycle();
_context = context;
MyAdapter = new MonthAdapter(context, this);
base.Adapter = MyAdapter;
base.Divider = null;
base.DividerHeight = 0;
base.SetBackgroundColor(bg);
base.CacheColorHint = bg;
MonthNameFormat = base.Resources.GetString(Resource.String.month_name_format);
WeekdayNameFormat = base.Resources.GetString(Resource.String.day_name_format);
FullDateFormat = CultureInfo.CurrentCulture.DateTimeFormat.LongDatePattern;
ClickHandler += OnCellClicked;
OnInvalidDateSelected += OnInvalidateDateClicked;
if (base.IsInEditMode) {
Init(DateTime.Now, DateTime.Now.AddYears(1)).WithSelectedDate(DateTime.Now);
}
}
private void OnCellClicked(MonthCellDescriptor cell)
{
var clickedDate = cell.DateTime;
if (!IsBetweenDates(clickedDate, MinDate, MaxDate) || !IsSelectable(clickedDate)) {
if (OnInvalidDateSelected != null) {
OnInvalidDateSelected(this, new DateSelectedEventArgs(clickedDate));
}
}
else {
bool wasSelected = DoSelectDate(clickedDate, cell);
if (OnDateSelected != null) {
if (wasSelected) {
OnDateSelected(this, new DateSelectedEventArgs(clickedDate));
}
else if (OnDateUnselected != null) {
OnDateUnselected(this, new DateSelectedEventArgs(clickedDate));
}
}
}
}
private void OnInvalidateDateClicked(object sender, DateSelectedEventArgs e)
{
string fullDateFormat = _context.Resources.GetString(Resource.String.full_date_format);
string errorMsg = _context.Resources.GetString(Resource.String.invalid_date);
errorMsg = string.Format(errorMsg, MinDate.ToString(fullDateFormat),
MaxDate.ToString(fullDateFormat));
Toast.MakeText(_context, errorMsg, ToastLength.Short).Show();
}
public FluentInitializer Init(DateTime minDate, DateTime maxDate)
{
if (minDate == DateTime.MinValue || maxDate == DateTime.MinValue) {
throw new IllegalArgumentException("minDate and maxDate must be non-zero. " +
Debug(minDate, maxDate));
}
if (minDate.CompareTo(maxDate) > 0) {
throw new IllegalArgumentException("minDate must be before maxDate. " +
Debug(minDate, maxDate));
}
Mode = SelectionMode.Single;
//Clear out any previously selected dates/cells.
SelectedCals.Clear();
SelectedCells.Clear();
_highlightedCals.Clear();
_highlightedCells.Clear();
//Clear previous state.
Cells.Clear();
Months.Clear();
MinDate = minDate;
MaxDate = maxDate;
MinDate = SetMidnight(MinDate);
MaxDate = SetMidnight(MaxDate);
// maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month,
// We don't accidentally include that month in the view.
MaxDate = MaxDate.AddMinutes(-1);
//Now iterate between minCal and maxCal and build up our list of months to show.
_monthCounter = MinDate;
int maxMonth = MaxDate.Month;
int maxYear = MaxDate.Year;
while ((_monthCounter.Month <= maxMonth
|| _monthCounter.Year < maxYear)
&& _monthCounter.Year < maxYear + 1) {
var month = new MonthDescriptor(_monthCounter.Month, _monthCounter.Year, _monthCounter,
_monthCounter.ToString(MonthNameFormat));
Cells.Add(GetMonthCells(month, _monthCounter));
Logr.D("Adding month {0}", month);
Months.Add(month);
_monthCounter = _monthCounter.AddMonths(1);
}
ValidateAndUpdate();
return new FluentInitializer(this);
}
internal List<List<MonthCellDescriptor>> GetMonthCells(MonthDescriptor month, DateTime startCal)
{
var cells = new List<List<MonthCellDescriptor>>();
var cal = new DateTime(startCal.Year, startCal.Month, 1);
var firstDayOfWeek = (int) cal.DayOfWeek;
cal = cal.AddDays((int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - firstDayOfWeek);
var minSelectedCal = GetMinDate(SelectedCals);
var maxSelectedCal = GetMaxDate(SelectedCals);
while ((cal.Month < month.Month + 1 || cal.Year < month.Year)
&& cal.Year <= month.Year) {
Logr.D("Building week row starting at {0}", cal);
var weekCells = new List<MonthCellDescriptor>();
cells.Add(weekCells);
for (int i = 0; i < 7; i++) {
var date = cal;
bool isCurrentMonth = cal.Month == month.Month;
bool isSelected = isCurrentMonth && ContatinsDate(SelectedCals, cal);
bool isSelectable = isCurrentMonth && IsBetweenDates(cal, MinDate, MaxDate);
bool isToday = IsSameDate(cal, Today);
bool isHighlighted = ContatinsDate(_highlightedCals, cal);
int value = cal.Day;
var rangeState = RangeState.None;
if (SelectedCals.Count > 1) {
if (IsSameDate(minSelectedCal, cal)) {
rangeState = RangeState.First;
}
else if (IsSameDate(maxSelectedCal, cal)) {
rangeState = RangeState.Last;
}
else if (IsBetweenDates(cal, minSelectedCal, maxSelectedCal)) {
rangeState = RangeState.Middle;
}
}
weekCells.Add(new MonthCellDescriptor(date, isCurrentMonth, isSelectable, isSelected,
isToday, isHighlighted, value, rangeState));
cal = cal.AddDays(1);
}
}
return cells;
}
internal void ScrollToSelectedMonth(int selectedIndex)
{
ScrollToSelectedMonth(selectedIndex, false);
}
internal void ScrollToSelectedMonth(int selectedIndex, bool smoothScroll)
{
Task.Factory.StartNew(() =>
{
if (smoothScroll) {
SmoothScrollToPosition(selectedIndex);
}
else {
SetSelection(selectedIndex);
}
});
}
private MonthCellWithMonthIndex GetMonthCellWithIndexByDate(DateTime date)
{
int index = 0;
foreach (var monthCell in Cells) {
foreach (var actCell in from weekCell in monthCell
from actCell in weekCell
where IsSameDate(actCell.DateTime, date) && actCell.IsSelectable
select actCell)
return new MonthCellWithMonthIndex(actCell, index);
index++;
}
return null;
}
protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
if (Months.Count == 0) {
throw new InvalidOperationException(
"Must have at least one month to display. Did you forget to call Init()?");
}
base.OnMeasure(widthMeasureSpec, heightMeasureSpec);
}
private static DateTime SetMidnight(DateTime date)
{
return date.Subtract(date.TimeOfDay);
}
private bool IsSelectable(DateTime date)
{
return OnDateSelectable == null || OnDateSelectable(date);
}
private DateTime ApplyMultiSelect(DateTime date, DateTime selectedCal)
{
foreach (var selectedCell in SelectedCells) {
if (selectedCell.DateTime == date) {
//De-select the currently selected cell.
selectedCell.IsSelected = false;
SelectedCells.Remove(selectedCell);
date = DateTime.MinValue;
break;
}
}
foreach (var cal in SelectedCals) {
if (IsSameDate(cal, selectedCal)) {
SelectedCals.Remove(cal);
break;
}
}
return date;
}
private void ClearOldSelection()
{
foreach (var selectedCell in SelectedCells) {
//De-select the currently selected cell.
selectedCell.IsSelected = false;
}
SelectedCells.Clear();
SelectedCals.Clear();
}
internal bool DoSelectDate(DateTime date, MonthCellDescriptor cell)
{
var newlySelectedDate = date;
SetMidnight(newlySelectedDate);
//Clear any remaining range state.
foreach (var selectedCell in SelectedCells) {
selectedCell.RangeState = RangeState.None;
}
switch (Mode) {
case SelectionMode.Range:
if (SelectedCals.Count > 1) {
//We've already got a range selected: clear the old one.
ClearOldSelection();
}
else if (SelectedCals.Count == 1 && newlySelectedDate.CompareTo(SelectedCals[0]) < 0) {
//We're moving the start of the range back in time: clear the old start date.
ClearOldSelection();
}
break;
case SelectionMode.Multi:
date = ApplyMultiSelect(date, newlySelectedDate);
break;
case SelectionMode.Single:
ClearOldSelection();
break;
default:
throw new IllegalStateException("Unknown SelectionMode " + Mode);
}
if (date > DateTime.MinValue) {
if (SelectedCells.Count == 0 || !SelectedCells[0].Equals(cell)) {
SelectedCells.Add(cell);
cell.IsSelected = true;
}
SelectedCals.Add(newlySelectedDate);
if (Mode == SelectionMode.Range && SelectedCells.Count > 1) {
//Select all days in between start and end.
var startDate = SelectedCells[0].DateTime;
var endDate = SelectedCells[1].DateTime;
SelectedCells[0].RangeState = RangeState.First;
SelectedCells[1].RangeState = RangeState.Last;
foreach (var month in Cells) {
foreach (var week in month) {
foreach (var singleCell in week) {
var singleCellDate = singleCell.DateTime;
if (singleCellDate.CompareTo(startDate) >= 0
&& singleCellDate.CompareTo(endDate) <= 0
&& singleCell.IsSelectable) {
singleCell.IsSelected = true;
singleCell.RangeState = RangeState.Middle;
SelectedCells.Add(singleCell);
}
}
}
}
}
}
ValidateAndUpdate();
return date > DateTime.MinValue;
}
internal void ValidateAndUpdate()
{
if (Adapter == null) {
Adapter = MyAdapter;
}
MyAdapter.NotifyDataSetChanged();
}
internal bool SelectDate(DateTime date)
{
return SelectDate(date, false);
}
private bool SelectDate(DateTime date, bool smoothScroll)
{
ValidateDate(date);
var cell = GetMonthCellWithIndexByDate(date);
if (cell == null || !IsSelectable(date)) {
return false;
}
bool wasSelected = DoSelectDate(date, cell.Cell);
if (wasSelected) {
ScrollToSelectedMonth(cell.MonthIndex, smoothScroll);
}
return wasSelected;
}
private void ValidateDate(DateTime date)
{
if (date == DateTime.MinValue) {
throw new IllegalArgumentException("Selected date must be non-zero.");
}
if (date.CompareTo(MinDate) < 0 || date.CompareTo(MaxDate) > 0) {
throw new IllegalArgumentException(
string.Format("Selected date must be between minDate and maxDate. "
+ "minDate: {0}, maxDate: {1}, selectedDate: {2}.",
MinDate.ToShortDateString(), MaxDate.ToShortDateString(), date.ToShortDateString()));
}
}
private static DateTime GetMinDate(List<DateTime> selectedCals)
{
if (selectedCals == null || selectedCals.Count == 0) {
return DateTime.MinValue;
}
selectedCals.Sort();
return selectedCals[0];
}
private static DateTime GetMaxDate(List<DateTime> selectedCals)
{
if (selectedCals == null || selectedCals.Count == 0) {
return DateTime.MinValue;
}
selectedCals.Sort();
return selectedCals[selectedCals.Count - 1];
}
private static bool IsBetweenDates(DateTime date, DateTime minCal, DateTime maxCal)
{
return (date.Equals(minCal) || date.CompareTo(minCal) > 0) // >= minCal
&& date.CompareTo(maxCal) < 0; // && < maxCal
}
private static bool IsSameDate(DateTime cal, DateTime selectedDate)
{
return cal.Month == selectedDate.Month
&& cal.Year == selectedDate.Year
&& cal.Day == selectedDate.Day;
}
internal static bool IsSameMonth(DateTime cal, MonthDescriptor month)
{
return (cal.Month == month.Month && cal.Year == month.Year);
}
private static bool ContatinsDate(IEnumerable<DateTime> selectedCals, DateTime cal)
{
return selectedCals.Any(selectedCal => IsSameDate(cal, selectedCal));
}
public void HighlightDates(ICollection<DateTime> dates)
{
foreach (var date in dates) {
ValidateDate(date);
var monthCellWithMonthIndex = GetMonthCellWithIndexByDate(date);
if (monthCellWithMonthIndex != null) {
var cell = monthCellWithMonthIndex.Cell;
_highlightedCells.Add(cell);
_highlightedCals.Add(date);
cell.IsHighlighted = true;
}
}
MyAdapter.NotifyDataSetChanged();
Adapter = MyAdapter;
}
private static string Debug(DateTime minDate, DateTime maxDate)
{
return "minDate: " + minDate + "\nmaxDate: " + maxDate;
}
private class MonthCellWithMonthIndex
{
public readonly MonthCellDescriptor Cell;
public readonly int MonthIndex;
public MonthCellWithMonthIndex(MonthCellDescriptor cell, int monthIndex)
{
Cell = cell;
MonthIndex = monthIndex;
}
}
}
public class FluentInitializer
{
private readonly CalendarPickerView _calendar;
public FluentInitializer(CalendarPickerView calendar)
{
_calendar = calendar;
}
public FluentInitializer InMode(CalendarPickerView.SelectionMode mode)
{
_calendar.Mode = mode;
_calendar.ValidateAndUpdate();
return this;
}
public FluentInitializer WithSelectedDate(DateTime selectedDate)
{
return WithSelectedDates(new List<DateTime> {selectedDate});
}
public FluentInitializer WithSelectedDates(ICollection<DateTime> selectedDates)
{
if (_calendar.Mode == CalendarPickerView.SelectionMode.Single && _calendar.SelectedDates.Count > 1) {
throw new IllegalArgumentException("SINGLE mode can't be used with multiple selectedDates");
}
if (_calendar.SelectedDates != null) {
foreach (var date in selectedDates) {
_calendar.SelectDate(date);
}
}
int selectedIndex = -1;
int todayIndex = -1;
for (int i = 0; i < _calendar.Months.Count; i++) {
var month = _calendar.Months[i];
if (selectedIndex == -1) {
if (_calendar.SelectedCals.Any(
selectedCal => CalendarPickerView.IsSameMonth(selectedCal, month))) {
selectedIndex = i;
}
if (selectedIndex == -1 && todayIndex == -1 &&
CalendarPickerView.IsSameMonth(DateTime.Now, month)) {
todayIndex = i;
}
}
}
if (selectedIndex != -1) {
_calendar.ScrollToSelectedMonth(selectedIndex);
}
else if (todayIndex != -1) {
_calendar.ScrollToSelectedMonth(todayIndex);
}
_calendar.ValidateAndUpdate();
return this;
}
public FluentInitializer WithLocale(Java.Util.Locale locale)
{
//Not sure how to translate this to C# flavor.
//Leave it later.
throw new NotImplementedException();
}
public FluentInitializer WithHighlightedDates(ICollection<DateTime> dates)
{
_calendar.HighlightDates(dates);
return this;
}
public FluentInitializer WithHighlightedDate(DateTime date)
{
return WithHighlightedDates(new List<DateTime> {date});
}
}
public delegate void ClickHandler(MonthCellDescriptor cell);
public delegate bool DateSelectableHandler(DateTime date);
public class DateSelectedEventArgs : EventArgs
{
public DateSelectedEventArgs(DateTime date)
{
SelectedDate = date;
}
public DateTime SelectedDate { get; private set; }
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* 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.
*/
/* Created by Alex Maitland, maitlandalex@gmail.com */
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Google.GData.Analytics;
using Google.GData.Client;
using Google.GData.Client.LiveTests;
using Google.GData.Client.UnitTests;
using Google.Analytics;
using NUnit.Framework;
namespace Google.GData.Client.UnitTests.Analytics
{
[TestFixture, Category("Analytics")]
public class AnalyticsDataServiceTest : BaseLiveTestClass
{
private const string DataFeedUrl = "http://www.google.com/analytics/feeds/data";
private const string AccountFeedUrl = "http://www.google.com/analytics/feeds/accounts/default";
private string accountId;
private TestContext TestContext1;
protected override void ReadConfigFile()
{
base.ReadConfigFile();
if (unitTestConfiguration.Contains("analyticsUserName") == true)
{
this.userName = (string)unitTestConfiguration["analyticsUserName"];
Tracing.TraceInfo("Read userName value: " + this.userName);
}
if (unitTestConfiguration.Contains("analyticsPassWord") == true)
{
this.passWord = (string)unitTestConfiguration["analyticsPassWord"];
Tracing.TraceInfo("Read passWord value: " + this.passWord);
}
if (unitTestConfiguration.Contains("accountId") == true)
{
this.accountId = (string)unitTestConfiguration["accountId"];
Tracing.TraceInfo("Read accountId value: " + this.accountId);
}
}
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get { return TestContext1; }
set { TestContext1 = value; }
}
[Test]
public void QueryAccountIds()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
AccountQuery feedQuery = new AccountQuery(AccountFeedUrl);
AccountFeed actual = service.Query(feedQuery);
foreach (AccountEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
Assert.IsNotNull(entry.ProfileId.Value);
if (this.accountId == null)
this.accountId = entry.ProfileId.Value;
}
}
[Test]
public void QueryBrowserMetrics()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:pageviews";
query.Dimensions = "ga:browser";
query.Sort = "ga:browser,ga:pageviews";
query.GAStartDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
query.GAEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
XmlTextWriter writer = new XmlTextWriter("QueryBrowserMetricsOutput.xml", Encoding.UTF8);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
actual.SaveToXml(writer);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryProductCategoryResultForPeriod()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Dimensions = "ga:productCategory,ga:productName";
query.Metrics = "ga:itemRevenue,ga:itemQuantity";
query.Sort = "ga:productCategory";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual);
Assert.IsNotNull(actual.Entries);
foreach(DataEntry entry in actual.Entries)
{
Assert.AreEqual(2, entry.Dimensions.Count);
Assert.IsNotNull(entry.Dimensions[0]);
Assert.IsNotNull(entry.Dimensions[0].Name);
Assert.IsNotNull(entry.Dimensions[0].Value);
Assert.IsNotNull(entry.Dimensions[1]);
Assert.IsNotNull(entry.Dimensions[1].Name);
Assert.IsNotNull(entry.Dimensions[1].Value);
Assert.AreEqual(2, entry.Metrics.Count);
Assert.IsNotNull(entry.Metrics[0]);
Assert.IsNotNull(entry.Metrics[0].Name);
Assert.IsNotNull(entry.Metrics[0].Value);
Assert.IsNotNull(entry.Metrics[1]);
Assert.IsNotNull(entry.Metrics[1].Name);
Assert.IsNotNull(entry.Metrics[1].Value);
}
}
[Test]
public void QueryVisitorsResultForPeriod()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:visitors";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
query.StartIndex = 1;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
}
[Test]
public void QuerySiteStatsResultForPeriod()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:pageviews,ga:visits,ga:newVisits,ga:transactions,ga:uniquePageviews";
query.GAStartDate = new DateTime(2009, 04, 19).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 25).ToString("yyyy-MM-dd");
query.StartIndex = 1;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(5, actual.Aggregates.Metrics.Count);
}
[Test]
public void QueryTransactionIdReturnAllResults()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
int currentIndex = 1;
const int resultsPerPage = 1000;
List<DataFeed> querys = new List<DataFeed>();
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Dimensions = "ga:transactionId,ga:date";
query.Metrics = "ga:transactionRevenue";
query.Sort = "ga:date";
query.GAStartDate = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
query.NumberToRetrieve = resultsPerPage;
query.StartIndex = currentIndex;
DataFeed actual = service.Query(query);
querys.Add(actual);
double totalPages = Math.Round(((double)actual.TotalResults / (double)resultsPerPage) + 0.5);
for (int i = 1; i < totalPages; i++)
{
currentIndex += resultsPerPage;
query.StartIndex = currentIndex;
actual = service.Query(query);
querys.Add(actual);
}
for (int i = 0; i < querys.Count; i++)
{
foreach (DataEntry entry in querys[i].Entries)
{
Assert.IsNotNull(entry.Id);
}
}
}
[Test]
public void QueryTransactionIdReturn200Results()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Dimensions = "ga:transactionId,ga:date";
query.Metrics = "ga:transactionRevenue";
query.Sort = "ga:date";
query.GAStartDate = new DateTime(2009, 04, 01).ToString("yyyy-MM-dd");
query.GAEndDate = new DateTime(2009, 04, 30).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
Assert.AreEqual(200, actual.ItemsPerPage);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void QueryPageViews()
{
AnalyticsService service = new AnalyticsService(this.ApplicationName);
service.Credentials = new GDataCredentials(this.userName, this.passWord);
DataQuery query = new DataQuery(DataFeedUrl);
query.Ids = this.accountId;
query.Metrics = "ga:pageviews";
query.Dimensions = "ga:pageTitle";
query.Sort = "-ga:pageviews";
query.GAStartDate = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
query.GAEndDate = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd");
query.NumberToRetrieve = 200;
DataFeed actual = service.Query(query);
Assert.IsNotNull(actual.Aggregates);
Assert.AreEqual(1, actual.Aggregates.Metrics.Count);
foreach (DataEntry entry in actual.Entries)
{
Assert.IsNotNull(entry.Id);
}
}
[Test]
public void TestAnalyticsModel()
{
RequestSettings settings = new RequestSettings("Unittests", this.userName, this.passWord);
AnalyticsRequest request = new AnalyticsRequest(settings);
Feed<Account> accounts = request.GetAccounts();
foreach (Account a in accounts.Entries)
{
Assert.IsNotNull(a.AccountId);
Assert.IsNotNull(a.ProfileId);
Assert.IsNotNull(a.WebPropertyId);
if (this.accountId == null)
this.accountId = a.TableId;
}
DataQuery q = new DataQuery(this.accountId, DateTime.Now.AddDays(-14), DateTime.Now.AddDays(-2), "ga:pageviews", "ga:pageTitle", "ga:pageviews");
Dataset set = request.Get(q);
foreach (Data d in set.Entries)
{
Assert.IsNotNull(d.Id);
Assert.IsNotNull(d.Metrics);
Assert.IsNotNull(d.Dimensions);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.MachineLearning.WebServices
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// These APIs allow end users to operate on Azure Machine Learning Web
/// Services resources. They support the following
/// operations:<ul><li>Create or update a web
/// service</li><li>Get a web
/// service</li><li>Patch a web
/// service</li><li>Delete a web
/// service</li><li>Get All Web Services in a Resource Group
/// </li><li>Get All Web Services in a
/// Subscription</li><li>Get Web Services
/// Keys</li></ul>
/// </summary>
public partial class AzureMLWebServicesManagementClient : Microsoft.Rest.ServiceClient<AzureMLWebServicesManagementClient>, IAzureMLWebServicesManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// The Azure subscription ID.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// The version of the Microsoft.MachineLearning resource provider API to use.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IWebServicesOperations.
/// </summary>
public virtual IWebServicesOperations WebServices { get; private set; }
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AzureMLWebServicesManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AzureMLWebServicesManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AzureMLWebServicesManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AzureMLWebServicesManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AzureMLWebServicesManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AzureMLWebServicesManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AzureMLWebServicesManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AzureMLWebServicesManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AzureMLWebServicesManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.WebServices = new WebServicesOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.ApiVersion = "2016-05-01-preview";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicSerializeJsonConverter<WebServiceProperties>("packageType"));
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.PolymorphicDeserializeJsonConverter<WebServiceProperties>("packageType"));
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
}
}
| |
using System;
using NDatabase;
using NDatabase.Api;
using NDatabase.Btree;
using NDatabase.Core.BTree;
using NDatabase.Tool.Wrappers;
using NUnit.Framework;
namespace Test.NDatabase.Odb.Test.Btree.Odb
{
[TestFixture]
public class TestODBLazyBTree : ODBTest
{
private const int Size = 200;
private IBTreePersister GetPersister(string baseName)
{
var odb = Open(baseName);
return new LazyOdbBtreePersister(((global::NDatabase.Odb)odb).GetStorageEngine());
}
public static void Main2(string[] args)
{
var t = new TestODBLazyBTree();
for (var i = 0; i < 1000; i++)
{
try
{
t.Test1a();
}
catch (Exception)
{
Console.Out.WriteLine("ERROR On loop " + i);
throw;
}
}
}
[Test]
public virtual void Test01()
{
var baseName = GetBaseName();
DeleteBase(baseName);
var persister = GetPersister(baseName);
IBTree tree = new OdbBtreeMultiple(2, persister);
var start = OdbTime.GetCurrentTimeInMs();
for (var i = 0; i < Size; i++)
tree.Insert(i + 1, "value " + (i + 1));
var end = OdbTime.GetCurrentTimeInMs();
Println("time/object=" + (end - start) / (float) Size);
AssertTrue((end - start) < 3000);
AssertEquals(Size, tree.GetSize());
var iterator = tree.Iterator<object>(OrderByConstants.OrderByAsc);
var j = 0;
while (iterator.MoveNext())
{
var o = iterator.Current;
AssertEquals("value " + (j + 1), o);
j++;
if (j % 10 == 0)
Println(j);
}
persister.Close();
DeleteBase(baseName);
}
[Test]
public virtual void Test1()
{
var baseName = GetBaseName();
var persister = GetPersister(baseName);
IBTree tree = new OdbBtreeMultiple(2, persister);
var start = OdbTime.GetCurrentTimeInMs();
for (var i = 0; i < Size; i++)
tree.Insert(i + 1, "value " + (i + 1));
var end = OdbTime.GetCurrentTimeInMs();
Println(end - start);
if (testPerformance)
AssertTrue((end - start) < 0.34 * Size);
// println("insert of "+SIZE+" elements in BTREE = " +
// (end-start)+"ms");
// persister.close();
// persister = getPersister();
AssertEquals(Size, tree.GetSize());
var iterator = tree.Iterator<object>(OrderByConstants.OrderByAsc);
var j = 0;
while (iterator.MoveNext())
{
var o = iterator.Current;
AssertEquals("value " + (j + 1), o);
j++;
if (j % 10 == 0)
Println(j);
}
persister.Close();
DeleteBase(baseName);
}
[Test]
public virtual void Test1a()
{
var baseName = GetBaseName();
var persister = GetPersister(baseName);
IBTree tree = new OdbBtreeMultiple(2, persister);
for (var i = 0; i < Size; i++)
tree.Insert(i + 1, "value " + (i + 1));
// println(new BTreeDisplay().build(tree,true).toString());
persister.Close();
persister = GetPersister(baseName);
tree = persister.LoadBTree(tree.GetId());
// println(new BTreeDisplay().build(tree,true).toString());
AssertEquals(Size, tree.GetSize());
var iterator = tree.Iterator<object>(OrderByConstants.OrderByAsc);
var j = 0;
while (iterator.MoveNext())
{
var o = iterator.Current;
AssertEquals("value " + (j + 1), o);
j++;
if (j == Size)
AssertEquals("value " + Size, o);
}
persister.Close();
DeleteBase(baseName);
}
[Test]
public virtual void Test2()
{
var baseName = GetBaseName();
var persister = GetPersister(baseName);
IBTree tree = new OdbBtreeMultiple(2, persister);
for (var i = 0; i < Size; i++)
tree.Insert(i + 1, "value " + (i + 1));
AssertEquals(Size, tree.GetSize());
var iterator = tree.Iterator<object>(OrderByConstants.OrderByDesc);
var j = 0;
while (iterator.MoveNext())
{
var o = iterator.Current;
// println(o);
j++;
if (j == Size)
AssertEquals("value " + 1, o);
}
persister.Close();
DeleteBase(baseName);
}
[Test]
public virtual void Test2a()
{
var baseName = GetBaseName();
// LogUtil.allOn(true);
DeleteBase(baseName);
var persister = GetPersister(baseName);
IBTreeMultipleValuesPerKey tree = new OdbBtreeMultiple(20, persister);
var start0 = OdbTime.GetCurrentTimeInMs();
for (var i = 0; i < Size; i++)
tree.Insert(i + 1, "value " + (i + 1));
// println("Commiting");
persister.Close();
var end0 = OdbTime.GetCurrentTimeInMs();
// println("insert of "+SIZE+" elements in BTREE = " +
// (end0-start0)+"ms");
// println("end Commiting");
persister = GetPersister(baseName);
// println("reloading btree");
tree = (IBTreeMultipleValuesPerKey) persister.LoadBTree(tree.GetId());
// println("end reloading btree , size="+tree.size());
AssertEquals(Size, tree.GetSize());
long totalSearchTime = 0;
long oneSearchTime = 0;
long minSearchTime = 10000;
long maxSearchTime = -1;
for (var i = 0; i < Size; i++)
{
var start = OdbTime.GetCurrentTimeInMs();
var o = tree.Search(i + 1);
var end = OdbTime.GetCurrentTimeInMs();
AssertEquals("value " + (i + 1), o[0]);
oneSearchTime = (end - start);
// println("Search time for "+o+" = "+oneSearchTime);
if (oneSearchTime > maxSearchTime)
maxSearchTime = oneSearchTime;
if (oneSearchTime < minSearchTime)
minSearchTime = oneSearchTime;
totalSearchTime += oneSearchTime;
}
persister.Close();
// println("total search time="+totalSearchTime +
// " - mean st="+((double)totalSearchTime/SIZE));
// println("min search time="+minSearchTime + " - max="+maxSearchTime);
// Median search time must be smaller than 1ms
DeleteBase(baseName);
AssertTrue(totalSearchTime < 1 * Size);
}
[Test]
public virtual void TestLazyCache()
{
var baseName = GetBaseName();
var persister = GetPersister(baseName);
IBTree tree = new OdbBtreeMultiple(2, persister);
var start = OdbTime.GetCurrentTimeInMs();
for (var i = 0; i < Size; i++)
tree.Insert(i + 1, "value " + (i + 1));
var end = OdbTime.GetCurrentTimeInMs();
if (testPerformance)
AssertTrue((end - start) < 0.34 * Size);
// println("insert of "+SIZE+" elements in BTREE = " +
// (end-start)+"ms");
// persister.close();
// persister = getPersister();
// /assertEquals(SIZE,tree.size());
var iterator = tree.Iterator<object>(OrderByConstants.OrderByAsc);
var j = 0;
while (iterator.MoveNext())
{
var o = iterator.Current;
j++;
if (j == Size)
AssertEquals("value " + Size, o);
}
persister.Close();
DeleteBase(baseName);
}
}
}
| |
// 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.Diagnostics.Tracing
{
[System.FlagsAttribute]
public enum EventActivityOptions
{
Detachable = 8,
Disable = 2,
None = 0,
Recursive = 4,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Method)]
public sealed partial class EventAttribute : System.Attribute
{
public EventAttribute(int eventId) { }
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } set { } }
public int EventId { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public string Message { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } set { } }
public byte Version { get { throw null; } set { } }
}
public enum EventChannel : byte
{
Admin = (byte)16,
Analytic = (byte)18,
Debug = (byte)19,
None = (byte)0,
Operational = (byte)17,
}
public enum EventCommand
{
Disable = -3,
Enable = -2,
SendManifest = -1,
Update = 0,
}
public partial class EventCommandEventArgs : System.EventArgs
{
internal EventCommandEventArgs() { }
public System.Collections.Generic.IDictionary<string, string> Arguments { get { throw null; } }
public System.Diagnostics.Tracing.EventCommand Command { get { throw null; } }
public bool DisableEvent(int eventId) { throw null; }
public bool EnableEvent(int eventId) { throw null; }
}
public partial class EventCounter : System.IDisposable
{
public EventCounter(string name, System.Diagnostics.Tracing.EventSource eventSource) { }
public void Dispose() { }
public void WriteMetric(float value) { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Struct, Inherited=false)]
public partial class EventDataAttribute : System.Attribute
{
public EventDataAttribute() { }
public string Name { get { throw null; } set { } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property)]
public partial class EventFieldAttribute : System.Attribute
{
public EventFieldAttribute() { }
public System.Diagnostics.Tracing.EventFieldFormat Format { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventFieldTags Tags { get { throw null; } set { } }
}
public enum EventFieldFormat
{
Boolean = 3,
Default = 0,
Hexadecimal = 4,
HResult = 15,
Json = 12,
String = 2,
Xml = 11,
}
[System.FlagsAttribute]
public enum EventFieldTags
{
None = 0,
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property)]
public partial class EventIgnoreAttribute : System.Attribute
{
public EventIgnoreAttribute() { }
}
[System.FlagsAttribute]
public enum EventKeywords : long
{
All = (long)-1,
AuditFailure = (long)4503599627370496,
AuditSuccess = (long)9007199254740992,
CorrelationHint = (long)4503599627370496,
EventLogClassic = (long)36028797018963968,
MicrosoftTelemetry = (long)562949953421312,
None = (long)0,
Sqm = (long)2251799813685248,
WdiContext = (long)562949953421312,
WdiDiagnostic = (long)1125899906842624,
}
public enum EventLevel
{
Critical = 1,
Error = 2,
Informational = 4,
LogAlways = 0,
Verbose = 5,
Warning = 3,
}
public abstract partial class EventListener : System.IDisposable
{
protected EventListener() { }
public event System.EventHandler<System.Diagnostics.Tracing.EventSourceCreatedEventArgs> EventSourceCreated { add { } remove { } }
public event System.EventHandler<System.Diagnostics.Tracing.EventWrittenEventArgs> EventWritten { add { } remove { } }
public void DisableEvents(System.Diagnostics.Tracing.EventSource eventSource) { }
public virtual void Dispose() { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword) { }
public void EnableEvents(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords matchAnyKeyword, System.Collections.Generic.IDictionary<string, string> arguments) { }
protected static int EventSourceIndex(System.Diagnostics.Tracing.EventSource eventSource) { throw null; }
protected internal virtual void OnEventSourceCreated(System.Diagnostics.Tracing.EventSource eventSource) { }
protected internal virtual void OnEventWritten(System.Diagnostics.Tracing.EventWrittenEventArgs eventData) { }
}
[System.FlagsAttribute]
public enum EventManifestOptions
{
AllCultures = 2,
AllowEventSourceOverride = 8,
None = 0,
OnlyIfNeededForRegistration = 4,
Strict = 1,
}
public enum EventOpcode
{
DataCollectionStart = 3,
DataCollectionStop = 4,
Extension = 5,
Info = 0,
Receive = 240,
Reply = 6,
Resume = 7,
Send = 9,
Start = 1,
Stop = 2,
Suspend = 8,
}
public partial class EventSource : System.IDisposable
{
protected EventSource() { }
protected EventSource(bool throwOnEventWriteErrors) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings) { }
protected EventSource(System.Diagnostics.Tracing.EventSourceSettings settings, params string[] traits) { }
public EventSource(string eventSourceName) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config) { }
public EventSource(string eventSourceName, System.Diagnostics.Tracing.EventSourceSettings config, params string[] traits) { }
public System.Exception ConstructionException { get { throw null; } }
public static System.Guid CurrentThreadActivityId { get { throw null; } }
public System.Guid Guid { get { throw null; } }
public string Name { get { throw null; } }
public System.Diagnostics.Tracing.EventSourceSettings Settings { get { throw null; } }
public event System.EventHandler<System.Diagnostics.Tracing.EventCommandEventArgs> EventCommandExecuted { add { } remove { } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
~EventSource() { }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest) { throw null; }
public static string GenerateManifest(System.Type eventSourceType, string assemblyPathToIncludeInManifest, System.Diagnostics.Tracing.EventManifestOptions flags) { throw null; }
public static System.Guid GetGuid(System.Type eventSourceType) { throw null; }
public static string GetName(System.Type eventSourceType) { throw null; }
public static System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource> GetSources() { throw null; }
public string GetTrait(string key) { throw null; }
public bool IsEnabled() { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords) { throw null; }
public bool IsEnabled(System.Diagnostics.Tracing.EventLevel level, System.Diagnostics.Tracing.EventKeywords keywords, System.Diagnostics.Tracing.EventChannel channel) { throw null; }
protected virtual void OnEventCommand(System.Diagnostics.Tracing.EventCommandEventArgs command) { }
public static void SendCommand(System.Diagnostics.Tracing.EventSource eventSource, System.Diagnostics.Tracing.EventCommand command, System.Collections.Generic.IDictionary<string, string> commandArguments) { }
public static void SetCurrentThreadActivityId(System.Guid activityId) { }
public static void SetCurrentThreadActivityId(System.Guid activityId, out System.Guid oldActivityThatWillContinue) { throw null; }
public override string ToString() { throw null; }
public void Write(string eventName) { }
public void Write(string eventName, System.Diagnostics.Tracing.EventSourceOptions options) { }
protected void WriteEvent(int eventId) { }
protected void WriteEvent(int eventId, byte[] arg1) { }
protected void WriteEvent(int eventId, int arg1) { }
protected void WriteEvent(int eventId, int arg1, int arg2) { }
protected void WriteEvent(int eventId, int arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, int arg1, string arg2) { }
protected void WriteEvent(int eventId, long arg1) { }
protected void WriteEvent(int eventId, long arg1, byte[] arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2) { }
protected void WriteEvent(int eventId, long arg1, long arg2, long arg3) { }
protected void WriteEvent(int eventId, long arg1, string arg2) { }
protected void WriteEvent(int eventId, params object[] args) { }
protected void WriteEvent(int eventId, string arg1) { }
protected void WriteEvent(int eventId, string arg1, int arg2) { }
protected void WriteEvent(int eventId, string arg1, int arg2, int arg3) { }
protected void WriteEvent(int eventId, string arg1, long arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2) { }
protected void WriteEvent(int eventId, string arg1, string arg2, string arg3) { }
[System.CLSCompliantAttribute(false)]
protected unsafe void WriteEventCore(int eventId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
protected void WriteEventWithRelatedActivityId(int eventId, System.Guid relatedActivityId, params object[] args) { }
[System.CLSCompliantAttribute(false)]
protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, System.Guid* relatedActivityId, int eventDataCount, System.Diagnostics.Tracing.EventSource.EventData* data) { }
public void Write<T>(string eventName, System.Diagnostics.Tracing.EventSourceOptions options, T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref System.Guid activityId, ref System.Guid relatedActivityId, ref T data) { }
public void Write<T>(string eventName, ref System.Diagnostics.Tracing.EventSourceOptions options, ref T data) { }
public void Write<T>(string eventName, T data) { }
protected internal partial struct EventData
{
private int _dummyPrimitive;
public System.IntPtr DataPointer { get { throw null; } set { } }
public int Size { get { throw null; } set { } }
}
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class)]
public sealed partial class EventSourceAttribute : System.Attribute
{
public EventSourceAttribute() { }
public string Guid { get { throw null; } set { } }
public string LocalizationResources { get { throw null; } set { } }
public string Name { get { throw null; } set { } }
}
public partial class EventSourceCreatedEventArgs : System.EventArgs
{
public EventSourceCreatedEventArgs() { }
public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } }
}
public partial class EventSourceException : System.Exception
{
public EventSourceException() { }
protected EventSourceException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public EventSourceException(string message) { }
public EventSourceException(string message, System.Exception innerException) { }
}
public partial struct EventSourceOptions
{
private int _dummyPrimitive;
public System.Diagnostics.Tracing.EventActivityOptions ActivityOptions { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } set { } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } set { } }
}
[System.FlagsAttribute]
public enum EventSourceSettings
{
Default = 0,
EtwManifestEventFormat = 4,
EtwSelfDescribingEventFormat = 8,
ThrowOnEventWriteErrors = 1,
}
[System.FlagsAttribute]
public enum EventTags
{
None = 0,
}
public enum EventTask
{
None = 0,
}
public partial class EventWrittenEventArgs : System.EventArgs
{
internal EventWrittenEventArgs() { }
public System.Guid ActivityId { get { throw null; } }
public System.Diagnostics.Tracing.EventChannel Channel { get { throw null; } }
public int EventId { get { throw null; } }
public string EventName { get { throw null; } }
public System.Diagnostics.Tracing.EventSource EventSource { get { throw null; } }
public System.Diagnostics.Tracing.EventKeywords Keywords { get { throw null; } }
public System.Diagnostics.Tracing.EventLevel Level { get { throw null; } }
public string Message { get { throw null; } }
public System.Diagnostics.Tracing.EventOpcode Opcode { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<object> Payload { get { throw null; } }
public System.Collections.ObjectModel.ReadOnlyCollection<string> PayloadNames { get { throw null; } }
public System.Guid RelatedActivityId { get { throw null; } }
public System.Diagnostics.Tracing.EventTags Tags { get { throw null; } }
public System.Diagnostics.Tracing.EventTask Task { get { throw null; } }
public byte Version { get { throw null; } }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Method)]
public sealed partial class NonEventAttribute : System.Attribute
{
public NonEventAttribute() { }
}
}
| |
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Graphics;
using Appracatappra.ActionComponents.ActionTray;
using Android.Graphics.Drawables;
using Android.Graphics.Drawables.Shapes;
namespace ActionTrayTest.Android
{
[Activity (Label = "ActionTrayTest.Android", MainLauncher = true)]
public class Activity1 : Activity
{
#region Private Variables
private UIActionTray leftTray, rightTray, toolsTray, propertyTray, paletteTray, documentTray;
#endregion
#region Public Variables
public UIActionTrayManager trayManager;
#endregion
#region Override Methods
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Gain Access to all views and controls in our layout
leftTray = FindViewById<UIActionTray> (Resource.Id.trayLeft);
rightTray = FindViewById<UIActionTray> (Resource.Id.trayRight);
toolsTray = FindViewById<UIActionTray> (Resource.Id.trayTools);
propertyTray = FindViewById<UIActionTray> (Resource.Id.trayProperty);
paletteTray = FindViewById<UIActionTray> (Resource.Id.trayPalette);
documentTray = FindViewById<UIActionTray> (Resource.Id.trayDocuments);
// Create a TrayManager to handle a collection of "palette"
// trays. It will automatically close any open tray when
// another tray in this collection is opened.
trayManager = new UIActionTrayManager ();
// Automatically close the left and right trays when any tray
// in the manager's collection is opened
trayManager.TrayOpened += (tray) => {
// Animate the trays being closed
leftTray.CloseTray (true);
rightTray.CloseTray (true);
};
// Setup the left side tray
leftTray.trayType = UIActionTrayType.Draggable;
leftTray.orientation = UIActionTrayOrientation.Left;
leftTray.tabLocation = UIActionTrayTabLocation.BottomOrRight;
leftTray.frameType = UIActionTrayFrameType.EdgeOnly;
leftTray.tabType = UIActionTrayTabType.IconAndTitle;
leftTray.bringToFrontOnTouch=true;
// Style tray
leftTray.appearance.background = Color.Gray;
leftTray.appearance.border = Color.Red;
leftTray.icon = Resource.Drawable.icon_calendar;
leftTray.title = "Events";
leftTray.appearance.tabAlpha=100;
leftTray.CloseTray (false);
// Respond to the left tray being touched
leftTray.Touched+= (tray) => {
//Yes, close this tray and aminate the closing
rightTray.CloseTray (true);
// Tell any open palette trays to close
trayManager.CloseAllTrays ();
// Close document tray
documentTray.CloseTray (true);
};
// Setup the right side tray
rightTray.trayType = UIActionTrayType.Popup;
rightTray.orientation = UIActionTrayOrientation.Right;
rightTray.bringToFrontOnTouch = true;
rightTray.CloseTray (false);
// Respond to the tray being opened
rightTray.Opened+= (tray) => {
//Close this tray and aminate the closing
leftTray.CloseTray (true);
// Tell any open palette trays to close
trayManager.CloseAllTrays ();
// Close document tray
documentTray.CloseTray (true);
};
// Set tray type
documentTray.trayType = UIActionTrayType.AutoClosingPopup;
documentTray.orientation = UIActionTrayOrientation.Bottom;
documentTray.tabType = UIActionTrayTabType.GripAndTitle;
documentTray.bringToFrontOnTouch=true;
// Style tray
documentTray.tabWidth = 125;
documentTray.appearance.background = Color.Gray;
documentTray.title = "Documents";
documentTray.CloseTray (false);
// Respond to the tray being opened
documentTray.Opened += (tray) => {
// Close left and right trays
leftTray.CloseTray(true);
rightTray.CloseTray(true);
};
//--------------------------------------------------------------------------------------
// Create three action tray's and use them as a collection via an ActionTrayManager
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// Palette 1
// Set tray type
paletteTray.trayType = UIActionTrayType.AutoClosingPopup;
paletteTray.orientation = UIActionTrayOrientation.Top;
paletteTray.tabLocation = UIActionTrayTabLocation.TopOrLeft;
paletteTray.tabType = UIActionTrayTabType.IconAndTitle;
paletteTray.CloseTray (false);
// Style tray
paletteTray.tabWidth = 125;
paletteTray.appearance.background = Color.Gray;
paletteTray.icon = Resource.Drawable.icon_palette;
paletteTray.title="Palette";
// Add this tray to the manager's collection
trayManager.AddTray (paletteTray);
//--------------------------------------------------------------------------------------
// Palette 2
// Setup property tray type
propertyTray.trayType = UIActionTrayType.Popup;
propertyTray.orientation = UIActionTrayOrientation.Top;
propertyTray.tabLocation = UIActionTrayTabLocation.TopOrLeft;
propertyTray.tabType = UIActionTrayTabType.IconAndTitle;
propertyTray.CloseTray (false);
// Style tray
propertyTray.tabWidth = 125;
propertyTray.appearance.background = Color.Rgb (38,38,38);
propertyTray.icon=Resource.Drawable.icon_measures;
propertyTray.title="Properties";
// Add this tray to the manager's collection
trayManager.AddTray (propertyTray);
//--------------------------------------------------------------------------------------
// Palette 3
// Setup tools tray type
toolsTray.trayType = UIActionTrayType.AutoClosingPopup;
toolsTray.orientation = UIActionTrayOrientation.Top;
toolsTray.tabType = UIActionTrayTabType.IconOnly;
toolsTray.CloseTray (false);
// Style tools tray
toolsTray.tabWidth = 50;
toolsTray.tabLocation = UIActionTrayTabLocation.BottomOrRight;
toolsTray.appearance.background = Color.Rgb (38,38,38);
toolsTray.tabType = UIActionTrayTabType.CustomDrawn;
toolsTray.icon = Resource.Drawable.icon_pencil;
// Custom draw this tab
toolsTray.CustomDrawDragTab += (tray, canvas, rect) => {
//Draw background
var body= new ShapeDrawable(new RectShape());
body.Paint.Color=tray.appearance.background;
body.SetBounds (rect.Left, rect.Top, rect.Right, rect.Bottom);
body.Draw (canvas);
//Define icon paint
var iPaint=new Paint();
iPaint.Alpha=tray.appearance.tabAlpha;
//Load bitmap
var bitmap=BitmapFactory.DecodeResource(Resources,tray.icon);
//Draw image
canvas.DrawBitmap (bitmap, rect.Left+1, rect.Top+5, iPaint);
};
// Add this tray to the manager's collection
trayManager.AddTray (toolsTray);
}
protected override void OnSaveInstanceState (Bundle outState)
{
//Save the state of all trays on the screen
outState.PutString("leftTray",leftTray.SaveState);
outState.PutString("rightTray",rightTray.SaveState);
outState.PutString("documentTray",documentTray.SaveState);
outState.PutString("paletteTray",paletteTray.SaveState);
outState.PutString("propertyTray",propertyTray.SaveState);
outState.PutString("toolsTray",toolsTray.SaveState);
base.OnSaveInstanceState (outState);
}
protected override void OnRestoreInstanceState (Bundle savedInstanceState)
{
//Restore all trays to their previous states
leftTray.RestoreState(savedInstanceState.GetString("leftTray"));
rightTray.RestoreState(savedInstanceState.GetString("rightTray"));
documentTray.RestoreState(savedInstanceState.GetString("documentTray"));
paletteTray.RestoreState(savedInstanceState.GetString("paletteTray"));
propertyTray.RestoreState(savedInstanceState.GetString("propertyTray"));
toolsTray.RestoreState(savedInstanceState.GetString("toolsTray"));
base.OnRestoreInstanceState (savedInstanceState);
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.ProjectModel.Graph;
using Microsoft.Extensions.ProjectModel.Utilities;
using NuGet.Versioning;
namespace Microsoft.Extensions.ProjectModel.Resolution
{
public class LibraryManager
{
private readonly IList<LibraryDescription> _libraries;
private readonly IList<DiagnosticMessage> _diagnostics;
private readonly string _projectPath;
public LibraryManager(IList<LibraryDescription> libraries,
IList<DiagnosticMessage> diagnostics,
string projectPath)
{
_libraries = libraries;
_diagnostics = diagnostics;
_projectPath = projectPath;
}
public IList<LibraryDescription> GetLibraries()
{
return _libraries;
}
public IList<DiagnosticMessage> GetAllDiagnostics()
{
var messages = new List<DiagnosticMessage>();
if (_diagnostics != null)
{
messages.AddRange(_diagnostics);
}
var dependencies = new Dictionary<string, List<DependencyItem>>();
var topLevel = new List<LibraryItem>();
foreach (var library in GetLibraries())
{
if (!library.Resolved)
{
string message;
string errorCode;
if (library.Compatible)
{
foreach (var range in library.RequestedRanges)
{
errorCode = ErrorCodes.NU1001;
message = $"The dependency {FormatLibraryRange(range)} could not be resolved.";
AddDiagnostics(messages, library, message, DiagnosticMessageSeverity.Error, errorCode);
}
}
else
{
errorCode = ErrorCodes.NU1002;
message = $"The dependency {library.Identity} does not support framework {library.Framework}.";
AddDiagnostics(messages, library, message, DiagnosticMessageSeverity.Error, errorCode);
}
}
else
{
// Store dependency -> library for later
// J.N -> [(R1, P1), (R2, P2)]
foreach (var dependency in library.Dependencies)
{
List<DependencyItem> items;
if (!dependencies.TryGetValue(dependency.Name, out items))
{
items = new List<DependencyItem>();
dependencies[dependency.Name] = items;
}
items.Add(new DependencyItem(dependency, library));
}
foreach (var range in library.RequestedRanges)
{
// Skip libraries that aren't specified in a project.json
// Only report problems for this project
if (string.IsNullOrEmpty(range.SourceFilePath))
{
continue;
}
// We only care about things requested in this project
if (!string.Equals(_projectPath, range.SourceFilePath))
{
continue;
}
if (range.VersionRange == null)
{
// TODO: Show errors/warnings for things without versions
continue;
}
topLevel.Add(new LibraryItem(range, library));
// If we ended up with a declared version that isn't what was asked for directly
// then report a warning
// Case 1: Non floating version and the minimum doesn't match what was specified
// Case 2: Floating version that fell outside of the range
if ((!range.VersionRange.IsFloating &&
range.VersionRange.MinVersion != library.Identity.Version) ||
(range.VersionRange.IsFloating &&
!range.VersionRange.Float.Satisfies(library.Identity.Version)))
{
var message = $"Dependency specified was {FormatLibraryRange(range)} but ended up with {library.Identity}.";
messages.Add(
new DiagnosticMessage(
ErrorCodes.NU1007,
message,
range.SourceFilePath,
DiagnosticMessageSeverity.Warning,
range.SourceLine,
range.SourceColumn,
library));
}
}
}
}
// Version conflicts
foreach (var libraryItem in topLevel)
{
var library = libraryItem.Library;
if (library.Identity.Type != LibraryType.Package)
{
continue;
}
List<DependencyItem> items;
if (dependencies.TryGetValue(library.Identity.Name, out items))
{
foreach (var item in items)
{
var versionRange = item.Dependency.VersionRange;
if (versionRange == null)
{
continue;
}
if (library.Identity.Version.IsPrerelease && !versionRange.IncludePrerelease)
{
versionRange = VersionRange.SetIncludePrerelease(versionRange, includePrerelease: true);
}
if (item.Library != library && !versionRange.Satisfies(library.Identity.Version))
{
var message = $"Dependency conflict. {item.Library.Identity} expected {FormatLibraryRange(item.Dependency)} but got {library.Identity.Version}";
messages.Add(
new DiagnosticMessage(
ErrorCodes.NU1012,
message,
libraryItem.RequestedRange.SourceFilePath,
DiagnosticMessageSeverity.Warning,
libraryItem.RequestedRange.SourceLine,
libraryItem.RequestedRange.SourceColumn,
library));
}
}
}
}
return messages;
}
private static string FormatLibraryRange(LibraryRange range)
{
if (range.VersionRange == null)
{
return range.Name;
}
return range.Name + " " + VersionUtility.RenderVersion(range.VersionRange);
}
private void AddDiagnostics(List<DiagnosticMessage> messages,
LibraryDescription library,
string message,
DiagnosticMessageSeverity severity,
string errorCode)
{
// A (in project.json) -> B (unresolved) (not in project.json)
foreach (var source in GetRangesWithSourceLocations(library).Distinct())
{
// We only care about things requested in this project
if (!string.Equals(_projectPath, source.SourceFilePath))
{
continue;
}
messages.Add(
new DiagnosticMessage(
errorCode,
message,
source.SourceFilePath,
severity,
source.SourceLine,
source.SourceColumn,
library));
}
}
private IEnumerable<LibraryRange> GetRangesWithSourceLocations(LibraryDescription library)
{
foreach (var range in library.RequestedRanges)
{
if (!string.IsNullOrEmpty(range.SourceFilePath))
{
yield return range;
}
}
foreach (var parent in library.Parents)
{
foreach (var relevantPath in GetRangesWithSourceLocations(parent))
{
yield return relevantPath;
}
}
}
private struct DependencyItem
{
public LibraryRange Dependency { get; private set; }
public LibraryDescription Library { get; private set; }
public DependencyItem(LibraryRange dependency, LibraryDescription library)
{
Dependency = dependency;
Library = library;
}
}
private struct LibraryItem
{
public LibraryRange RequestedRange { get; private set; }
public LibraryDescription Library { get; private set; }
public LibraryItem(LibraryRange requestedRange, LibraryDescription library)
{
RequestedRange = requestedRange;
Library = library;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using EdjCase.JsonRpc.Router.Abstractions;
using EdjCase.JsonRpc.Router.Swagger.Extensions;
using EdjCase.JsonRpc.Router.Swagger.Models;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace EdjCase.JsonRpc.Router.Swagger
{
public class JsonRpcSwaggerProvider : ISwaggerProvider
{
private readonly ISchemaGenerator schemaGenerator;
private readonly SwaggerConfiguration swagerOptions;
private readonly IRpcMethodProvider methodProvider;
private readonly IXmlDocumentationService xmlDocumentationService;
private OpenApiDocument? cacheDocument;
private JsonNamingPolicy namePolicy;
public JsonRpcSwaggerProvider(
ISchemaGenerator schemaGenerator,
IRpcMethodProvider methodProvider,
IXmlDocumentationService xmlDocumentationService,
IOptions<SwaggerConfiguration> swaggerOptions
)
{
this.schemaGenerator = schemaGenerator;
this.swagerOptions = swaggerOptions.Value;
this.namePolicy = swaggerOptions.Value.NamingPolicy;
this.methodProvider = methodProvider;
this.xmlDocumentationService = xmlDocumentationService;
}
private List<UniqueMethod> GetUniqueKeyMethodPairs(RpcRouteMetaData metaData)
{
List<UniqueMethod> methodList = this.Convert(metaData.BaseRoute, path: null).ToList();
foreach ((RpcPath path, IReadOnlyList<IRpcMethodInfo> pathRoutes) in metaData.PathRoutes)
{
methodList.AddRange(this.Convert(pathRoutes, path));
}
return methodList;
}
private IEnumerable<UniqueMethod> Convert(IEnumerable<IRpcMethodInfo> routeInfo, RpcPath? path)
{
//group by name for generate unique url similar method names
foreach (IGrouping<string, IRpcMethodInfo> methodsGroup in routeInfo.GroupBy(x => x.Name))
{
int? methodCounter = methodsGroup.Count() > 1 ? 1 : (int?)null;
foreach (IRpcMethodInfo methodInfo in methodsGroup)
{
string methodName = this.namePolicy.ConvertName(methodInfo.Name);
string uniqueUrl = $"/{path}#{methodName}";
if (methodCounter != null)
{
uniqueUrl += $"#{methodCounter++}";
}
yield return new UniqueMethod(uniqueUrl, methodInfo);
}
}
}
public OpenApiDocument GetSwagger(string documentName, string? host = null, string? basePath = null)
{
if (this.cacheDocument != null)
{
return this.cacheDocument;
}
var schemaRepository = new SchemaRepository();
RpcRouteMetaData metaData = this.methodProvider.Get();
OpenApiPaths paths = this.GetOpenApiPaths(metaData, schemaRepository);
this.cacheDocument = new OpenApiDocument()
{
Info = new OpenApiInfo()
{
Title = Assembly.GetEntryAssembly().GetName().Name,
Version = "v1"
},
Servers = this.swagerOptions.Endpoints.Select(x => new OpenApiServer()
{
Url = x
}).ToList(),
Components = new OpenApiComponents()
{
Schemas = schemaRepository.Schemas
},
Paths = paths
};
return this.cacheDocument;
}
private OpenApiPaths GetOpenApiPaths(RpcRouteMetaData metaData, SchemaRepository schemaRepository)
{
OpenApiPaths paths = new OpenApiPaths();
List<UniqueMethod> uniqueMethods = this.GetUniqueKeyMethodPairs(metaData);
foreach (UniqueMethod method in uniqueMethods)
{
string operationKey = method.UniqueUrl.Replace("/", "_").Replace("#", "|");
OpenApiOperation operation = this.GetOpenApiOperation(operationKey, method.Info, schemaRepository);
var pathItem = new OpenApiPathItem()
{
Operations = new Dictionary<OperationType, OpenApiOperation>()
{
[OperationType.Post] = operation
}
};
paths.Add(method.UniqueUrl, pathItem);
}
return paths;
}
private OpenApiOperation GetOpenApiOperation(string key, IRpcMethodInfo methodInfo, SchemaRepository schemaRepository)
{
string methodAnnotation = this.xmlDocumentationService.GetSummaryForMethod(methodInfo);
Type trueReturnType = this.GetReturnType(methodInfo.RawReturnType);
return new OpenApiOperation()
{
Tags = new List<OpenApiTag>(),
Summary = methodAnnotation,
RequestBody = this.GetOpenApiRequestBody(key, methodInfo, schemaRepository),
Responses = this.GetOpenApiResponses(key, trueReturnType, schemaRepository)
};
}
private Type GetReturnType(Type returnType)
{
if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>))
{
//Return the `Task` return type
return returnType.GenericTypeArguments.First();
}
if (returnType == typeof(Task))
{
//Task with no return type
return typeof(void);
}
return returnType;
}
private OpenApiResponses GetOpenApiResponses(string key, Type returnMethodType, SchemaRepository schemaRepository)
{
return new OpenApiResponses()
{
["200"] = new OpenApiResponse()
{
Content = new Dictionary<string, OpenApiMediaType>()
{
["application/json"] = new OpenApiMediaType
{
Schema = this.GeResposeSchema(key, returnMethodType, schemaRepository)
}
}
}
};
}
private OpenApiRequestBody GetOpenApiRequestBody(string key, IRpcMethodInfo methodInfo,
SchemaRepository schemaRepository)
{
return new OpenApiRequestBody()
{
Content = new Dictionary<string, OpenApiMediaType>()
{
["application/json"] = new OpenApiMediaType()
{
Schema = this.GetBodyParamsSchema(key, schemaRepository, methodInfo)
}
}
};
}
private OpenApiSchema GetBodyParamsSchema(string key, SchemaRepository schemaRepository, IRpcMethodInfo methodInfo)
{
OpenApiSchema paramsObjectSchema = this.GetOpenApiEmptyObject();
foreach (IRpcParameterInfo parameterInfo in methodInfo.Parameters)
{
string name = this.namePolicy.ConvertName(parameterInfo.Name);
OpenApiSchema schema = this.schemaGenerator.GenerateSchema(parameterInfo.RawType, schemaRepository);
paramsObjectSchema.Properties.Add(name, schema);
}
paramsObjectSchema = schemaRepository.AddDefinition($"{key}", paramsObjectSchema);
var requestSchema = this.GetOpenApiEmptyObject();
requestSchema.Properties.Add("id", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
requestSchema.Properties.Add("jsonrpc", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
requestSchema.Properties.Add("method", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
requestSchema.Properties.Add("params", paramsObjectSchema);
requestSchema = schemaRepository.AddDefinition($"request_{key}", requestSchema);
this.RewriteJrpcAttributesExamples(requestSchema, schemaRepository, this.namePolicy.ConvertName(methodInfo.Name));
return requestSchema;
}
private OpenApiSchema GeResposeSchema(string key, Type returnMethodType, SchemaRepository schemaRepository)
{
var resultSchema = this.schemaGenerator.GenerateSchema(returnMethodType, schemaRepository);
var responseSchema = this.GetOpenApiEmptyObject();
responseSchema.Properties.Add("id", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
responseSchema.Properties.Add("jsonrpc", this.schemaGenerator.GenerateSchema(typeof(string), schemaRepository));
responseSchema.Properties.Add("result", resultSchema);
responseSchema = schemaRepository.AddDefinition($"response_{key}", responseSchema);
this.RewriteJrpcAttributesExamples(responseSchema, schemaRepository);
return responseSchema;
}
private OpenApiSchema GetOpenApiEmptyObject()
{
return new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>(),
Required = new SortedSet<string>(),
AdditionalPropertiesAllowed = false
};
}
private void RewriteJrpcAttributesExamples(OpenApiSchema schema, SchemaRepository schemaRepository, string method = "method_name")
{
var jrpcAttributesExample =
new OpenApiObject()
{
{"id", new OpenApiString(Guid.NewGuid().ToString())},
{"jsonrpc", new OpenApiString("2.0")},
{"method", new OpenApiString(method)},
};
foreach (var prop in schemaRepository.Schemas[schema.Reference.Id].Properties)
{
if (jrpcAttributesExample.ContainsKey(prop.Key))
{
prop.Value.Example = jrpcAttributesExample[prop.Key];
}
}
}
}
}
| |
using J2N;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JCG = J2N.Collections.Generic;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* this SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Lucene.Net.Util.Automaton
{
/// <summary>
/// Basic automata operations.
/// <para/>
/// @lucene.experimental
/// </summary>
public static class BasicOperations // LUCENENET specific - made static since all members are static
{
/// <summary>
/// Returns an automaton that accepts the concatenation of the languages of the
/// given automata.
/// <para/>
/// Complexity: linear in number of states.
/// </summary>
public static Automaton Concatenate(Automaton a1, Automaton a2)
{
if (a1.IsSingleton && a2.IsSingleton)
{
return BasicAutomata.MakeString(a1.singleton + a2.singleton);
}
if (IsEmpty(a1) || IsEmpty(a2))
{
return BasicAutomata.MakeEmpty();
}
// adding epsilon transitions with the NFA concatenation algorithm
// in this case always produces a resulting DFA, preventing expensive
// redundant determinize() calls for this common case.
bool deterministic = a1.IsSingleton && a2.IsDeterministic;
if (a1 == a2)
{
a1 = a1.CloneExpanded();
a2 = a2.CloneExpanded();
}
else
{
a1 = a1.CloneExpandedIfRequired();
a2 = a2.CloneExpandedIfRequired();
}
foreach (State s in a1.GetAcceptStates())
{
s.accept = false;
s.AddEpsilon(a2.initial);
}
a1.deterministic = deterministic;
//a1.clearHashCode();
a1.ClearNumberedStates();
a1.CheckMinimizeAlways();
return a1;
}
/// <summary>
/// Returns an automaton that accepts the concatenation of the languages of the
/// given automata.
/// <para/>
/// Complexity: linear in total number of states.
/// </summary>
public static Automaton Concatenate(IList<Automaton> l)
{
if (l.Count == 0)
{
return BasicAutomata.MakeEmptyString();
}
bool all_singleton = true;
foreach (Automaton a in l)
{
if (!a.IsSingleton)
{
all_singleton = false;
break;
}
}
if (all_singleton)
{
StringBuilder b = new StringBuilder();
foreach (Automaton a in l)
{
b.Append(a.singleton);
}
return BasicAutomata.MakeString(b.ToString());
}
else
{
foreach (Automaton a in l)
{
if (BasicOperations.IsEmpty(a))
{
return BasicAutomata.MakeEmpty();
}
}
JCG.HashSet<int> ids = new JCG.HashSet<int>();
foreach (Automaton a in l)
{
ids.Add(a.GetHashCode());
}
bool has_aliases = ids.Count != l.Count;
Automaton b = l[0];
if (has_aliases)
{
b = b.CloneExpanded();
}
else
{
b = b.CloneExpandedIfRequired();
}
ISet<State> ac = b.GetAcceptStates();
bool first = true;
foreach (Automaton a in l)
{
if (first)
{
first = false;
}
else
{
if (a.IsEmptyString)
{
continue;
}
Automaton aa = a;
if (has_aliases)
{
aa = aa.CloneExpanded();
}
else
{
aa = aa.CloneExpandedIfRequired();
}
ISet<State> ns = aa.GetAcceptStates();
foreach (State s in ac)
{
s.accept = false;
s.AddEpsilon(aa.initial);
if (s.accept)
{
ns.Add(s);
}
}
ac = ns;
}
}
b.deterministic = false;
//b.clearHashCode();
b.ClearNumberedStates();
b.CheckMinimizeAlways();
return b;
}
}
/// <summary>
/// Returns an automaton that accepts the union of the empty string and the
/// language of the given automaton.
/// <para/>
/// Complexity: linear in number of states.
/// </summary>
public static Automaton Optional(Automaton a)
{
a = a.CloneExpandedIfRequired();
State s = new State();
s.AddEpsilon(a.initial);
s.accept = true;
a.initial = s;
a.deterministic = false;
//a.clearHashCode();
a.ClearNumberedStates();
a.CheckMinimizeAlways();
return a;
}
/// <summary>
/// Returns an automaton that accepts the Kleene star (zero or more
/// concatenated repetitions) of the language of the given automaton. Never
/// modifies the input automaton language.
/// <para/>
/// Complexity: linear in number of states.
/// </summary>
public static Automaton Repeat(Automaton a)
{
a = a.CloneExpanded();
State s = new State
{
accept = true
};
s.AddEpsilon(a.initial);
foreach (State p in a.GetAcceptStates())
{
p.AddEpsilon(s);
}
a.initial = s;
a.deterministic = false;
//a.clearHashCode();
a.ClearNumberedStates();
a.CheckMinimizeAlways();
return a;
}
/// <summary>
/// Returns an automaton that accepts <paramref name="min"/> or more concatenated
/// repetitions of the language of the given automaton.
/// <para/>
/// Complexity: linear in number of states and in <paramref name="min"/>.
/// </summary>
public static Automaton Repeat(Automaton a, int min)
{
if (min == 0)
{
return Repeat(a);
}
IList<Automaton> @as = new List<Automaton>();
while (min-- > 0)
{
@as.Add(a);
}
@as.Add(Repeat(a));
return Concatenate(@as);
}
/// <summary>
/// Returns an automaton that accepts between <paramref name="min"/> and
/// <paramref name="max"/> (including both) concatenated repetitions of the language
/// of the given automaton.
/// <para/>
/// Complexity: linear in number of states and in <paramref name="min"/> and
/// <paramref name="max"/>.
/// </summary>
public static Automaton Repeat(Automaton a, int min, int max)
{
if (min > max)
{
return BasicAutomata.MakeEmpty();
}
max -= min;
a.ExpandSingleton();
Automaton b;
if (min == 0)
{
b = BasicAutomata.MakeEmptyString();
}
else if (min == 1)
{
b = (Automaton)a.Clone();
}
else
{
IList<Automaton> @as = new List<Automaton>();
while (min-- > 0)
{
@as.Add(a);
}
b = Concatenate(@as);
}
if (max > 0)
{
Automaton d = (Automaton)a.Clone();
while (--max > 0)
{
Automaton c = (Automaton)a.Clone();
foreach (State p in c.GetAcceptStates())
{
p.AddEpsilon(d.initial);
}
d = c;
}
foreach (State p in b.GetAcceptStates())
{
p.AddEpsilon(d.initial);
}
b.deterministic = false;
//b.clearHashCode();
b.ClearNumberedStates();
b.CheckMinimizeAlways();
}
return b;
}
/// <summary>
/// Returns a (deterministic) automaton that accepts the complement of the
/// language of the given automaton.
/// <para/>
/// Complexity: linear in number of states (if already deterministic).
/// </summary>
public static Automaton Complement(Automaton a)
{
a = a.CloneExpandedIfRequired();
a.Determinize();
a.Totalize();
foreach (State p in a.GetNumberedStates())
{
p.accept = !p.accept;
}
a.RemoveDeadTransitions();
return a;
}
/// <summary>
/// Returns a (deterministic) automaton that accepts the intersection of the
/// language of <paramref name="a1"/> and the complement of the language of
/// <paramref name="a2"/>. As a side-effect, the automata may be determinized, if not
/// already deterministic.
/// <para/>
/// Complexity: quadratic in number of states (if already deterministic).
/// </summary>
public static Automaton Minus(Automaton a1, Automaton a2)
{
if (BasicOperations.IsEmpty(a1) || a1 == a2)
{
return BasicAutomata.MakeEmpty();
}
if (BasicOperations.IsEmpty(a2))
{
return a1.CloneIfRequired();
}
if (a1.IsSingleton)
{
if (BasicOperations.Run(a2, a1.singleton))
{
return BasicAutomata.MakeEmpty();
}
else
{
return a1.CloneIfRequired();
}
}
return Intersection(a1, a2.Complement());
}
/// <summary>
/// Returns an automaton that accepts the intersection of the languages of the
/// given automata. Never modifies the input automata languages.
/// <para/>
/// Complexity: quadratic in number of states.
/// </summary>
public static Automaton Intersection(Automaton a1, Automaton a2)
{
if (a1.IsSingleton)
{
if (BasicOperations.Run(a2, a1.singleton))
{
return a1.CloneIfRequired();
}
else
{
return BasicAutomata.MakeEmpty();
}
}
if (a2.IsSingleton)
{
if (BasicOperations.Run(a1, a2.singleton))
{
return a2.CloneIfRequired();
}
else
{
return BasicAutomata.MakeEmpty();
}
}
if (a1 == a2)
{
return a1.CloneIfRequired();
}
Transition[][] transitions1 = a1.GetSortedTransitions();
Transition[][] transitions2 = a2.GetSortedTransitions();
Automaton c = new Automaton();
Queue<StatePair> worklist = new Queue<StatePair>(); // LUCENENET specific - Queue is much more performant than LinkedList
Dictionary<StatePair, StatePair> newstates = new Dictionary<StatePair, StatePair>();
StatePair p = new StatePair(c.initial, a1.initial, a2.initial);
worklist.Enqueue(p);
newstates[p] = p;
while (worklist.Count > 0)
{
p = worklist.Dequeue();
p.s.accept = p.s1.accept && p.s2.accept;
Transition[] t1 = transitions1[p.s1.number];
Transition[] t2 = transitions2[p.s2.number];
for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++)
{
while (b2 < t2.Length && t2[b2].max < t1[n1].min)
{
b2++;
}
for (int n2 = b2; n2 < t2.Length && t1[n1].max >= t2[n2].min; n2++)
{
if (t2[n2].max >= t1[n1].min)
{
StatePair q = new StatePair(t1[n1].to, t2[n2].to);
if (!newstates.TryGetValue(q, out StatePair r) || r is null)
{
q.s = new State();
worklist.Enqueue(q);
newstates[q] = q;
r = q;
}
int min = t1[n1].min > t2[n2].min ? t1[n1].min : t2[n2].min;
int max = t1[n1].max < t2[n2].max ? t1[n1].max : t2[n2].max;
p.s.AddTransition(new Transition(min, max, r.s));
}
}
}
}
c.deterministic = a1.deterministic && a2.deterministic;
c.RemoveDeadTransitions();
c.CheckMinimizeAlways();
return c;
}
/// <summary>
/// Returns <c>true</c> if these two automata accept exactly the
/// same language. This is a costly computation! Note
/// also that <paramref name="a1"/> and <paramref name="a2"/> will be determinized as a side
/// effect.
/// </summary>
public static bool SameLanguage(Automaton a1, Automaton a2)
{
if (a1 == a2)
{
return true;
}
if (a1.IsSingleton && a2.IsSingleton)
{
return a1.singleton.Equals(a2.singleton, StringComparison.Ordinal);
}
else if (a1.IsSingleton)
{
// subsetOf is faster if the first automaton is a singleton
return SubsetOf(a1, a2) && SubsetOf(a2, a1);
}
else
{
return SubsetOf(a2, a1) && SubsetOf(a1, a2);
}
}
/// <summary>
/// Returns true if the language of <paramref name="a1"/> is a subset of the language
/// of <paramref name="a2"/>. As a side-effect, <paramref name="a2"/> is determinized if
/// not already marked as deterministic.
/// <para/>
/// Complexity: quadratic in number of states.
/// </summary>
public static bool SubsetOf(Automaton a1, Automaton a2)
{
if (a1 == a2)
{
return true;
}
if (a1.IsSingleton)
{
if (a2.IsSingleton)
{
return a1.singleton.Equals(a2.singleton, StringComparison.Ordinal);
}
return BasicOperations.Run(a2, a1.singleton);
}
a2.Determinize();
Transition[][] transitions1 = a1.GetSortedTransitions();
Transition[][] transitions2 = a2.GetSortedTransitions();
Queue<StatePair> worklist = new Queue<StatePair>(); // LUCENENET specific - Queue is much more performant than LinkedList
JCG.HashSet<StatePair> visited = new JCG.HashSet<StatePair>();
StatePair p = new StatePair(a1.initial, a2.initial);
worklist.Enqueue(p);
visited.Add(p);
while (worklist.Count > 0)
{
p = worklist.Dequeue();
if (p.s1.accept && !p.s2.accept)
{
return false;
}
Transition[] t1 = transitions1[p.s1.number];
Transition[] t2 = transitions2[p.s2.number];
for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++)
{
while (b2 < t2.Length && t2[b2].max < t1[n1].min)
{
b2++;
}
int min1 = t1[n1].min, max1 = t1[n1].max;
for (int n2 = b2; n2 < t2.Length && t1[n1].max >= t2[n2].min; n2++)
{
if (t2[n2].min > min1)
{
return false;
}
if (t2[n2].max < Character.MaxCodePoint)
{
min1 = t2[n2].max + 1;
}
else
{
min1 = Character.MaxCodePoint;
max1 = Character.MinCodePoint;
}
StatePair q = new StatePair(t1[n1].to, t2[n2].to);
if (!visited.Contains(q))
{
worklist.Enqueue(q);
visited.Add(q);
}
}
if (min1 <= max1)
{
return false;
}
}
}
return true;
}
/// <summary>
/// Returns an automaton that accepts the union of the languages of the given
/// automata.
/// <para/>
/// Complexity: linear in number of states.
/// </summary>
public static Automaton Union(Automaton a1, Automaton a2)
{
if ((a1.IsSingleton && a2.IsSingleton && a1.singleton.Equals(a2.singleton, StringComparison.Ordinal)) || a1 == a2)
{
return a1.CloneIfRequired();
}
if (a1 == a2)
{
a1 = a1.CloneExpanded();
a2 = a2.CloneExpanded();
}
else
{
a1 = a1.CloneExpandedIfRequired();
a2 = a2.CloneExpandedIfRequired();
}
State s = new State();
s.AddEpsilon(a1.initial);
s.AddEpsilon(a2.initial);
a1.initial = s;
a1.deterministic = false;
//a1.clearHashCode();
a1.ClearNumberedStates();
a1.CheckMinimizeAlways();
return a1;
}
/// <summary>
/// Returns an automaton that accepts the union of the languages of the given
/// automata.
/// <para/>
/// Complexity: linear in number of states.
/// </summary>
public static Automaton Union(ICollection<Automaton> l)
{
JCG.HashSet<int> ids = new JCG.HashSet<int>();
foreach (Automaton a in l)
{
ids.Add(a.GetHashCode());
}
bool has_aliases = ids.Count != l.Count;
State s = new State();
foreach (Automaton b in l)
{
if (BasicOperations.IsEmpty(b))
{
continue;
}
Automaton bb = b;
if (has_aliases)
{
bb = bb.CloneExpanded();
}
else
{
bb = bb.CloneExpandedIfRequired();
}
s.AddEpsilon(bb.initial);
}
Automaton a_ = new Automaton
{
initial = s,
deterministic = false
};
//a.clearHashCode();
a_.ClearNumberedStates();
a_.CheckMinimizeAlways();
return a_;
}
// Simple custom ArrayList<Transition>
private sealed class TransitionList
{
internal Transition[] transitions = new Transition[2];
internal int count;
public void Add(Transition t)
{
if (transitions.Length == count)
{
// LUCENENET: Resize rather than copy
Array.Resize(ref transitions, ArrayUtil.Oversize(1 + count, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
}
transitions[count++] = t;
}
}
// Holds all transitions that start on this int point, or
// end at this point-1
private sealed class PointTransitions : IComparable<PointTransitions>
{
internal int point;
internal readonly TransitionList ends = new TransitionList();
internal readonly TransitionList starts = new TransitionList();
public int CompareTo(PointTransitions other)
{
return point - other.point;
}
public void Reset(int point)
{
this.point = point;
ends.count = 0;
starts.count = 0;
}
public override bool Equals(object other)
{
return ((PointTransitions)other).point == point;
}
public override int GetHashCode()
{
return point;
}
}
private sealed class PointTransitionSet
{
internal int count;
internal PointTransitions[] points = new PointTransitions[5];
private const int HASHMAP_CUTOVER = 30;
private readonly Dictionary<int?, PointTransitions> map = new Dictionary<int?, PointTransitions>();
private bool useHash = false;
private PointTransitions Next(int point)
{
// 1st time we are seeing this point
if (count == points.Length)
{
// LUCENENET: Resize rather than copy
Array.Resize(ref points, ArrayUtil.Oversize(1 + count, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
}
PointTransitions points0 = points[count];
if (points0 == null)
{
points0 = points[count] = new PointTransitions();
}
points0.Reset(point);
count++;
return points0;
}
private PointTransitions Find(int point)
{
if (useHash)
{
int? pi = point;
if (!map.TryGetValue(pi, out PointTransitions p))
{
p = Next(point);
map[pi] = p;
}
return p;
}
else
{
for (int i = 0; i < count; i++)
{
if (points[i].point == point)
{
return points[i];
}
}
PointTransitions p = Next(point);
if (count == HASHMAP_CUTOVER)
{
// switch to HashMap on the fly
if (Debugging.AssertsEnabled) Debugging.Assert(map.Count == 0);
for (int i = 0; i < count; i++)
{
map[points[i].point] = points[i];
}
useHash = true;
}
return p;
}
}
public void Reset()
{
if (useHash)
{
map.Clear();
useHash = false;
}
count = 0;
}
public void Sort()
{
// Tim sort performs well on already sorted arrays:
if (count > 1)
{
ArrayUtil.TimSort(points, 0, count);
}
}
public void Add(Transition t)
{
Find(t.min).starts.Add(t);
Find(1 + t.max).ends.Add(t);
}
public override string ToString()
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < count; i++)
{
if (i > 0)
{
s.Append(' ');
}
s.Append(points[i].point).Append(':').Append(points[i].starts.count).Append(',').Append(points[i].ends.count);
}
return s.ToString();
}
}
/// <summary>
/// Determinizes the given automaton.
/// <para/>
/// Worst case complexity: exponential in number of states.
/// </summary>
public static void Determinize(Automaton a)
{
if (a.IsDeterministic || a.IsSingleton)
{
return;
}
State[] allStates = a.GetNumberedStates();
// subset construction
bool initAccept = a.initial.accept;
int initNumber = a.initial.number;
a.initial = new State();
SortedInt32Set.FrozenInt32Set initialset = new SortedInt32Set.FrozenInt32Set(initNumber, a.initial);
Queue<SortedInt32Set.FrozenInt32Set> worklist = new Queue<SortedInt32Set.FrozenInt32Set>(); // LUCENENET specific - Queue is much more performant than LinkedList
IDictionary<SortedInt32Set.FrozenInt32Set, State> newstate = new Dictionary<SortedInt32Set.FrozenInt32Set, State>();
worklist.Enqueue(initialset);
a.initial.accept = initAccept;
newstate[initialset] = a.initial;
int newStateUpto = 0;
State[] newStatesArray = new State[5];
newStatesArray[newStateUpto] = a.initial;
a.initial.number = newStateUpto;
newStateUpto++;
// like Set<Integer,PointTransitions>
PointTransitionSet points = new PointTransitionSet();
// like SortedMap<Integer,Integer>
SortedInt32Set statesSet = new SortedInt32Set(5);
while (worklist.Count > 0)
{
SortedInt32Set.FrozenInt32Set s = worklist.Dequeue();
//worklist.Remove(s);
// Collate all outgoing transitions by min/1+max:
for (int i = 0; i < s.values.Length; i++)
{
State s0 = allStates[s.values[i]];
for (int j = 0; j < s0.numTransitions; j++)
{
points.Add(s0.TransitionsArray[j]);
}
}
if (points.count == 0)
{
// No outgoing transitions -- skip it
continue;
}
points.Sort();
int lastPoint = -1;
int accCount = 0;
State r = s.state;
for (int i = 0; i < points.count; i++)
{
int point = points.points[i].point;
if (statesSet.upto > 0)
{
if (Debugging.AssertsEnabled) Debugging.Assert(lastPoint != -1);
statesSet.ComputeHash();
if (!newstate.TryGetValue(statesSet.ToFrozenInt32Set(), out State q) || q == null)
{
q = new State();
SortedInt32Set.FrozenInt32Set p = statesSet.Freeze(q);
worklist.Enqueue(p);
if (newStateUpto == newStatesArray.Length)
{
// LUCENENET: Resize rather than copy
Array.Resize(ref newStatesArray, ArrayUtil.Oversize(1 + newStateUpto, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
}
newStatesArray[newStateUpto] = q;
q.number = newStateUpto;
newStateUpto++;
q.accept = accCount > 0;
newstate[p] = q;
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert((accCount > 0) == q.accept, () => "accCount=" + accCount + " vs existing accept=" + q.accept + " states=" + statesSet);
}
r.AddTransition(new Transition(lastPoint, point - 1, q));
}
// process transitions that end on this point
// (closes an overlapping interval)
Transition[] transitions = points.points[i].ends.transitions;
int limit = points.points[i].ends.count;
for (int j = 0; j < limit; j++)
{
Transition t = transitions[j];
int num = t.to.number;
statesSet.Decr(num);
accCount -= t.to.accept ? 1 : 0;
}
points.points[i].ends.count = 0;
// process transitions that start on this point
// (opens a new interval)
transitions = points.points[i].starts.transitions;
limit = points.points[i].starts.count;
for (int j = 0; j < limit; j++)
{
Transition t = transitions[j];
int num = t.to.number;
statesSet.Incr(num);
accCount += t.to.accept ? 1 : 0;
}
lastPoint = point;
points.points[i].starts.count = 0;
}
points.Reset();
if (Debugging.AssertsEnabled) Debugging.Assert(statesSet.upto == 0, () => "upto=" + statesSet.upto);
}
a.deterministic = true;
a.SetNumberedStates(newStatesArray, newStateUpto);
}
/// <summary>
/// Adds epsilon transitions to the given automaton. This method adds extra
/// character interval transitions that are equivalent to the given set of
/// epsilon transitions.
/// </summary>
/// <param name="a"> Automaton. </param>
/// <param name="pairs"> Collection of <see cref="StatePair"/> objects representing pairs of
/// source/destination states where epsilon transitions should be
/// added. </param>
public static void AddEpsilons(Automaton a, ICollection<StatePair> pairs)
{
a.ExpandSingleton();
Dictionary<State, JCG.HashSet<State>> forward = new Dictionary<State, JCG.HashSet<State>>();
Dictionary<State, JCG.HashSet<State>> back = new Dictionary<State, JCG.HashSet<State>>();
foreach (StatePair p in pairs)
{
if (!forward.TryGetValue(p.s1, out JCG.HashSet<State> to))
{
to = new JCG.HashSet<State>();
forward[p.s1] = to;
}
to.Add(p.s2);
if (!back.TryGetValue(p.s2, out JCG.HashSet<State> from))
{
from = new JCG.HashSet<State>();
back[p.s2] = from;
}
from.Add(p.s1);
}
// calculate epsilon closure
LinkedList<StatePair> worklist = new LinkedList<StatePair>(pairs);
JCG.HashSet<StatePair> workset = new JCG.HashSet<StatePair>(pairs);
while (worklist.Count > 0)
{
StatePair p = worklist.First.Value;
worklist.Remove(p);
workset.Remove(p);
#pragma warning disable IDE0018 // Inline variable declaration
JCG.HashSet<State> from;
#pragma warning restore IDE0018 // Inline variable declaration
if (forward.TryGetValue(p.s2, out JCG.HashSet<State> to))
{
foreach (State s in to)
{
StatePair pp = new StatePair(p.s1, s);
if (!pairs.Contains(pp))
{
pairs.Add(pp);
forward[p.s1].Add(s);
back[s].Add(p.s1);
worklist.AddLast(pp);
workset.Add(pp);
if (back.TryGetValue(p.s1, out from))
{
foreach (State q in from)
{
StatePair qq = new StatePair(q, p.s1);
if (!workset.Contains(qq))
{
worklist.AddLast(qq);
workset.Add(qq);
}
}
}
}
}
}
}
// add transitions
foreach (StatePair p in pairs)
{
p.s1.AddEpsilon(p.s2);
}
a.deterministic = false;
//a.clearHashCode();
a.ClearNumberedStates();
a.CheckMinimizeAlways();
}
/// <summary>
/// Returns <c>true</c> if the given automaton accepts the empty string and nothing
/// else.
/// </summary>
public static bool IsEmptyString(Automaton a)
{
if (a.IsSingleton)
{
return a.singleton.Length == 0;
}
else
{
return a.initial.accept && a.initial.NumTransitions == 0;
}
}
/// <summary>
/// Returns <c>true</c> if the given automaton accepts no strings.
/// </summary>
public static bool IsEmpty(Automaton a)
{
if (a.IsSingleton)
{
return false;
}
return !a.initial.accept && a.initial.NumTransitions == 0;
}
/// <summary>
/// Returns <c>true</c> if the given automaton accepts all strings.
/// </summary>
public static bool IsTotal(Automaton a)
{
if (a.IsSingleton)
{
return false;
}
if (a.initial.accept && a.initial.NumTransitions == 1)
{
Transition t = a.initial.GetTransitions().First();
return t.to == a.initial && t.min == Character.MinCodePoint && t.max == Character.MaxCodePoint;
}
return false;
}
/// <summary>
/// Returns <c>true</c> if the given string is accepted by the automaton.
/// <para/>
/// Complexity: linear in the length of the string.
/// <para/>
/// <b>Note:</b> for full performance, use the <see cref="RunAutomaton"/> class.
/// </summary>
public static bool Run(Automaton a, string s)
{
if (a.IsSingleton)
{
return s.Equals(a.singleton, StringComparison.Ordinal);
}
if (a.deterministic)
{
State p = a.initial;
int cp; // LUCENENET: Removed unnecessary assignment
for (int i = 0; i < s.Length; i += Character.CharCount(cp))
{
State q = p.Step(cp = Character.CodePointAt(s, i));
if (q == null)
{
return false;
}
p = q;
}
return p.accept;
}
else
{
State[] states = a.GetNumberedStates();
LinkedList<State> pp = new LinkedList<State>();
LinkedList<State> pp_other = new LinkedList<State>();
OpenBitSet bb = new OpenBitSet(states.Length);
OpenBitSet bb_other = new OpenBitSet(states.Length);
pp.AddLast(a.initial);
List<State> dest = new List<State>();
bool accept = a.initial.accept;
int c; // LUCENENET: Removed unnecessary assignment
for (int i = 0; i < s.Length; i += Character.CharCount(c))
{
c = Character.CodePointAt(s, i);
accept = false;
pp_other.Clear();
bb_other.Clear(0, bb_other.Length - 1);
foreach (State p in pp)
{
dest.Clear();
p.Step(c, dest);
foreach (State q in dest)
{
if (q.accept)
{
accept = true;
}
if (!bb_other.Get(q.number))
{
bb_other.Set(q.number);
pp_other.AddLast(q);
}
}
}
LinkedList<State> tp = pp;
pp = pp_other;
pp_other = tp;
OpenBitSet tb = bb;
bb = bb_other;
bb_other = tb;
}
return accept;
}
}
}
}
| |
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 Forum.WebApi.Areas.HelpPage.ModelDescriptions;
using Forum.WebApi.Areas.HelpPage.Models;
namespace Forum.WebApi.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.ComponentModel.DataAnnotations;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Cache;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Editors;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Mail;
using Umbraco.Cms.Core.Mapping;
using Umbraco.Cms.Core.Media;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.ContentEditing;
using Umbraco.Cms.Core.Models.Email;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Security;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure;
using Umbraco.Cms.Infrastructure.Persistence;
using Umbraco.Cms.Web.BackOffice.ActionResults;
using Umbraco.Cms.Web.BackOffice.Extensions;
using Umbraco.Cms.Web.BackOffice.Filters;
using Umbraco.Cms.Web.BackOffice.ModelBinders;
using Umbraco.Cms.Web.BackOffice.Security;
using Umbraco.Cms.Web.Common.ActionsResults;
using Umbraco.Cms.Web.Common.Attributes;
using Umbraco.Cms.Web.Common.Authorization;
using Umbraco.Cms.Web.Common.Security;
using Umbraco.Extensions;
using Constants = Umbraco.Cms.Core.Constants;
namespace Umbraco.Cms.Web.BackOffice.Controllers
{
[PluginController(Constants.Web.Mvc.BackOfficeApiArea)]
[Authorize(Policy = AuthorizationPolicies.SectionAccessUsers)]
[PrefixlessBodyModelValidator]
[IsCurrentUserModelFilter]
public class UsersController : BackOfficeNotificationsController
{
private readonly MediaFileManager _mediaFileManager;
private readonly ContentSettings _contentSettings;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly ISqlContext _sqlContext;
private readonly IImageUrlGenerator _imageUrlGenerator;
private readonly SecuritySettings _securitySettings;
private readonly IEmailSender _emailSender;
private readonly IBackOfficeSecurityAccessor _backofficeSecurityAccessor;
private readonly AppCaches _appCaches;
private readonly IShortStringHelper _shortStringHelper;
private readonly IUserService _userService;
private readonly ILocalizedTextService _localizedTextService;
private readonly IUmbracoMapper _umbracoMapper;
private readonly GlobalSettings _globalSettings;
private readonly IBackOfficeUserManager _userManager;
private readonly ILoggerFactory _loggerFactory;
private readonly LinkGenerator _linkGenerator;
private readonly IBackOfficeExternalLoginProviders _externalLogins;
private readonly UserEditorAuthorizationHelper _userEditorAuthorizationHelper;
private readonly IPasswordChanger<BackOfficeIdentityUser> _passwordChanger;
private readonly ILogger<UsersController> _logger;
public UsersController(
MediaFileManager mediaFileManager,
IOptions<ContentSettings> contentSettings,
IHostingEnvironment hostingEnvironment,
ISqlContext sqlContext,
IImageUrlGenerator imageUrlGenerator,
IOptions<SecuritySettings> securitySettings,
IEmailSender emailSender,
IBackOfficeSecurityAccessor backofficeSecurityAccessor,
AppCaches appCaches,
IShortStringHelper shortStringHelper,
IUserService userService,
ILocalizedTextService localizedTextService,
IUmbracoMapper umbracoMapper,
IOptions<GlobalSettings> globalSettings,
IBackOfficeUserManager backOfficeUserManager,
ILoggerFactory loggerFactory,
LinkGenerator linkGenerator,
IBackOfficeExternalLoginProviders externalLogins,
UserEditorAuthorizationHelper userEditorAuthorizationHelper,
IPasswordChanger<BackOfficeIdentityUser> passwordChanger)
{
_mediaFileManager = mediaFileManager;
_contentSettings = contentSettings.Value;
_hostingEnvironment = hostingEnvironment;
_sqlContext = sqlContext;
_imageUrlGenerator = imageUrlGenerator;
_securitySettings = securitySettings.Value;
_emailSender = emailSender;
_backofficeSecurityAccessor = backofficeSecurityAccessor;
_appCaches = appCaches;
_shortStringHelper = shortStringHelper;
_userService = userService;
_localizedTextService = localizedTextService;
_umbracoMapper = umbracoMapper;
_globalSettings = globalSettings.Value;
_userManager = backOfficeUserManager;
_loggerFactory = loggerFactory;
_linkGenerator = linkGenerator;
_externalLogins = externalLogins;
_userEditorAuthorizationHelper = userEditorAuthorizationHelper;
_passwordChanger = passwordChanger;
_logger = _loggerFactory.CreateLogger<UsersController>();
}
/// <summary>
/// Returns a list of the sizes of gravatar URLs for the user or null if the gravatar server cannot be reached
/// </summary>
/// <returns></returns>
public ActionResult<string[]> GetCurrentUserAvatarUrls()
{
var urls = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileManager, _imageUrlGenerator);
if (urls == null)
return ValidationProblem("Could not access Gravatar endpoint");
return urls;
}
[AppendUserModifiedHeader("id")]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostSetAvatar(int id, IList<IFormFile> file)
{
return PostSetAvatarInternal(file, _userService, _appCaches.RuntimeCache, _mediaFileManager, _shortStringHelper, _contentSettings, _hostingEnvironment, _imageUrlGenerator, id);
}
internal static IActionResult PostSetAvatarInternal(IList<IFormFile> files, IUserService userService, IAppCache cache, MediaFileManager mediaFileManager, IShortStringHelper shortStringHelper, ContentSettings contentSettings, IHostingEnvironment hostingEnvironment, IImageUrlGenerator imageUrlGenerator, int id)
{
if (files is null)
{
return new UnsupportedMediaTypeResult();
}
var root = hostingEnvironment.MapPathContentRoot(Constants.SystemDirectories.TempFileUploads);
//ensure it exists
Directory.CreateDirectory(root);
//must have a file
if (files.Count == 0)
{
return new NotFoundResult();
}
var user = userService.GetUserById(id);
if (user == null)
return new NotFoundResult();
if (files.Count > 1)
return new ValidationErrorResult("The request was not formatted correctly, only one file can be attached to the request");
//get the file info
var file = files.First();
var fileName = file.FileName.Trim(new[] { '\"' }).TrimEnd();
var safeFileName = fileName.ToSafeFileName(shortStringHelper);
var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower();
if (contentSettings.DisallowedUploadFiles.Contains(ext) == false)
{
//generate a path of known data, we don't want this path to be guessable
user.Avatar = "UserAvatars/" + (user.Id + safeFileName).GenerateHash<SHA1>() + "." + ext;
using (var fs = file.OpenReadStream())
{
mediaFileManager.FileSystem.AddFile(user.Avatar, fs, true);
}
userService.Save(user);
}
return new OkObjectResult(user.GetUserAvatarUrls(cache, mediaFileManager, imageUrlGenerator));
}
[AppendUserModifiedHeader("id")]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public ActionResult<string[]> PostClearAvatar(int id)
{
var found = _userService.GetUserById(id);
if (found == null)
return NotFound();
var filePath = found.Avatar;
//if the filePath is already null it will mean that the user doesn't have a custom avatar and their gravatar is currently
//being used (if they have one). This means they want to remove their gravatar too which we can do by setting a special value
//for the avatar.
if (filePath.IsNullOrWhiteSpace() == false)
{
found.Avatar = null;
}
else
{
//set a special value to indicate to not have any avatar
found.Avatar = "none";
}
_userService.Save(found);
if (filePath.IsNullOrWhiteSpace() == false)
{
if (_mediaFileManager.FileSystem.FileExists(filePath))
_mediaFileManager.FileSystem.DeleteFile(filePath);
}
return found.GetUserAvatarUrls(_appCaches.RuntimeCache, _mediaFileManager, _imageUrlGenerator);
}
/// <summary>
/// Gets a user by Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public ActionResult<UserDisplay> GetById(int id)
{
var user = _userService.GetUserById(id);
if (user == null)
{
return NotFound();
}
var result = _umbracoMapper.Map<IUser, UserDisplay>(user);
return result;
}
/// <summary>
/// Get users by integer ids
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public ActionResult<IEnumerable<UserDisplay>> GetByIds([FromJsonPath]int[] ids)
{
if (ids == null)
{
return NotFound();
}
if (ids.Length == 0)
return Enumerable.Empty<UserDisplay>().ToList();
var users = _userService.GetUsersById(ids);
if (users == null)
{
return NotFound();
}
var result = _umbracoMapper.MapEnumerable<IUser, UserDisplay>(users);
return result;
}
/// <summary>
/// Returns a paged users collection
/// </summary>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="userGroups"></param>
/// <param name="userStates"></param>
/// <param name="filter"></param>
/// <returns></returns>
public PagedUserResult GetPagedUsers(
int pageNumber = 1,
int pageSize = 10,
string orderBy = "username",
Direction orderDirection = Direction.Ascending,
[FromQuery]string[] userGroups = null,
[FromQuery]UserState[] userStates = null,
string filter = "")
{
//following the same principle we had in previous versions, we would only show admins to admins, see
// https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Web/umbraco.presentation/umbraco/Trees/loadUsers.cs#L91
// so to do that here, we'll need to check if this current user is an admin and if not we should exclude all user who are
// also admins
var hideDisabledUsers = _securitySettings.HideDisabledUsersInBackOffice;
var excludeUserGroups = new string[0];
var isAdmin = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsAdmin();
if (isAdmin == false)
{
//this user is not an admin so in that case we need to exclude all admin users
excludeUserGroups = new[] {Constants.Security.AdminGroupAlias};
}
var filterQuery = _sqlContext.Query<IUser>();
if (!_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.IsSuper())
{
// only super can see super - but don't use IsSuper, cannot be mapped to SQL
//filterQuery.Where(x => !x.IsSuper());
filterQuery.Where(x => x.Id != Constants.Security.SuperUserId);
}
if (filter.IsNullOrWhiteSpace() == false)
{
filterQuery.Where(x => x.Name.Contains(filter) || x.Username.Contains(filter));
}
if (hideDisabledUsers)
{
if (userStates == null || userStates.Any() == false)
{
userStates = new[] { UserState.Active, UserState.Invited, UserState.LockedOut, UserState.Inactive };
}
}
long pageIndex = pageNumber - 1;
long total;
var result = _userService.GetAll(pageIndex, pageSize, out total, orderBy, orderDirection, userStates, userGroups, excludeUserGroups, filterQuery);
var paged = new PagedUserResult(total, pageNumber, pageSize)
{
Items = _umbracoMapper.MapEnumerable<IUser, UserBasic>(result),
UserStates = _userService.GetUserStates()
};
return paged;
}
/// <summary>
/// Creates a new user
/// </summary>
/// <param name="userSave"></param>
/// <returns></returns>
public async Task<ActionResult<UserDisplay>> PostCreateUser(UserInvite userSave)
{
if (userSave == null) throw new ArgumentNullException("userSave");
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
if (_securitySettings.UsernameIsEmail)
{
//ensure they are the same if we're using it
userSave.Username = userSave.Email;
}
else
{
//first validate the username if were showing it
CheckUniqueUsername(userSave.Username, null);
}
CheckUniqueEmail(userSave.Email, null);
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
//Perform authorization here to see if the current user can actually save this user with the info being requested
var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, null, null, null, userSave.UserGroups);
if (canSaveUser == false)
{
return Unauthorized(canSaveUser.Result);
}
//we want to create the user with the UserManager, this ensures the 'empty' (special) password
//format is applied without us having to duplicate that logic
var identityUser = BackOfficeIdentityUser.CreateNew(_globalSettings, userSave.Username, userSave.Email, _globalSettings.DefaultUILanguage);
identityUser.Name = userSave.Name;
var created = await _userManager.CreateAsync(identityUser);
if (created.Succeeded == false)
{
return ValidationProblem(created.Errors.ToErrorMessage());
}
string resetPassword;
var password = _userManager.GeneratePassword();
var result = await _userManager.AddPasswordAsync(identityUser, password);
if (result.Succeeded == false)
{
return ValidationProblem(created.Errors.ToErrorMessage());
}
resetPassword = password;
//now re-look the user back up which will now exist
var user = _userService.GetByEmail(userSave.Email);
//map the save info over onto the user
user = _umbracoMapper.Map(userSave, user);
//since the back office user is creating this user, they will be set to approved
user.IsApproved = true;
_userService.Save(user);
var display = _umbracoMapper.Map<UserDisplay>(user);
display.ResetPasswordValue = resetPassword;
return display;
}
/// <summary>
/// Invites a user
/// </summary>
/// <param name="userSave"></param>
/// <returns></returns>
/// <remarks>
/// This will email the user an invite and generate a token that will be validated in the email
/// </remarks>
public async Task<ActionResult<UserDisplay>> PostInviteUser(UserInvite userSave)
{
if (userSave == null) throw new ArgumentNullException("userSave");
if (userSave.Message.IsNullOrWhiteSpace())
ModelState.AddModelError("Message", "Message cannot be empty");
IUser user;
if (_securitySettings.UsernameIsEmail)
{
//ensure it's the same
userSave.Username = userSave.Email;
}
else
{
//first validate the username if we're showing it
var userResult = CheckUniqueUsername(userSave.Username, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue);
if (!(userResult.Result is null))
{
return userResult.Result;
}
user = userResult.Value;
}
user = CheckUniqueEmail(userSave.Email, u => u.LastLoginDate != default || u.EmailConfirmedDate.HasValue);
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
if (!_emailSender.CanSendRequiredEmail())
{
return ValidationProblem("No Email server is configured");
}
//Perform authorization here to see if the current user can actually save this user with the info being requested
var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, user, null, null, userSave.UserGroups);
if (canSaveUser == false)
{
return ValidationProblem(canSaveUser.Result, StatusCodes.Status401Unauthorized);
}
if (user == null)
{
//we want to create the user with the UserManager, this ensures the 'empty' (special) password
//format is applied without us having to duplicate that logic
var identityUser = BackOfficeIdentityUser.CreateNew(_globalSettings, userSave.Username, userSave.Email, _globalSettings.DefaultUILanguage);
identityUser.Name = userSave.Name;
var created = await _userManager.CreateAsync(identityUser);
if (created.Succeeded == false)
{
return ValidationProblem(created.Errors.ToErrorMessage());
}
//now re-look the user back up
user = _userService.GetByEmail(userSave.Email);
}
//map the save info over onto the user
user = _umbracoMapper.Map(userSave, user);
//ensure the invited date is set
user.InvitedDate = DateTime.Now;
//Save the updated user (which will process the user groups too)
_userService.Save(user);
var display = _umbracoMapper.Map<UserDisplay>(user);
//send the email
await SendUserInviteEmailAsync(display, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Name, _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser.Email, user, userSave.Message);
display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles","resendInviteHeader"), _localizedTextService.Localize("speechBubbles","resendInviteSuccess", new[] { user.Name }));
return display;
}
private IUser CheckUniqueEmail(string email, Func<IUser, bool> extraCheck)
{
var user = _userService.GetByEmail(email);
if (user != null && (extraCheck == null || extraCheck(user)))
{
ModelState.AddModelError("Email", "A user with the email already exists");
}
return user;
}
private ActionResult<IUser> CheckUniqueUsername(string username, Func<IUser, bool> extraCheck)
{
var user = _userService.GetByUsername(username);
if (user != null && (extraCheck == null || extraCheck(user)))
{
ModelState.AddModelError(
_securitySettings.UsernameIsEmail ? "Email" : "Username",
"A user with the username already exists");
return ValidationProblem(ModelState);
}
return new ActionResult<IUser>(user);
}
private async Task SendUserInviteEmailAsync(UserBasic userDisplay, string from, string fromEmail, IUser to, string message)
{
var user = await _userManager.FindByIdAsync(((int) userDisplay.Id).ToString());
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
// Use info from SMTP Settings if configured, otherwise set fromEmail as fallback
var senderEmail = !string.IsNullOrEmpty(_globalSettings.Smtp?.From) ? _globalSettings.Smtp.From : fromEmail;
var inviteToken = string.Format("{0}{1}{2}",
(int)userDisplay.Id,
WebUtility.UrlEncode("|"),
token.ToUrlBase64());
// Get an mvc helper to get the URL
var action = _linkGenerator.GetPathByAction(
nameof(BackOfficeController.VerifyInvite),
ControllerExtensions.GetControllerName<BackOfficeController>(),
new
{
area = Constants.Web.Mvc.BackOfficeArea,
invite = inviteToken
});
// Construct full URL using configured application URL (which will fall back to request)
var applicationUri = _hostingEnvironment.ApplicationMainUrl;
var inviteUri = new Uri(applicationUri, action);
var emailSubject = _localizedTextService.Localize("user","inviteEmailCopySubject",
//Ensure the culture of the found user is used for the email!
UmbracoUserExtensions.GetUserCulture(to.Language, _localizedTextService, _globalSettings));
var emailBody = _localizedTextService.Localize("user","inviteEmailCopyFormat",
//Ensure the culture of the found user is used for the email!
UmbracoUserExtensions.GetUserCulture(to.Language, _localizedTextService, _globalSettings),
new[] { userDisplay.Name, from, message, inviteUri.ToString(), senderEmail });
// This needs to be in the correct mailto format including the name, else
// the name cannot be captured in the email sending notification.
// i.e. "Some Person" <hello@example.com>
var toMailBoxAddress = new MailboxAddress(to.Name, to.Email);
var mailMessage = new EmailMessage(senderEmail, toMailBoxAddress.ToString(), emailSubject, emailBody, true);
await _emailSender.SendAsync(mailMessage, Constants.Web.EmailTypes.UserInvite, true);
}
/// <summary>
/// Saves a user
/// </summary>
/// <param name="userSave"></param>
/// <returns></returns>
[OutgoingEditorModelEvent]
public ActionResult<UserDisplay> PostSaveUser(UserSave userSave)
{
if (userSave == null) throw new ArgumentNullException(nameof(userSave));
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
var found = _userService.GetUserById(userSave.Id);
if (found == null)
return NotFound();
//Perform authorization here to see if the current user can actually save this user with the info being requested
var canSaveUser = _userEditorAuthorizationHelper.IsAuthorized(_backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser, found, userSave.StartContentIds, userSave.StartMediaIds, userSave.UserGroups);
if (canSaveUser == false)
{
return Unauthorized(canSaveUser.Result);
}
var hasErrors = false;
// we need to check if there's any Deny Local login providers present, if so we need to ensure that the user's email address cannot be changed
var hasDenyLocalLogin = _externalLogins.HasDenyLocalLogin();
if (hasDenyLocalLogin)
{
userSave.Email = found.Email; // it cannot change, this would only happen if people are mucking around with the request
}
var existing = _userService.GetByEmail(userSave.Email);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Email", "A user with the email already exists");
hasErrors = true;
}
existing = _userService.GetByUsername(userSave.Username);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Username", "A user with the username already exists");
hasErrors = true;
}
// going forward we prefer to align usernames with email, so we should cross-check to make sure
// the email or username isn't somehow being used by anyone.
existing = _userService.GetByEmail(userSave.Username);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Username", "A user using this as their email already exists");
hasErrors = true;
}
existing = _userService.GetByUsername(userSave.Email);
if (existing != null && existing.Id != userSave.Id)
{
ModelState.AddModelError("Email", "A user using this as their username already exists");
hasErrors = true;
}
// if the found user has their email for username, we want to keep this synced when changing the email.
// we have already cross-checked above that the email isn't colliding with anything, so we can safely assign it here.
if (_securitySettings.UsernameIsEmail && found.Username == found.Email && userSave.Username != userSave.Email)
{
userSave.Username = userSave.Email;
}
if (hasErrors)
return ValidationProblem(ModelState);
//merge the save data onto the user
var user = _umbracoMapper.Map(userSave, found);
_userService.Save(user);
var display = _umbracoMapper.Map<UserDisplay>(user);
// determine if the user has changed their own language;
var currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
var userHasChangedOwnLanguage =
user.Id == currentUser.Id && currentUser.Language != user.Language;
var textToLocalise = userHasChangedOwnLanguage ? "operationSavedHeaderReloadUser" : "operationSavedHeader";
var culture = userHasChangedOwnLanguage
? CultureInfo.GetCultureInfo(user.Language)
: Thread.CurrentThread.CurrentUICulture;
display.AddSuccessNotification(_localizedTextService.Localize("speechBubbles", textToLocalise, culture), _localizedTextService.Localize("speechBubbles","editUserSaved", culture));
return display;
}
/// <summary>
///
/// </summary>
/// <param name="changingPasswordModel"></param>
/// <returns></returns>
public async Task<ActionResult<ModelWithNotifications<string>>> PostChangePassword(ChangingPasswordModel changingPasswordModel)
{
changingPasswordModel = changingPasswordModel ?? throw new ArgumentNullException(nameof(changingPasswordModel));
if (ModelState.IsValid == false)
{
return ValidationProblem(ModelState);
}
IUser found = _userService.GetUserById(changingPasswordModel.Id);
if (found == null)
{
return NotFound();
}
IUser currentUser = _backofficeSecurityAccessor.BackOfficeSecurity.CurrentUser;
// if it's the current user, the current user cannot reset their own password without providing their old password
if (currentUser.Username == found.Username && string.IsNullOrEmpty(changingPasswordModel.OldPassword))
{
return ValidationProblem("Password reset is not allowed without providing old password");
}
if (!currentUser.IsAdmin() && found.IsAdmin())
{
return ValidationProblem("The current user cannot change the password for the specified user");
}
Attempt<PasswordChangedModel> passwordChangeResult = await _passwordChanger.ChangePasswordWithIdentityAsync(changingPasswordModel, _userManager);
if (passwordChangeResult.Success)
{
var result = new ModelWithNotifications<string>(passwordChangeResult.Result.ResetPassword);
result.AddSuccessNotification(_localizedTextService.Localize("general","success"), _localizedTextService.Localize("user","passwordChangedGeneric"));
return result;
}
foreach (string memberName in passwordChangeResult.Result.ChangeError.MemberNames)
{
ModelState.AddModelError(memberName, passwordChangeResult.Result.ChangeError.ErrorMessage);
}
return ValidationProblem(ModelState);
}
/// <summary>
/// Disables the users with the given user ids
/// </summary>
/// <param name="userIds"></param>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostDisableUsers([FromQuery]int[] userIds)
{
var tryGetCurrentUserId = _backofficeSecurityAccessor.BackOfficeSecurity.GetUserId();
if (tryGetCurrentUserId && userIds.Contains(tryGetCurrentUserId.Result))
{
return ValidationProblem("The current user cannot disable itself");
}
var users = _userService.GetUsersById(userIds).ToArray();
foreach (var u in users)
{
u.IsApproved = false;
u.InvitedDate = null;
}
_userService.Save(users);
if (users.Length > 1)
{
return Ok(_localizedTextService.Localize("speechBubbles","disableUsersSuccess", new[] {userIds.Length.ToString()}));
}
return Ok(_localizedTextService.Localize("speechBubbles","disableUserSuccess", new[] { users[0].Name }));
}
/// <summary>
/// Enables the users with the given user ids
/// </summary>
/// <param name="userIds"></param>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostEnableUsers([FromQuery]int[] userIds)
{
var users = _userService.GetUsersById(userIds).ToArray();
foreach (var u in users)
{
u.IsApproved = true;
}
_userService.Save(users);
if (users.Length > 1)
{
return Ok(
_localizedTextService.Localize("speechBubbles","enableUsersSuccess", new[] { userIds.Length.ToString() }));
}
return Ok(
_localizedTextService.Localize("speechBubbles","enableUserSuccess", new[] { users[0].Name }));
}
/// <summary>
/// Unlocks the users with the given user ids
/// </summary>
/// <param name="userIds"></param>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public async Task<IActionResult> PostUnlockUsers([FromQuery]int[] userIds)
{
if (userIds.Length <= 0) return Ok();
var notFound = new List<int>();
foreach (var u in userIds)
{
var user = await _userManager.FindByIdAsync(u.ToString());
if (user == null)
{
notFound.Add(u);
continue;
}
var unlockResult = await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now.AddMinutes(-1));
if (unlockResult.Succeeded == false)
{
return ValidationProblem(
$"Could not unlock for user {u} - error {unlockResult.Errors.ToErrorMessage()}");
}
if (userIds.Length == 1)
{
return Ok(
_localizedTextService.Localize("speechBubbles","unlockUserSuccess", new[] {user.Name}));
}
}
return Ok(
_localizedTextService.Localize("speechBubbles","unlockUsersSuccess", new[] {(userIds.Length - notFound.Count).ToString()}));
}
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostSetUserGroupsOnUsers([FromQuery]string[] userGroupAliases, [FromQuery]int[] userIds)
{
var users = _userService.GetUsersById(userIds).ToArray();
var userGroups = _userService.GetUserGroupsByAlias(userGroupAliases).Select(x => x.ToReadOnlyGroup()).ToArray();
foreach (var u in users)
{
u.ClearGroups();
foreach (var userGroup in userGroups)
{
u.AddGroup(userGroup);
}
}
_userService.Save(users);
return Ok(
_localizedTextService.Localize("speechBubbles","setUserGroupOnUsersSuccess"));
}
/// <summary>
/// Deletes the non-logged in user provided id
/// </summary>
/// <param name="id">User Id</param>
/// <remarks>
/// Limited to users that haven't logged in to avoid issues with related records constrained
/// with a foreign key on the user Id
/// </remarks>
[Authorize(Policy = AuthorizationPolicies.AdminUserEditsRequireAdmin)]
public IActionResult PostDeleteNonLoggedInUser(int id)
{
var user = _userService.GetUserById(id);
if (user == null)
{
return NotFound();
}
// Check user hasn't logged in. If they have they may have made content changes which will mean
// the Id is associated with audit trails, versions etc. and can't be removed.
if (user.LastLoginDate != default(DateTime))
{
return BadRequest();
}
var userName = user.Name;
_userService.Delete(user, true);
return Ok(
_localizedTextService.Localize("speechBubbles","deleteUserSuccess", new[] { userName }));
}
public class PagedUserResult : PagedResult<UserBasic>
{
public PagedUserResult(long totalItems, long pageNumber, long pageSize) : base(totalItems, pageNumber, pageSize)
{
UserStates = new Dictionary<UserState, int>();
}
/// <summary>
/// This is basically facets of UserStates key = state, value = count
/// </summary>
[DataMember(Name = "userStates")]
public IDictionary<UserState, int> UserStates { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel;
using System.DirectoryServices.ActiveDirectory;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Xunit;
namespace System.Diagnostics.Tests
{
public partial class ProcessTests : ProcessTestBase
{
private class FinalizingProcess : Process
{
public static volatile bool WasFinalized;
public static void CreateAndRelease()
{
new FinalizingProcess();
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
WasFinalized = true;
}
base.Dispose(disposing);
}
}
private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority)
{
_process.PriorityClass = exPriorityClass;
_process.Refresh();
Assert.Equal(priority, _process.BasePriority);
}
private void AssertNonZeroWindowsZeroUnix(long value)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.NotEqual(0, value);
}
else
{
Assert.Equal(0, value);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestBasePriorityOnWindows()
{
CreateDefaultProcess();
ProcessPriorityClass originalPriority = _process.PriorityClass;
var expected = PlatformDetection.IsWindowsNanoServer ? ProcessPriorityClass.BelowNormal : ProcessPriorityClass.Normal; // For some reason we're BelowNormal initially on Nano
Assert.Equal(expected, originalPriority);
try
{
// We are not checking for RealTime case here, as RealTime priority process can
// preempt the threads of all other processes, including operating system processes
// performing important tasks, which may cause the machine to be unresponsive.
//SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24);
SetAndCheckBasePriority(ProcessPriorityClass.High, 13);
SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4);
SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8);
}
finally
{
_process.PriorityClass = originalPriority;
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[InlineData(null)]
public void TestEnableRaiseEvents(bool? enable)
{
bool exitedInvoked = false;
Process p = CreateProcessLong();
if (enable.HasValue)
{
p.EnableRaisingEvents = enable.Value;
}
p.Exited += delegate { exitedInvoked = true; };
StartSleepKillWait(p);
if (enable.GetValueOrDefault())
{
// There's no guarantee that the Exited callback will be invoked by
// the time Process.WaitForExit completes, though it's extremely likely.
// There could be a race condition where WaitForExit is returning from
// its wait and sees that the callback is already running asynchronously,
// at which point it returns to the caller even if the callback hasn't
// entirely completed. As such, we spin until the value is set.
Assert.True(SpinWait.SpinUntil(() => exitedInvoked, WaitInMS));
}
else
{
Assert.False(exitedInvoked);
}
}
[Fact]
public void ProcessStart_TryExitCommandAsFileName_ThrowsWin32Exception()
{
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = "exit", Arguments = "42" }));
}
[Fact]
public void ProcessStart_UseShellExecuteFalse_FilenameIsUrl_ThrowsWin32Exception()
{
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = "https://www.github.com/corefx" }));
}
[Fact]
public void ProcessStart_TryOpenFolder_UseShellExecuteIsFalse_ThrowsWin32Exception()
{
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = false, FileName = Path.GetTempPath() }));
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // OSX doesn't support throwing on Process.Start
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // UWP overrides WorkingDirectory (https://github.com/dotnet/corefx/pull/25266#issuecomment-347719832).
public void TestStartWithBadWorkingDirectory()
{
string program;
string workingDirectory;
if (PlatformDetection.IsWindows)
{
program = "powershell.exe";
workingDirectory = @"C:\does-not-exist";
}
else
{
program = "uname";
workingDirectory = "/does-not-exist";
}
if (IsProgramInstalled(program))
{
var psi = new ProcessStartInfo
{
FileName = program,
UseShellExecute = false,
WorkingDirectory = workingDirectory
};
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(psi));
Assert.NotEqual(0, e.NativeErrorCode);
}
else
{
Console.WriteLine($"Program {program} is not installed on this machine.");
}
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.HasWindowsShell))]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "not supported on UAP")]
[OuterLoop("Launches File Explorer")]
public void ProcessStart_UseShellExecuteTrue_OpenMissingFile_Throws()
{
string fileToOpen = Path.Combine(Environment.CurrentDirectory, "_no_such_file.TXT");
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }));
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.HasWindowsShell))]
[InlineData(true)]
[InlineData(false)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "not supported on UAP")]
[OuterLoop("Launches File Explorer")]
public void ProcessStart_UseShellExecute_OnWindows_DoesNotThrow(bool isFolder)
{
string fileToOpen;
if (isFolder)
{
fileToOpen = Environment.CurrentDirectory;
}
else
{
fileToOpen = GetTestFilePath() + ".txt";
File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnWindows_DoesNotThrow)}");
}
using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen }))
{
if (isFolder)
{
Assert.Null(px);
}
else
{
if (px != null) // sometimes process is null
{
Assert.Equal("notepad", px.ProcessName);
px.Kill();
Assert.True(px.WaitForExit(WaitInMS));
}
}
}
}
[Fact]
public void TestExitCode()
{
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.Equal(SuccessExitCode, p.ExitCode);
}
{
Process p = CreateProcessLong();
StartSleepKillWait(p);
Assert.NotEqual(0, p.ExitCode);
}
}
[Fact]
public void TestExitTime()
{
// Try twice, since it's possible that the system clock could be adjusted backwards between when we snapshot it
// and when the process ends, but vanishingly unlikely that would happen twice.
DateTime timeBeforeProcessStart = DateTime.MaxValue;
Process p = null;
for (int i = 0; i <= 1; i++)
{
// ExitTime resolution on some platforms is less accurate than our DateTime.UtcNow resolution, so
// we subtract ms from the begin time to account for it.
timeBeforeProcessStart = DateTime.UtcNow.AddMilliseconds(-25);
p = CreateProcessLong();
p.Start();
Assert.Throws<InvalidOperationException>(() => p.ExitTime);
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
if (p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart)
break;
}
Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart,
$@"TestExitTime is incorrect. " +
$@"TimeBeforeStart {timeBeforeProcessStart} Ticks={timeBeforeProcessStart.Ticks}, " +
$@"ExitTime={p.ExitTime}, Ticks={p.ExitTime.Ticks}, " +
$@"ExitTimeUniversal {p.ExitTime.ToUniversalTime()} Ticks={p.ExitTime.ToUniversalTime().Ticks}, " +
$@"NowUniversal {DateTime.Now.ToUniversalTime()} Ticks={DateTime.Now.Ticks}");
}
[Fact]
public void StartTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StartTime);
}
[Fact]
public void TestId()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle));
}
else
{
IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunnerName).Select(p => p.Id);
Assert.Contains(_process.Id, testProcessIds);
}
}
[Fact]
public void TestHasExited()
{
{
Process p = CreateProcessPortable(RemotelyInvokable.Dummy);
p.Start();
Assert.True(p.WaitForExit(WaitInMS));
Assert.True(p.HasExited, "TestHasExited001 failed");
}
{
Process p = CreateProcessLong();
p.Start();
try
{
Assert.False(p.HasExited, "TestHasExited002 failed");
}
finally
{
p.Kill();
Assert.True(p.WaitForExit(WaitInMS));
}
Assert.True(p.HasExited, "TestHasExited003 failed");
}
}
[Fact]
public void HasExited_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HasExited);
}
[Fact]
public void Kill_NotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Kill());
}
[Fact]
public void TestMachineName()
{
CreateDefaultProcess();
// Checking that the MachineName returns some value.
Assert.NotNull(_process.MachineName);
}
[Fact]
public void MachineName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MachineName);
}
[Fact]
public void TestMainModule()
{
Process p = Process.GetCurrentProcess();
// On UAP casing may not match - we use Path.GetFileName(exePath) instead of kernel32!GetModuleFileNameEx which is not available on UAP
Func<string, string> normalize = PlatformDetection.IsUap ?
(Func<string, string>)((s) => s.ToLowerInvariant()) :
(s) => s;
Assert.True(p.Modules.Count > 0);
Assert.Equal(normalize(HostRunnerName), normalize(p.MainModule.ModuleName));
Assert.EndsWith(normalize(HostRunnerName), normalize(p.MainModule.FileName));
Assert.Equal(normalize(string.Format("System.Diagnostics.ProcessModule ({0})", HostRunnerName)), normalize(p.MainModule.ToString()));
}
[Fact]
public void TestMaxWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MaxWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MaxWorkingSet = (IntPtr)((int)curValue + 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)max;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MaxWorkingSet);
}
finally
{
_process.MaxWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MaxWorkingSet is not supported on OSX.
public void MaxWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MaxWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MaxValueWorkingSet_GetSetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet);
Assert.Throws<PlatformNotSupportedException>(() => process.MaxWorkingSet = (IntPtr)1);
}
[Fact]
public void TestMinWorkingSet()
{
CreateDefaultProcess();
using (Process p = Process.GetCurrentProcess())
{
Assert.True((long)p.MaxWorkingSet > 0);
Assert.True((long)p.MinWorkingSet >= 0);
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
return; // doesn't support getting/setting working set for other processes
long curValue = (long)_process.MinWorkingSet;
Assert.True(curValue >= 0);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try
{
_process.MinWorkingSet = (IntPtr)((int)curValue - 1024);
IntPtr min, max;
uint flags;
Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags);
curValue = (int)min;
_process.Refresh();
Assert.Equal(curValue, (int)_process.MinWorkingSet);
}
finally
{
_process.MinWorkingSet = (IntPtr)curValue;
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // Getting MinWorkingSet is not supported on OSX.
public void MinWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MinWorkingSet);
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void MinWorkingSet_GetMacos_ThrowsPlatformSupportedException()
{
var process = new Process();
Assert.Throws<PlatformNotSupportedException>(() => process.MinWorkingSet);
}
[Fact]
public void TestModules()
{
ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules;
foreach (ProcessModule pModule in moduleCollection)
{
// Validated that we can get a value for each of the following.
Assert.NotNull(pModule);
Assert.NotNull(pModule.FileName);
Assert.NotNull(pModule.ModuleName);
// Just make sure these don't throw
IntPtr baseAddr = pModule.BaseAddress;
IntPtr entryAddr = pModule.EntryPointAddress;
int memSize = pModule.ModuleMemorySize;
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestNonpagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64);
}
[Fact]
public void NonpagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64);
}
[Fact]
public void PagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedSystemMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64);
}
[Fact]
public void PagedSystemMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakPagedMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64);
}
[Fact]
public void PeakPagedMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakVirtualMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64);
}
[Fact]
public void PeakVirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakWorkingSet64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64);
}
[Fact]
public void PeakWorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPrivateMemorySize64()
{
CreateDefaultProcess();
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64);
}
[Fact]
public void PrivateMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestVirtualMemorySize64()
{
CreateDefaultProcess();
Assert.True(_process.VirtualMemorySize64 > 0);
}
[Fact]
public void VirtualMemorySize64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize64);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestWorkingSet64()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
Assert.True(_process.WorkingSet64 >= 0);
return;
}
Assert.True(_process.WorkingSet64 > 0);
}
[Fact]
public void WorkingSet64_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.WorkingSet64);
}
[Fact]
public void TestProcessorTime()
{
CreateDefaultProcess();
Assert.True(_process.UserProcessorTime.TotalSeconds >= 0);
Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0);
double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
double processorTimeAtHalfSpin = 0;
// Perform loop to occupy cpu, takes less than a second.
int i = int.MaxValue / 16;
while (i > 0)
{
i--;
if (i == int.MaxValue / 32)
processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds;
}
Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds);
}
[Fact]
public void UserProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.UserProcessorTime);
}
[Fact]
public void PriviledgedProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PrivilegedProcessorTime);
}
[Fact]
public void TotalProcessorTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.TotalProcessorTime);
}
[Fact]
public void TestProcessStartTime()
{
TimeSpan allowedWindow = TimeSpan.FromSeconds(1);
for (int i = 0; i < 2; i++)
{
Process p = CreateProcessPortable(RemotelyInvokable.ReadLine);
Assert.Throws<InvalidOperationException>(() => p.StartTime);
DateTime testStartTime = DateTime.Now;
p.StartInfo.RedirectStandardInput = true;
p.Start();
Assert.Equal(p.StartTime, p.StartTime);
DateTime processStartTime = p.StartTime;
using (StreamWriter writer = p.StandardInput)
{
writer.WriteLine("start");
}
Assert.True(p.WaitForExit(WaitInMS));
DateTime testEndTime = DateTime.Now;
bool hasTimeChanged = testEndTime < testStartTime;
if (i != 0 || !hasTimeChanged)
{
Assert.InRange(processStartTime, testStartTime - allowedWindow, testEndTime + allowedWindow);
break;
}
}
}
[Fact]
public void ExitTime_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ExitTime);
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // getting/setting affinity not supported on OSX
public void TestProcessorAffinity()
{
CreateDefaultProcess();
IntPtr curProcessorAffinity = _process.ProcessorAffinity;
try
{
_process.ProcessorAffinity = new IntPtr(0x1);
Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity);
}
finally
{
_process.ProcessorAffinity = curProcessorAffinity;
Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity);
}
}
[Fact]
public void TestPriorityBoostEnabled()
{
CreateDefaultProcess();
bool isPriorityBoostEnabled = _process.PriorityBoostEnabled;
try
{
_process.PriorityBoostEnabled = true;
Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed");
_process.PriorityBoostEnabled = false;
Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed");
}
finally
{
_process.PriorityBoostEnabled = isPriorityBoostEnabled;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // PriorityBoostEnabled is a no-op on Unix.
public void PriorityBoostEnabled_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled);
Assert.Throws<InvalidOperationException>(() => process.PriorityBoostEnabled = true);
}
[Fact, PlatformSpecific(TestPlatforms.Windows)] // Expected behavior varies on Windows and Unix
public void TestPriorityClassWindows()
{
CreateDefaultProcess();
ProcessPriorityClass priorityClass = _process.PriorityClass;
try
{
_process.PriorityClass = ProcessPriorityClass.High;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High);
_process.PriorityClass = ProcessPriorityClass.Normal;
Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal);
}
finally
{
_process.PriorityClass = priorityClass;
}
}
[Theory]
[InlineData((ProcessPriorityClass)0)]
[InlineData(ProcessPriorityClass.Normal | ProcessPriorityClass.Idle)]
public void TestInvalidPriorityClass(ProcessPriorityClass priorityClass)
{
var process = new Process();
Assert.Throws<InvalidEnumArgumentException>(() => process.PriorityClass = priorityClass);
}
[Fact]
public void PriorityClass_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.PriorityClass);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestProcessName()
{
CreateDefaultProcess();
string expected = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : HostRunner;
Assert.Equal(Path.GetFileNameWithoutExtension(expected), Path.GetFileNameWithoutExtension(_process.ProcessName), StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void ProcessName_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.ProcessName);
}
[Fact]
public void TestSafeHandle()
{
CreateDefaultProcess();
Assert.False(_process.SafeHandle.IsInvalid);
}
[Fact]
public void SafeHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SafeHandle);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestSessionId()
{
CreateDefaultProcess();
uint sessionId;
#if TargetsWindows
Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId);
#else
sessionId = (uint)Interop.getsid(_process.Id);
#endif
Assert.Equal(sessionId, (uint)_process.SessionId);
}
[Fact]
public void SessionId_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.SessionId);
}
[Fact]
public void TestGetCurrentProcess()
{
Process current = Process.GetCurrentProcess();
Assert.NotNull(current);
int currentProcessId =
#if TargetsWindows
Interop.GetCurrentProcessId();
#else
Interop.getpid();
#endif
Assert.Equal(currentProcessId, current.Id);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestGetProcessById()
{
CreateDefaultProcess();
Process p = Process.GetProcessById(_process.Id);
Assert.Equal(_process.Id, p.Id);
Assert.Equal(_process.ProcessName, p.ProcessName);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestGetProcesses()
{
Process currentProcess = Process.GetCurrentProcess();
// Get all the processes running on the machine, and check if the current process is one of them.
var foundCurrentProcess = (from p in Process.GetProcesses()
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses001 failed");
foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName)
where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName))
select p).Any();
Assert.True(foundCurrentProcess, "TestGetProcesses002 failed");
}
[Fact]
public void GetProcesseses_NullMachineName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcesses(null));
}
[Fact]
public void GetProcesses_EmptyMachineName_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcesses(""));
}
[Fact]
[ActiveIssue(26720, TargetFrameworkMonikers.Uap)]
[ActiveIssue(27459)]
public void GetProcesses_InvalidMachineName_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Process.GetProcesses(Guid.NewGuid().ToString()));
}
[Fact]
public void GetProcesses_RemoteMachinePath_ReturnsExpected()
{
try
{
Process[] processes = Process.GetProcesses(Environment.MachineName + "." + Domain.GetComputerDomain());
Assert.NotEmpty(processes);
}
catch (ActiveDirectoryObjectNotFoundException)
{
//This will be thrown when the executing machine is not domain-joined, i.e. in CI
}
catch (PlatformNotSupportedException)
{
//System.DirectoryServices is not supported on all platforms
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_ProcessName_ReturnsExpected()
{
// Get the current process using its name
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(".", process.MachineName));
}
public static IEnumerable<object[]> MachineName_TestData()
{
string currentProcessName = Process.GetCurrentProcess().MachineName;
yield return new object[] { currentProcessName };
yield return new object[] { "." };
yield return new object[] { Dns.GetHostName() };
}
public static IEnumerable<object[]> MachineName_Remote_TestData()
{
yield return new object[] { Guid.NewGuid().ToString("N") };
yield return new object[] { "\\" + Guid.NewGuid().ToString("N") };
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[MemberData(nameof(MachineName_TestData))]
public void GetProcessesByName_ProcessNameMachineName_ReturnsExpected(string machineName)
{
Process currentProcess = Process.GetCurrentProcess();
Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName, machineName);
Assert.NotEmpty(processes);
Assert.All(processes, process => Assert.Equal(machineName, process.MachineName));
}
[MemberData(nameof(MachineName_Remote_TestData))]
[PlatformSpecific(TestPlatforms.Windows)] // Accessing processes on remote machines is only supported on Windows.
public void GetProcessesByName_RemoteMachineNameWindows_ReturnsExpected(string machineName)
{
try
{
GetProcessesByName_ProcessNameMachineName_ReturnsExpected(machineName);
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_NoSuchProcess_ReturnsEmpty()
{
string processName = Guid.NewGuid().ToString("N");
Assert.Empty(Process.GetProcessesByName(processName));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_NullMachineName_ThrowsArgumentNullException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentNullException>("machineName", () => Process.GetProcessesByName(currentProcess.ProcessName, null));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void GetProcessesByName_EmptyMachineName_ThrowsArgumentException()
{
Process currentProcess = Process.GetCurrentProcess();
AssertExtensions.Throws<ArgumentException>(null, () => Process.GetProcessesByName(currentProcess.ProcessName, ""));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Behavior differs on Windows and Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Retrieving information about local processes is not supported on uap")]
public void TestProcessOnRemoteMachineWindows()
{
Process currentProccess = Process.GetCurrentProcess();
void TestRemoteProccess(Process remoteProcess)
{
Assert.Equal(currentProccess.Id, remoteProcess.Id);
Assert.Equal(currentProccess.BasePriority, remoteProcess.BasePriority);
Assert.Equal(currentProccess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents);
Assert.Equal("127.0.0.1", remoteProcess.MachineName);
// This property throws exception only on remote processes.
Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule);
}
try
{
TestRemoteProccess(Process.GetProcessById(currentProccess.Id, "127.0.0.1"));
TestRemoteProccess(Process.GetProcessesByName(currentProccess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProccess.Id).Single());
}
catch (InvalidOperationException)
{
// As we can't detect reliably if performance counters are enabled
// we let possible InvalidOperationExceptions pass silently.
}
}
[Fact]
public void StartInfo_GetFileName_ReturnsExpected()
{
Process process = CreateProcessLong();
process.Start();
// Processes are not hosted by dotnet in the full .NET Framework.
string expectedFileName = PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative ? TestConsoleApp : RunnerName;
Assert.Equal(expectedFileName, process.StartInfo.FileName);
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = CreateProcessLong();
process.Start();
// .NET Core fixes a bug where Process.StartInfo for a unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
var startInfo = new ProcessStartInfo();
process.StartInfo = startInfo;
Assert.Equal(startInfo, process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo = new ProcessStartInfo());
}
process.Kill();
Assert.True(process.WaitForExit(WaitInMS));
}
[Fact]
public void StartInfo_SetGet_ReturnsExpected()
{
var process = new Process() { StartInfo = new ProcessStartInfo(TestConsoleApp) };
Assert.Equal(TestConsoleApp, process.StartInfo.FileName);
}
[Fact]
public void StartInfo_SetNull_ThrowsArgumentNullException()
{
var process = new Process();
Assert.Throws<ArgumentNullException>(() => process.StartInfo = null);
}
[Fact]
public void StartInfo_GetOnRunningProcess_ThrowsInvalidOperationException()
{
Process process = Process.GetCurrentProcess();
// .NET Core fixes a bug where Process.StartInfo for an unrelated process would
// return information about the current process, not the unrelated process.
// See https://github.com/dotnet/corefx/issues/1100.
if (PlatformDetection.IsFullFramework)
{
Assert.NotNull(process.StartInfo);
}
else
{
Assert.Throws<InvalidOperationException>(() => process.StartInfo);
}
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "Non applicable for uap - RemoteInvoke works differently")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData(@"""abc"" d e", @"abc,d,e")]
[InlineData("\"abc\"\t\td\te", @"abc,d,e")]
[InlineData(@"a\\b d""e f""g h", @"a\\b,de fg,h")]
[InlineData(@"\ \\ \\\", @"\,\\,\\\")]
[InlineData(@"a\\\""b c d", @"a\""b,c,d")]
[InlineData(@"a\\\\""b c"" d e", @"a\\b c,d,e")]
[InlineData(@"a""b c""d e""f g""h i""j k""l", @"ab cd,ef gh,ij kl")]
[InlineData(@"a b c""def", @"a,b,cdef")]
[InlineData(@"""\a\"" \\""\\\ b c", @"\a"" \\\\,b,c")]
[InlineData("\"\" b \"\"", ",b,")]
[InlineData("\"\"\"\" b c", "\",b,c")]
[InlineData("c\"\"\"\" b \"\"\\", "c\",b,\\")]
[InlineData("\"\"c \"\"b\"\" d\"\\", "c,b,d\\")]
[InlineData("\"\"a\"\" b d", "a,b,d")]
[InlineData("b d \"\"a\"\" ", "b,d,a")]
[InlineData("\\\"\\\"a\\\"\\\" b d", "\"\"a\"\",b,d")]
[InlineData("b d \\\"\\\"a\\\"\\\"", "b,d,\"\"a\"\"")]
public void TestArgumentParsing(string inputArguments, string expectedArgv)
{
var options = new RemoteInvokeOptions
{
Start = true,
StartInfo = new ProcessStartInfo { RedirectStandardOutput = true }
};
using (RemoteInvokeHandle handle = RemoteInvokeRaw((Func<string, string, string, int>)RemotelyInvokable.ConcatThreeArguments, inputArguments, options))
{
Assert.Equal(expectedArgv, handle.Process.StandardOutput.ReadToEnd());
}
}
[Fact]
public void StandardInput_GetNotRedirected_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.StandardInput);
}
// [Fact] // uncomment for diagnostic purposes to list processes to console
public void TestDiagnosticsWithConsoleWriteLine()
{
foreach (var p in Process.GetProcesses().OrderBy(p => p.Id))
{
Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count);
p.Dispose();
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "GC has different behavior on Mono")]
public void CanBeFinalized()
{
FinalizingProcess.CreateAndRelease();
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.True(FinalizingProcess.WasFinalized);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void TestStartWithMissingFile(bool fullPath)
{
string path = Guid.NewGuid().ToString("N");
if (fullPath)
{
path = Path.GetFullPath(path);
Assert.True(Path.IsPathRooted(path));
}
else
{
Assert.False(Path.IsPathRooted(path));
}
Assert.False(File.Exists(path));
Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path));
Assert.NotEqual(0, e.NativeErrorCode);
}
[Fact]
public void Start_NullStartInfo_ThrowsArgumentNullExceptionException()
{
AssertExtensions.Throws<ArgumentNullException>("startInfo", () => Process.Start((ProcessStartInfo)null));
}
[Fact]
public void Start_EmptyFileName_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardOutputEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardOutput = false,
StandardOutputEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_HasStandardErrorEncodingNonRedirected_ThrowsInvalidOperationException()
{
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "FileName",
RedirectStandardError = false,
StandardErrorEncoding = Encoding.UTF8
}
};
Assert.Throws<InvalidOperationException>(() => process.Start());
}
[Fact]
public void Start_Disposed_ThrowsObjectDisposedException()
{
var process = new Process();
process.StartInfo.FileName = "Nothing";
process.Dispose();
Assert.Throws<ObjectDisposedException>(() => process.Start());
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
public void TestHandleCount()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.HandleCount > 0);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)] // Expected process HandleCounts differs on OSX
public void TestHandleCount_OSX()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.Equal(0, p.HandleCount);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux | TestPlatforms.Windows)] // Expected process HandleCounts differs on OSX
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Handle count change is not reliable, but seems less robust on NETFX")]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
[ActiveIssue(27459)]
public void HandleCountChanges()
{
RemoteInvoke(() =>
{
Process p = Process.GetCurrentProcess();
int handleCount = p.HandleCount;
using (var fs1 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs2 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
using (var fs3 = File.Open(GetTestFilePath(), FileMode.OpenOrCreate))
{
p.Refresh();
int secondHandleCount = p.HandleCount;
Assert.True(handleCount < secondHandleCount);
handleCount = secondHandleCount;
}
p.Refresh();
int thirdHandleCount = p.HandleCount;
Assert.True(thirdHandleCount < handleCount);
return SuccessExitCode;
}).Dispose();
}
[Fact]
public void HandleCount_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.HandleCount);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowHandle is not supported on Unix.
public void MainWindowHandle_NoWindow_ReturnsEmptyHandle()
{
CreateDefaultProcess();
Assert.Equal(IntPtr.Zero, _process.MainWindowHandle);
Assert.Equal(_process.MainWindowHandle, _process.MainWindowHandle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowHandle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowHandle);
}
[Fact]
public void MainWindowTitle_NoWindow_ReturnsEmpty()
{
CreateDefaultProcess();
Assert.Empty(_process.MainWindowTitle);
Assert.Same(_process.MainWindowTitle, _process.MainWindowTitle);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // MainWindowTitle is a no-op and always returns string.Empty on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void MainWindowTitle_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.MainWindowTitle);
}
[Fact]
public void CloseMainWindow_NoWindow_ReturnsFalse()
{
CreateDefaultProcess();
Assert.False(_process.CloseMainWindow());
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void CloseMainWindow_NotStarted_ThrowsInvalidOperationException_WindowsNonUap()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.CloseMainWindow());
}
[Fact]
// CloseMainWindow is a no-op and always returns false on Unix or Uap.
public void CloseMainWindow_NotStarted_ReturnsFalse_UapOrNonWindows()
{
if (PlatformDetection.IsWindows && !PlatformDetection.IsUap)
return;
var process = new Process();
Assert.False(process.CloseMainWindow());
}
[PlatformSpecific(TestPlatforms.Windows)] // Needs to get the process Id from OS
[Fact]
public void TestRespondingWindows()
{
using (Process p = Process.GetCurrentProcess())
{
Assert.True(p.Responding);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Responding always returns true on Unix.
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "HWND not available")]
public void Responding_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
Assert.Throws<InvalidOperationException>(() => process.Responding);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestNonpagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void NonpagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.NonpagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPagedSystemMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PagedSystemMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PagedSystemMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakPagedMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakPagedMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakPagedMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PeakVirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakVirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPeakWorkingSet()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
public void PeakWorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PeakWorkingSet);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestPrivateMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
public void PrivateMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.PrivateMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestVirtualMemorySize()
{
CreateDefaultProcess();
#pragma warning disable 0618
Assert.Equal(unchecked((int)_process.VirtualMemorySize64), _process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
public void VirtualMemorySize_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.VirtualMemorySize);
#pragma warning restore 0618
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void TestWorkingSet()
{
CreateDefaultProcess();
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// resident memory can be 0 on OSX.
#pragma warning disable 0618
Assert.True(_process.WorkingSet >= 0);
#pragma warning restore 0618
return;
}
#pragma warning disable 0618
Assert.True(_process.WorkingSet > 0);
#pragma warning restore 0618
}
[Fact]
public void WorkingSet_GetNotStarted_ThrowsInvalidOperationException()
{
var process = new Process();
#pragma warning disable 0618
Assert.Throws<InvalidOperationException>(() => process.WorkingSet);
#pragma warning restore 0618
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartInvalidNamesTest()
{
Assert.Throws<InvalidOperationException>(() => Process.Start(null, "userName", new SecureString(), "thisDomain"));
Assert.Throws<InvalidOperationException>(() => Process.Start(string.Empty, "userName", new SecureString(), "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start("exe", string.Empty, new SecureString(), "thisDomain"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartWithInvalidUserNamePassword()
{
SecureString password = AsSecureString("Value");
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), "userName", password, "thisDomain"));
Assert.Throws<Win32Exception>(() => Process.Start(GetCurrentProcessName(), Environment.UserName, password, Environment.UserDomainName));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = "thisDomain";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, userName, password, domain); // This writes junk to the Console but with this overload, we can't prevent that.
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
Assert.True(p.WaitForExit(WaitInMS));
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")]
public void Process_StartWithArgumentsTest()
{
string currentProcessName = GetCurrentProcessName();
string userName = string.Empty;
string domain = Environment.UserDomainName;
string arguments = "-xml testResults.xml";
SecureString password = AsSecureString("Value");
Process p = Process.Start(currentProcessName, arguments, userName, password, domain);
Assert.NotNull(p);
Assert.Equal(currentProcessName, p.StartInfo.FileName);
Assert.Equal(arguments, p.StartInfo.Arguments);
Assert.Equal(userName, p.StartInfo.UserName);
Assert.Same(password, p.StartInfo.Password);
Assert.Equal(domain, p.StartInfo.Domain);
p.Kill();
password.Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Starting process with authentication not supported on Unix
public void Process_StartWithDuplicatePassword()
{
var startInfo = new ProcessStartInfo()
{
FileName = "exe",
UserName = "dummyUser",
PasswordInClearText = "Value",
Password = AsSecureString("Value"),
UseShellExecute = false
};
var process = new Process() { StartInfo = startInfo };
AssertExtensions.Throws<ArgumentException>(null, () => process.Start());
}
[Fact]
public void TestLongProcessIsWorking()
{
// Sanity check for CreateProcessLong
Process p = CreateProcessLong();
p.Start();
Thread.Sleep(500);
Assert.False(p.HasExited);
p.Kill();
p.WaitForExit();
Assert.True(p.HasExited);
}
private string GetCurrentProcessName()
{
return $"{Process.GetCurrentProcess().ProcessName}.exe";
}
private SecureString AsSecureString(string str)
{
SecureString secureString = new SecureString();
foreach (var ch in str)
{
secureString.AppendChar(ch);
}
return secureString;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using Internal.Win32;
using Internal.Runtime.CompilerServices;
using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT;
using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION;
using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION;
namespace System
{
public sealed partial class TimeZoneInfo
{
// registry constants for the 'Time Zones' hive
//
private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones";
private const string DisplayValue = "Display";
private const string DaylightValue = "Dlt";
private const string StandardValue = "Std";
private const string MuiDisplayValue = "MUI_Display";
private const string MuiDaylightValue = "MUI_Dlt";
private const string MuiStandardValue = "MUI_Std";
private const string TimeZoneInfoValue = "TZI";
private const string FirstEntryValue = "FirstEntry";
private const string LastEntryValue = "LastEntry";
private const int MaxKeyLength = 255;
#pragma warning disable 0420
private sealed partial class CachedData
{
private static TimeZoneInfo GetCurrentOneYearLocal()
{
// load the data from the OS
TIME_ZONE_INFORMATION timeZoneInformation;
uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation);
return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ?
CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) :
GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false);
}
private volatile OffsetAndRule _oneYearLocalFromUtc;
public OffsetAndRule GetOneYearLocalFromUtc(int year)
{
OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc;
if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year)
{
TimeZoneInfo currentYear = GetCurrentOneYearLocal();
AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0];
oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule);
_oneYearLocalFromUtc = oneYearLocFromUtc;
}
return oneYearLocFromUtc;
}
}
#pragma warning restore 0420
private sealed class OffsetAndRule
{
public readonly int Year;
public readonly TimeSpan Offset;
public readonly AdjustmentRule Rule;
public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule)
{
Year = year;
Offset = offset;
Rule = rule;
}
}
/// <summary>
/// Returns a cloned array of AdjustmentRule objects
/// </summary>
public AdjustmentRule[] GetAdjustmentRules()
{
if (_adjustmentRules == null)
{
return Array.Empty<AdjustmentRule>();
}
return (AdjustmentRule[])_adjustmentRules.Clone();
}
private static void PopulateAllSystemTimeZones(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (reg != null)
{
foreach (string keyName in reg.GetSubKeyNames())
{
TimeZoneInfo value;
Exception ex;
TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache
}
}
}
}
private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled)
{
string standardName = zone.GetStandardName();
if (standardName.Length == 0)
{
_id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local"
}
else
{
_id = standardName;
}
_baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0);
if (!dstDisabled)
{
// only create the adjustment rule if DST is enabled
REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone);
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias);
if (rule != null)
{
_adjustmentRules = new[] { rule };
}
}
ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime);
_displayName = standardName;
_standardDisplayName = standardName;
_daylightDisplayName = zone.GetDaylightName();
}
/// <summary>
/// Helper function to check if the current TimeZoneInformation struct does not support DST.
/// This check returns true when the DaylightDate == StandardDate.
/// This check is only meant to be used for "Local".
/// </summary>
private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) =>
timeZone.DaylightDate.Equals(timeZone.StandardDate);
/// <summary>
/// Converts a REG_TZI_FORMAT struct to an AdjustmentRule.
/// </summary>
private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset)
{
bool supportsDst = timeZoneInformation.StandardDate.Month != 0;
if (!supportsDst)
{
if (timeZoneInformation.Bias == defaultBaseUtcOffset)
{
// this rule will not contain any information to be used to adjust dates. just ignore it
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
TimeSpan.Zero, // no daylight saving transition
TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1),
TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1),
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule
noDaylightTransitions: false);
}
//
// Create an AdjustmentRule with TransitionTime objects
//
TransitionTime daylightTransitionStart;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true))
{
return null;
}
TransitionTime daylightTransitionEnd;
if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false))
{
return null;
}
if (daylightTransitionStart.Equals(daylightTransitionEnd))
{
// this happens when the time zone does support DST but the OS has DST disabled
return null;
}
return AdjustmentRule.CreateAdjustmentRule(
startDate,
endDate,
new TimeSpan(0, -timeZoneInformation.DaylightBias, 0),
daylightTransitionStart,
daylightTransitionEnd,
new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0),
noDaylightTransitions: false);
}
/// <summary>
/// Helper function that searches the registry for a time zone entry
/// that matches the TimeZoneInformation struct.
/// </summary>
private static string FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false))
{
if (key == null)
{
return null;
}
foreach (string keyName in key.GetSubKeyNames())
{
if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled))
{
return keyName;
}
}
}
return null;
}
/// <summary>
/// Helper function for retrieving the local system time zone.
/// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException.
/// Assumes cachedData lock is taken.
/// </summary>
/// <returns>A new TimeZoneInfo instance.</returns>
private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData)
{
Debug.Assert(Monitor.IsEntered(cachedData));
//
// Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id"
//
var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION();
// call kernel32!GetDynamicTimeZoneInformation...
uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation);
if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID)
{
// return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
// check to see if we can use the key name returned from the API call
string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName();
if (dynamicTimeZoneKeyName.Length != 0)
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation);
// the key name was not returned or it pointed to a bogus entry - search for the entry ourselves
string id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled);
if (id != null)
{
TimeZoneInfo zone;
Exception ex;
if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success)
{
// successfully loaded the time zone from the registry
return zone;
}
}
// We could not find the data in the registry. Fall back to using
// the data from the Win32 API
return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled);
}
/// <summary>
/// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of
/// try/catch logic for handling the TimeZoneInfo private constructor that takes
/// a TIME_ZONE_INFORMATION structure.
/// </summary>
private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled)
{
// first try to create the TimeZoneInfo with the original 'dstDisabled' flag
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
// if 'dstDisabled' was false then try passing in 'true' as a last ditch effort
if (!dstDisabled)
{
try
{
return new TimeZoneInfo(timeZoneInformation, dstDisabled: true);
}
catch (ArgumentException) { }
catch (InvalidTimeZoneException) { }
}
// the data returned from Windows is completely bogus; return a dummy entry
return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId);
}
/// <summary>
/// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>.
/// This function wraps the logic necessary to keep the private
/// SystemTimeZones cache in working order
///
/// This function will either return a valid TimeZoneInfo instance or
/// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'.
/// </summary>
public static TimeZoneInfo FindSystemTimeZoneById(string id)
{
// Special case for Utc as it will not exist in the dictionary with the rest
// of the system time zones. There is no need to do this check for Local.Id
// since Local is a real time zone that exists in the dictionary cache
if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase))
{
return Utc;
}
if (id == null)
{
throw new ArgumentNullException(nameof(id));
}
if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0'))
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo value;
Exception e;
TimeZoneInfoResult result;
CachedData cachedData = s_cachedData;
lock (cachedData)
{
result = TryGetTimeZone(id, false, out value, out e, cachedData);
}
if (result == TimeZoneInfoResult.Success)
{
return value;
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
}
else if (result == TimeZoneInfoResult.SecurityException)
{
throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
}
else
{
throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
// DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone
internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst)
{
bool isDaylightSavings = false;
isAmbiguousLocalDst = false;
TimeSpan baseOffset;
int timeYear = time.Year;
OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear);
baseOffset = match.Offset;
if (match.Rule != null)
{
baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta;
if (match.Rule.HasDaylightSaving)
{
isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local);
baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */);
}
}
return baseOffset;
}
/// <summary>
/// Converts a REG_TZI_FORMAT struct to a TransitionTime
/// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read
/// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read
/// </summary>
private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate)
{
//
// SYSTEMTIME -
//
// If the time zone does not support daylight saving time or if the caller needs
// to disable daylight saving time, the wMonth member in the SYSTEMTIME structure
// must be zero. If this date is specified, the DaylightDate value in the
// TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system
// assumes the time zone data is invalid and no changes will be applied.
//
bool supportsDst = (timeZoneInformation.StandardDate.Month != 0);
if (!supportsDst)
{
transitionTime = default;
return false;
}
//
// SYSTEMTIME -
//
// * FixedDateRule -
// If the Year member is not zero, the transition date is absolute; it will only occur one time
//
// * FloatingDateRule -
// To select the correct day in the month, set the Year member to zero, the Hour and Minute
// members to the transition time, the DayOfWeek member to the appropriate weekday, and the
// Day member to indicate the occurence of the day of the week within the month (first through fifth).
//
// Using this notation, specify the 2:00a.m. on the first Sunday in April as follows:
// Hour = 2,
// Month = 4,
// DayOfWeek = 0,
// Day = 1.
//
// Specify 2:00a.m. on the last Thursday in October as follows:
// Hour = 2,
// Month = 10,
// DayOfWeek = 4,
// Day = 5.
//
if (readStartDate)
{
//
// read the "daylightTransitionStart"
//
if (timeZoneInformation.DaylightDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.DaylightDate.Hour,
timeZoneInformation.DaylightDate.Minute,
timeZoneInformation.DaylightDate.Second,
timeZoneInformation.DaylightDate.Milliseconds),
timeZoneInformation.DaylightDate.Month,
timeZoneInformation.DaylightDate.Day);
}
}
else
{
//
// read the "daylightTransitionEnd"
//
if (timeZoneInformation.StandardDate.Year == 0)
{
transitionTime = TransitionTime.CreateFloatingDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day, /* Week 1-5 */
(DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek);
}
else
{
transitionTime = TransitionTime.CreateFixedDateRule(
new DateTime(1, /* year */
1, /* month */
1, /* day */
timeZoneInformation.StandardDate.Hour,
timeZoneInformation.StandardDate.Minute,
timeZoneInformation.StandardDate.Second,
timeZoneInformation.StandardDate.Milliseconds),
timeZoneInformation.StandardDate.Month,
timeZoneInformation.StandardDate.Day);
}
}
return true;
}
/// <summary>
/// Helper function that takes:
/// 1. A string representing a <time_zone_name> registry key name.
/// 2. A REG_TZI_FORMAT struct containing the default rule.
/// 3. An AdjustmentRule[] out-parameter.
/// </summary>
private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset)
{
rules = null;
e = null;
try
{
// Optional, Dynamic Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// Dynamic DST
// * "FirstEntry" REG_DWORD "1980"
// First year in the table. If the current year is less than this value,
// this entry will be used for DST boundaries
// * "LastEntry" REG_DWORD "2038"
// Last year in the table. If the current year is greater than this value,
// this entry will be used for DST boundaries"
// * "<year1>" REG_BINARY REG_TZI_FORMAT
// * "<year2>" REG_BINARY REG_TZI_FORMAT
// * "<year3>" REG_BINARY REG_TZI_FORMAT
//
using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false))
{
if (dynamicKey == null)
{
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(
defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
if (rule != null)
{
rules = new[] { rule };
}
return true;
}
//
// loop over all of the "<time_zone_name>\Dynamic DST" hive entries
//
// read FirstEntry {MinValue - (year1, 12, 31)}
// read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)}
// read LastEntry {(yearN, 1, 1) - MaxValue }
// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
int first = (int)dynamicKey.GetValue(FirstEntryValue, -1);
int last = (int)dynamicKey.GetValue(LastEntryValue, -1);
if (first == -1 || last == -1 || first > last)
{
return false;
}
// read the first year entry
REG_TZI_FORMAT dtzi;
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
if (first == last)
{
// there is just 1 dynamic rule for this time zone.
AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset);
if (rule != null)
{
rules = new[] { rule };
}
return true;
}
List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1);
// there are more than 1 dynamic rules for this time zone.
AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
DateTime.MinValue.Date, // MinValue
new DateTime(first, 12, 31), // December 31, <FirstYear>
defaultBaseUtcOffset);
if (firstRule != null)
{
rulesList.Add(firstRule);
}
// read the middle year entries
for (int i = first + 1; i < last; i++)
{
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(i, 1, 1), // January 01, <Year>
new DateTime(i, 12, 31), // December 31, <Year>
defaultBaseUtcOffset);
if (middleRule != null)
{
rulesList.Add(middleRule);
}
}
// read the last year entry
if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi))
{
return false;
}
AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation(
dtzi,
new DateTime(last, 1, 1), // January 01, <LastYear>
DateTime.MaxValue.Date, // MaxValue
defaultBaseUtcOffset);
if (lastRule != null)
{
rulesList.Add(lastRule);
}
// convert the List to an AdjustmentRule array
if (rulesList.Count != 0)
{
rules = rulesList.ToArray();
}
} // end of: using (RegistryKey dynamicKey...
}
catch (InvalidCastException ex)
{
// one of the RegistryKey.GetValue calls could not be cast to an expected value type
e = ex;
return false;
}
catch (ArgumentOutOfRangeException ex)
{
e = ex;
return false;
}
catch (ArgumentException ex)
{
e = ex;
return false;
}
return true;
}
private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi)
{
byte[] regValue = key.GetValue(name, null) as byte[];
if (regValue == null || regValue.Length != sizeof(REG_TZI_FORMAT))
{
dtzi = default;
return false;
}
fixed (byte * pBytes = ®Value[0])
dtzi = *(REG_TZI_FORMAT *)pBytes;
return true;
}
/// <summary>
/// Helper function that compares the StandardBias and StandardDate portion a
/// TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) =>
timeZone.Bias == registryTimeZoneInfo.Bias &&
timeZone.StandardBias == registryTimeZoneInfo.StandardBias &&
timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate);
/// <summary>
/// Helper function that compares a TimeZoneInformation struct to a time zone registry entry.
/// </summary>
private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled)
{
dstDisabled = false;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
return false;
}
REG_TZI_FORMAT registryTimeZoneInfo;
if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo))
{
return false;
}
//
// first compare the bias and standard date information between the data from the Win32 API
// and the data from the registry...
//
bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo);
if (!result)
{
return false;
}
result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) ||
//
// since Daylight Saving Time is not "disabled", do a straight comparision between
// the Win32 API data and the registry data ...
//
(timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias &&
timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate));
// Finally compare the "StandardName" string value...
//
// we do not compare "DaylightName" as this TimeZoneInformation field may contain
// either "StandardName" or "DaylightName" depending on the time of year and current machine settings
//
if (result)
{
string registryStandardName = key.GetValue(StandardValue, string.Empty) as string;
result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal);
}
return result;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via MUI.
/// The function expects a string in the form: "@resource.dll, -123"
///
/// "resource.dll" is a language-neutral portable executable (LNPE) file in
/// the %windir%\system32 directory. The OS is queried to find the best-fit
/// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui).
/// If a localized resource file exists, we LoadString resource ID "123" and
/// return it to our caller.
/// </summary>
private static string TryGetLocalizedNameByMuiNativeResource(string resource)
{
if (string.IsNullOrEmpty(resource))
{
return string.Empty;
}
// parse "@tzres.dll, -100"
//
// filePath = "C:\Windows\System32\tzres.dll"
// resourceId = -100
//
string[] resources = resource.Split(',');
if (resources.Length != 2)
{
return string.Empty;
}
string filePath;
int resourceId;
// get the path to Windows\System32
string system32 = Environment.SystemDirectory;
// trim the string "@tzres.dll" => "tzres.dll"
string tzresDll = resources[0].TrimStart('@');
try
{
filePath = Path.Combine(system32, tzresDll);
}
catch (ArgumentException)
{
// there were probably illegal characters in the path
return string.Empty;
}
if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId))
{
return string.Empty;
}
resourceId = -resourceId;
try
{
StringBuilder fileMuiPath = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH);
fileMuiPath.Length = Interop.Kernel32.MAX_PATH;
int fileMuiPathLength = Interop.Kernel32.MAX_PATH;
int languageLength = 0;
long enumerator = 0;
bool succeeded = Interop.Kernel32.GetFileMUIPath(
Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES,
filePath, null /* language */, ref languageLength,
fileMuiPath, ref fileMuiPathLength, ref enumerator);
if (!succeeded)
{
StringBuilderCache.Release(fileMuiPath);
return string.Empty;
}
return TryGetLocalizedNameByNativeResource(StringBuilderCache.GetStringAndRelease(fileMuiPath), resourceId);
}
catch (EntryPointNotFoundException)
{
return string.Empty;
}
}
/// <summary>
/// Helper function for retrieving a localized string resource via a native resource DLL.
/// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll"
///
/// "resource.dll" is a language-specific resource DLL.
/// If the localized resource DLL exists, LoadString(resource) is returned.
/// </summary>
private static string TryGetLocalizedNameByNativeResource(string filePath, int resource)
{
using (SafeLibraryHandle handle =
Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
{
if (!handle.IsInvalid)
{
const int LoadStringMaxLength = 500;
StringBuilder localizedResource = StringBuilderCache.Acquire(LoadStringMaxLength);
int result = Interop.User32.LoadString(handle, resource,
localizedResource, LoadStringMaxLength);
if (result != 0)
{
return StringBuilderCache.GetStringAndRelease(localizedResource);
}
}
}
return string.Empty;
}
/// <summary>
/// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry
///
/// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI
/// resource dll(s). When the keys do not exist, the function falls back to reading from the standard
/// key-values
/// </summary>
private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName)
{
displayName = string.Empty;
standardName = string.Empty;
daylightName = string.Empty;
// read the MUI_ registry keys
string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;
string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;
string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;
// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
{
displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource);
}
if (!string.IsNullOrEmpty(standardNameMuiResource))
{
standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource);
}
if (!string.IsNullOrEmpty(daylightNameMuiResource))
{
daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource);
}
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
displayName = key.GetValue(DisplayValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(standardName))
{
standardName = key.GetValue(StandardValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
daylightName = key.GetValue(DaylightValue, string.Empty) as string;
}
}
/// <summary>
/// Helper function that takes a string representing a <time_zone_name> registry key name
/// and returns a TimeZoneInfo instance.
/// </summary>
private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e)
{
e = null;
// Standard Time Zone Registry Data
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// HKLM
// Software
// Microsoft
// Windows NT
// CurrentVersion
// Time Zones
// <time_zone_name>
// * STD, REG_SZ "Standard Time Name"
// (For OS installed zones, this will always be English)
// * MUI_STD, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Standard Time,
// add "%windir%\system32\" after "@"
// * DLT, REG_SZ "Daylight Time Name"
// (For OS installed zones, this will always be English)
// * MUI_DLT, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for Daylight Time,
// add "%windir%\system32\" after "@"
// * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..."
// * MUI_Display, REG_SZ "@tzres.dll,-1234"
// Indirect string to localized resource for the Display,
// add "%windir%\system32\" after "@"
// * TZI, REG_BINARY REG_TZI_FORMAT
//
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false))
{
if (key == null)
{
value = null;
return TimeZoneInfoResult.TimeZoneNotFoundException;
}
REG_TZI_FORMAT defaultTimeZoneInformation;
if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation))
{
// the registry value could not be cast to a byte array
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
AdjustmentRule[] adjustmentRules;
if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias))
{
value = null;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
GetLocalizedNamesByRegistryKey(key, out string displayName, out string standardName, out string daylightName);
try
{
value = new TimeZoneInfo(
id,
new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0),
displayName,
standardName,
daylightName,
adjustmentRules,
disableDaylightSavingTime: false);
return TimeZoneInfoResult.Success;
}
catch (ArgumentException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
catch (InvalidTimeZoneException ex)
{
// TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException
value = null;
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
}
}
}
}
| |
// 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 Xunit;
namespace System.Tests
{
public static class BufferTests
{
[Fact]
public static void BlockCopy()
{
byte[] src = new byte[] { 0x1a, 0x2b, 0x3c, 0x4d };
byte[] dst = new byte[] { 0x6f, 0x6f, 0x6f, 0x6f, 0x6f, 0x6f };
Buffer.BlockCopy(src, 0, dst, 1, 4);
Assert.Equal(new byte[] { 0x6f, 0x1a, 0x2b, 0x3c, 0x4d, 0x6f }, dst);
}
[Fact]
public static void BlockCopy_SameDestinationAndSourceArray()
{
byte[] dst = new byte[] { 0x1a, 0x2b, 0x3c, 0x4d, 0x5e };
Buffer.BlockCopy(dst, 1, dst, 2, 2);
Assert.Equal(new byte[] { 0x1a, 0x2b, 0x2b, 0x3c, 0x5e }, dst);
}
[Fact]
public static void BlockCopy_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("src", () => Buffer.BlockCopy(null, 0, new int[3], 0, 0)); // Src is null
AssertExtensions.Throws<ArgumentNullException>("dst", () => Buffer.BlockCopy(new string[3], 0, null, 0, 0)); // Dst is null
AssertExtensions.Throws<ArgumentOutOfRangeException>("srcOffset", () => Buffer.BlockCopy(new byte[3], -1, new byte[3], 0, 0)); // SrcOffset < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("dstOffset", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], -1, 0)); // DstOffset < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 0, -1)); // Count < 0
AssertExtensions.Throws<ArgumentException>("src", () => Buffer.BlockCopy(new string[3], 0, new byte[3], 0, 0)); // Src is not a byte array
AssertExtensions.Throws<ArgumentException>("dst", "dest", () => Buffer.BlockCopy(new byte[3], 0, new string[3], 0, 0)); // Dst is not a byte array
AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 3, new byte[3], 0, 1)); // SrcOffset + count >= src.length
AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 4, new byte[3], 0, 0)); // SrcOffset >= src.Length
AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 3, 1)); // DstOffset + count >= dst.Length
AssertExtensions.Throws<ArgumentException>("", () => Buffer.BlockCopy(new byte[3], 0, new byte[3], 4, 0)); // DstOffset >= dst.Length
}
public static unsafe IEnumerable<object[]> ByteLength_TestData()
{
return new object[][]
{
new object[] { typeof(byte), sizeof(byte) },
new object[] { typeof(sbyte), sizeof(sbyte) },
new object[] { typeof(short), sizeof(short) },
new object[] { typeof(ushort), sizeof(ushort) },
new object[] { typeof(int), sizeof(int) },
new object[] { typeof(uint), sizeof(uint) },
new object[] { typeof(long), sizeof(long) },
new object[] { typeof(ulong), sizeof(ulong) },
new object[] { typeof(IntPtr), sizeof(IntPtr) },
new object[] { typeof(UIntPtr), sizeof(UIntPtr) },
new object[] { typeof(double), sizeof(double) },
new object[] { typeof(float), sizeof(float) },
new object[] { typeof(bool), sizeof(bool) },
new object[] { typeof(char), sizeof(char) }
};
}
[Theory]
[MemberData(nameof(ByteLength_TestData))]
public static void ByteLength(Type type, int size)
{
const int Length = 25;
Array array = Array.CreateInstance(type, Length);
Assert.Equal(Length * size, Buffer.ByteLength(array));
}
[Fact]
public static void ByteLength_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("array", () => Buffer.ByteLength(null)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(DateTime), 25))); // Array is not a primitive
AssertExtensions.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(decimal), 25))); // Array is not a primitive
AssertExtensions.Throws<ArgumentException>("array", () => Buffer.ByteLength(Array.CreateInstance(typeof(string), 25))); // Array is not a primitive
}
[Theory]
[InlineData(new uint[] { 0x01234567, 0x89abcdef }, 0, 0x67)]
[InlineData(new uint[] { 0x01234567, 0x89abcdef }, 7, 0x89)]
public static void GetByte(Array array, int index, int expected)
{
Assert.Equal(expected, Buffer.GetByte(array, index));
}
[Fact]
public static void GetByte_Invalid()
{
var array = new uint[] { 0x01234567, 0x89abcdef };
AssertExtensions.Throws<ArgumentNullException>("array", () => Buffer.GetByte(null, 0)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", () => Buffer.GetByte(new object[10], 0)); // Array is not a primitive array
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.GetByte(array, -1)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.GetByte(array, 8)); // Index >= array.Length
}
[Theory]
[InlineData(25000, 0, 30000, 0, 25000)]
[InlineData(25000, 0, 30000, 5000, 25000)]
[InlineData(25000, 5000, 30000, 6000, 20000)]
[InlineData(25000, 5000, 30000, 6000, 4000)]
[InlineData(100, 0, 100, 0, 0)]
[InlineData(100, 0, 100, 0, 1)]
[InlineData(100, 0, 100, 0, 2)]
[InlineData(100, 0, 100, 0, 3)]
[InlineData(100, 0, 100, 0, 4)]
[InlineData(100, 0, 100, 0, 5)]
[InlineData(100, 0, 100, 0, 6)]
[InlineData(100, 0, 100, 0, 7)]
[InlineData(100, 0, 100, 0, 8)]
[InlineData(100, 0, 100, 0, 9)]
[InlineData(100, 0, 100, 0, 10)]
[InlineData(100, 0, 100, 0, 11)]
[InlineData(100, 0, 100, 0, 12)]
[InlineData(100, 0, 100, 0, 13)]
[InlineData(100, 0, 100, 0, 14)]
[InlineData(100, 0, 100, 0, 15)]
[InlineData(100, 0, 100, 0, 16)]
[InlineData(100, 0, 100, 0, 17)]
public static unsafe void MemoryCopy(int sourceLength, int sourceIndexOffset, int destinationLength, int destinationIndexOffset, long sourceBytesToCopy)
{
var sourceArray = new byte[sourceLength];
for (int i = 0; i < sourceArray.Length; i++)
{
sourceArray[i] = unchecked((byte)i);
}
var destinationArray = new byte[destinationLength];
for (int i = 0; i < destinationArray.Length; i++)
{
destinationArray[i] = unchecked((byte)(i * 2));
}
fixed (byte* sourceBase = sourceArray, destinationBase = destinationArray)
{
Buffer.MemoryCopy(sourceBase + sourceIndexOffset, destinationBase + destinationIndexOffset, destinationLength, sourceBytesToCopy);
}
for (int i = 0; i < destinationIndexOffset; i++)
{
Assert.Equal(unchecked((byte)(i * 2)), destinationArray[i]);
}
for (int i = 0; i < sourceBytesToCopy; i++)
{
Assert.Equal(sourceArray[i + sourceIndexOffset], destinationArray[i + destinationIndexOffset]);
}
for (long i = destinationIndexOffset + sourceBytesToCopy; i < destinationArray.Length; i++)
{
Assert.Equal(unchecked((byte)(i * 2)), destinationArray[i]);
}
}
[Theory]
[InlineData(200, 50, 100)]
[InlineData(200, 5, 15)]
public static unsafe void MemoryCopy_OverlappingBuffers(int sourceLength, int destinationIndexOffset, int sourceBytesToCopy)
{
var array = new int[sourceLength];
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
fixed (int* arrayBase = array)
{
Buffer.MemoryCopy(arrayBase, arrayBase + destinationIndexOffset, sourceLength * 4, sourceBytesToCopy * 4);
}
for (int i = 0; i < sourceBytesToCopy; i++)
{
Assert.Equal(i, array[i + destinationIndexOffset]);
}
}
[Fact]
public static unsafe void MemoryCopy_Invalid()
{
var sourceArray = new int[5000];
var destinationArray = new int[1000];
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceBytesToCopy", () =>
{
fixed (int* sourceBase = sourceArray, destinationBase = destinationArray)
{
Buffer.MemoryCopy(sourceBase, destinationBase, 5000 * 4, 20000 * 4); // Source bytes to copy > destination size in bytes
}
});
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceBytesToCopy", () =>
{
fixed (int* sourceBase = sourceArray, destinationBase = destinationArray)
{
Buffer.MemoryCopy(sourceBase, destinationBase, (ulong)5000 * 4, (ulong)20000 * 4); // Source bytes to copy > destination size in bytes
}
});
}
[Theory]
[InlineData(new uint[] { 0x01234567, 0x89abcdef }, 0, 0x42, new uint[] { 0x01234542, 0x89abcdef })]
[InlineData(new uint[] { 0x01234542, 0x89abcdef }, 7, 0xa2, new uint[] { 0x01234542, 0xa2abcdef })]
public static void SetByte(Array array, int index, byte value, Array expected)
{
Buffer.SetByte(array, index, value);
Assert.Equal(expected, array);
}
[Fact]
public static void SetByte_Invalid()
{
var array = new uint[] { 0x01234567, 0x89abcdef };
AssertExtensions.Throws<ArgumentNullException>("array", () => Buffer.SetByte(null, 0, 0xff)); // Array is null
AssertExtensions.Throws<ArgumentException>("array", () => Buffer.SetByte(new object[10], 0, 0xff)); // Array is not a primitive array
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.SetByte(array, -1, 0xff)); // Index < 0
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Buffer.SetByte(array, 8, 0xff)); // Index > array.Length
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Microsoft.NodejsTools.Jade
{
/// <summary>
/// Represents a range in a text buffer or a string. Specified start and end of text.
/// End is exclusive, i.e. Length = End - Start. Implements IComparable that compares
/// range start positions.
/// </summary>
[DebuggerDisplay("[{Start}...{End}], Length = {Length}")]
internal class TextRange : IExpandableTextRange, ICloneable, IComparable
{
private static TextRange _emptyRange = new TextRange(0, 0);
private int _start;
private int _end;
/// <summary>
/// Returns an empty, invalid range.
/// </summary>
public static TextRange EmptyRange => _emptyRange;
/// <summary>
/// Creates text range starting at position 0
/// and length of 1
/// </summary>
public TextRange()
: this(0)
{
}
/// <summary>
/// Creates text range starting at given position
/// and length of 1.
/// </summary>
/// <param name="position">Start position</param>
public TextRange(int position)
{
this._start = position;
this._end = position < Int32.MaxValue ? position + 1 : position;
}
/// <summary>
/// Creates text range based on start and end positions.
/// End is exclusive, Length = End - Start
/// <param name="start">Range start</param>
/// <param name="length">Range length</param>
/// </summary>
public TextRange(int start, int length)
{
if (length < 0)
throw new ArgumentException("Length must not be negative");
this._start = start;
this._end = start + length;
}
/// <summary>
/// Creates text range based on another text range
/// </summary>
/// <param name="range">Text range to use as position source</param>
public TextRange(ITextRange range)
: this(range.Start, range.Length)
{
}
/// <summary>
/// Resets text range to (0, 0)
/// </summary>
public void Empty()
{
this._start = 0;
this._end = 0;
}
/// <summary>
/// Creates text range based on start and end positions.
/// End is exclusive, Length = End - Start
/// </summary>
/// <param name="start"></param>
/// <param name="end"></param>
public static TextRange FromBounds(int start, int end)
{
return new TextRange(start, end - start);
}
/// <summary>
/// Finds out of range intersects another range
/// </summary>
/// <param name="start">Start of another range</param>
/// <param name="length">Length of another range</param>
/// <returns>True if ranges intersect</returns>
public virtual bool Intersect(int start, int length)
{
return TextRange.Intersect(this, start, length);
}
/// <summary>
/// Finds out of range intersects another range
/// </summary>
/// <param name="start">Text range</param>
/// <returns>True if ranges intersect</returns>
public virtual bool Intersect(ITextRange range)
{
return TextRange.Intersect(this, range.Start, range.Length);
}
/// <summary>
/// Finds out if range represents valid text range (it's length is greater than zero)
/// </summary>
/// <returns>True if range is valid</returns>
public virtual bool IsValid()
{
return TextRange.IsValid(this);
}
#region ITextRange
/// <summary>
/// Text range start position
/// </summary>
public int Start => this._start;
/// <summary>
/// Text range end position (excluded)
/// </summary>
public int End => this._end;
/// <summary>
/// Text range length
/// </summary>
public int Length => this.End - this.Start;
/// <summary>
/// Determines if range contains given position
/// </summary>
public virtual bool Contains(int position)
{
return TextRange.Contains(this, position);
}
/// <summary>
/// Determines if text range fully contains another range
/// </summary>
/// <param name="range"></param>
public virtual bool Contains(ITextRange range)
{
return Contains(range.Start) && Contains(range.End);
}
/// <summary>
/// Determines if element contains one or more of the ranges
/// </summary>
/// <returns></returns>
public virtual bool Contains(IEnumerable<ITextRange> ranges)
{
if (ranges == null)
return false;
var contains = false;
foreach (var range in ranges)
{
if (Contains(range))
{
contains = true;
break;
}
}
return contains;
}
/// <summary>
/// Shifts text range by a given offset
/// </summary>
public void Shift(int offset)
{
this._start += offset;
this._end += offset;
}
public void Expand(int startOffset, int endOffset)
{
if (this._start + startOffset > this._end + endOffset)
throw new ArgumentException("Combination of start and end offsets should not be making range invalid");
this._start += startOffset;
this._end += endOffset;
}
#endregion
[ExcludeFromCodeCoverage]
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "[{0}...{1}]", this.Start, this.End);
}
/// <summary>
/// Determines if ranges are equal. Ranges are equal when they are either both null
/// or both are not null and their coordinates are equal.
/// </summary>
/// <param name="left">First range</param>
/// <param name="right">Second range</param>
/// <returns>True if ranges are equal</returns>
public static bool AreEqual(ITextRange left, ITextRange right)
{
if (Object.ReferenceEquals(left, right))
return true;
// If one is null, but not both, return false.
if (((object)left == null) || ((object)right == null))
return false;
return (left.Start == right.Start) && (left.End == right.End);
}
/// <summary>
/// Determines if range contains given position
/// </summary>
/// <param name="range">Text range</param>
/// <param name="position">Position</param>
/// <returns>True if position is inside the range</returns>
public static bool Contains(ITextRange range, int position)
{
return Contains(range.Start, range.Length, position);
}
/// <summary>
/// Determines if range contains another range
/// </summary>
public static bool Contains(ITextRange range, ITextRange other)
{
var textRange = new TextRange(range);
return textRange.Contains(other);
}
/// <summary>
/// Determines if range contains all ranges in a collection
/// </summary>
public static bool Contains(ITextRange range, IEnumerable<ITextRange> ranges)
{
var textRange = new TextRange(range);
return textRange.Contains(ranges);
}
/// <summary>
/// Determines if range contains given position
/// </summary>
/// <param name="rangeStart">Start of the text range</param>
/// <param name="rangeLength">Length of the text range</param>
/// <param name="position">Position</param>
/// <returns>Tru if position is inside the range</returns>
public static bool Contains(int rangeStart, int rangeLength, int position)
{
if (rangeLength == 0 && position == rangeStart)
return true;
return position >= rangeStart && position < rangeStart + rangeLength;
}
/// <summary>
/// Finds out if range intersects another range
/// </summary>
/// <param name="range1">First text range</param>
/// <param name="range2">Second text range</param>
/// <returns>True if ranges intersect</returns>
public static bool Intersect(ITextRange range1, ITextRange range2)
{
return Intersect(range1, range2.Start, range2.Length);
}
/// <summary>
/// Finds out if range intersects another range
/// </summary>
/// <param name="range">First text range</param>
/// <param name="rangeStart2">Start of the second range</param>
/// <param name="rangeLength2">Length of the second range</param>
/// <returns>True if ranges intersect</returns>
public static bool Intersect(ITextRange range1, int rangeStart2, int rangeLength2)
{
return Intersect(range1.Start, range1.Length, rangeStart2, rangeLength2);
}
/// <summary>
/// Finds out if range intersects another range
/// </summary>
/// <param name="rangeStart1">Start of the first range</param>
/// <param name="rangeLength1">Length of the first range</param>
/// <param name="rangeStart2">Start of the second range</param>
/// <param name="rangeLength2">Length of the second range</param>
/// <returns>True if ranges intersect</returns>
public static bool Intersect(int rangeStart1, int rangeLength1, int rangeStart2, int rangeLength2)
{
// !(rangeEnd2 <= rangeStart1 || rangeStart2 >= rangeEnd1)
// Support intersection with empty ranges
if (rangeLength1 == 0 && rangeLength2 == 0)
return rangeStart1 == rangeStart2;
if (rangeLength1 == 0)
return Contains(rangeStart2, rangeLength2, rangeStart1);
if (rangeLength2 == 0)
return Contains(rangeStart1, rangeLength1, rangeStart2);
return rangeStart2 + rangeLength2 > rangeStart1 && rangeStart2 < rangeStart1 + rangeLength1;
}
/// <summary>
/// Finds out if range represents valid text range (when range is not null and it's length is greater than zero)
/// </summary>
/// <returns>True if range is valid</returns>
public static bool IsValid(ITextRange range)
{
return range != null && range.Length > 0;
}
/// <summary>
/// Calculates range that includes both supplied ranges.
/// </summary>
public static ITextRange Union(ITextRange range1, ITextRange range2)
{
var start = Math.Min(range1.Start, range2.Start);
var end = Math.Max(range1.End, range2.End);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Calculates range that includes both supplied ranges.
/// </summary>
public static ITextRange Union(ITextRange range1, int rangeStart, int rangeLength)
{
var start = Math.Min(range1.Start, rangeStart);
var end = Math.Max(range1.End, rangeStart + rangeLength);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Calculates range that is an intersection of the supplied ranges.
/// </summary>
/// <returns>Intersection or empty range if ranges don't intersect</returns>
public static ITextRange Intersection(ITextRange range1, ITextRange range2)
{
var start = Math.Max(range1.Start, range2.Start);
var end = Math.Min(range1.End, range2.End);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Calculates range that is an intersection of the supplied ranges.
/// </summary>
/// <returns>Intersection or empty range if ranges don't intersect</returns>
public static ITextRange Intersection(ITextRange range1, int rangeStart, int rangeLength)
{
var start = Math.Max(range1.Start, rangeStart);
var end = Math.Min(range1.End, rangeStart + rangeLength);
return start <= end ? TextRange.FromBounds(start, end) : TextRange.EmptyRange;
}
/// <summary>
/// Creates copy of the text range object via memberwise cloning
/// </summary>
public virtual object Clone()
{
return this.MemberwiseClone();
}
public int CompareTo(object obj)
{
var other = obj as TextRange;
if (other == null)
return -1;
return this.Start.CompareTo(other.Start);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return CompareTo(obj) == 0;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public static bool operator ==(TextRange range1, TextRange range2)
{
if ((object)range1 == null && (object)range2 == null)
return true;
if ((object)range1 == null || (object)range2 == null)
return false;
return range1.Equals(range2);
}
public static bool operator !=(TextRange range1, TextRange range2)
{
return !(range1 == range2);
}
public static bool operator <(TextRange range1, TextRange range2)
{
if ((object)range1 == null || (object)range2 == null)
return false;
return range1.CompareTo(range2) < 0;
}
public static bool operator >(TextRange range1, TextRange range2)
{
if ((object)range1 == null || (object)range2 == null)
return false;
return range1.CompareTo(range2) > 0;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlNamedNodeMap.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml {
using System.Collections;
// Represents a collection of nodes that can be accessed by name or index.
public partial class XmlNamedNodeMap : IEnumerable {
internal XmlNode parent;
internal SmallXmlNodeList nodes;
internal XmlNamedNodeMap(XmlNode parent)
{
this.parent = parent;
}
// Retrieves a XmlNode specified by name.
public virtual XmlNode GetNamedItem(String name) {
int offset = FindNodeOffset(name);
if (offset >= 0)
return (XmlNode)nodes[offset];
return null;
}
// Adds a XmlNode using its Name property
public virtual XmlNode SetNamedItem(XmlNode node) {
if ( node == null )
return null;
int offset = FindNodeOffset( node.LocalName, node.NamespaceURI );
if (offset == -1) {
AddNode( node );
return null;
}
else {
return ReplaceNodeAt( offset, node );
}
}
// Removes the node specified by name.
public virtual XmlNode RemoveNamedItem(String name) {
int offset = FindNodeOffset(name);
if (offset >= 0) {
return RemoveNodeAt( offset );
}
return null;
}
// Gets the number of nodes in this XmlNamedNodeMap.
public virtual int Count {
[System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline across NGen image boundaries")]
get {
return nodes.Count;
}
}
// Retrieves the node at the specified index in this XmlNamedNodeMap.
public virtual XmlNode Item(int index) {
if (index < 0 || index >= nodes.Count)
return null;
try {
return (XmlNode)nodes[index];
} catch ( ArgumentOutOfRangeException ) {
throw new IndexOutOfRangeException(Res.GetString(Res.Xdom_IndexOutOfRange));
}
}
//
// DOM Level 2
//
// Retrieves a node specified by LocalName and NamespaceURI.
public virtual XmlNode GetNamedItem(String localName, String namespaceURI) {
int offset = FindNodeOffset( localName, namespaceURI );
if (offset >= 0)
return (XmlNode)nodes[offset];
return null;
}
// Removes a node specified by local name and namespace URI.
public virtual XmlNode RemoveNamedItem(String localName, String namespaceURI) {
int offset = FindNodeOffset( localName, namespaceURI );
if (offset >= 0) {
return RemoveNodeAt( offset );
}
return null;
}
public virtual IEnumerator GetEnumerator() {
return nodes.GetEnumerator();
}
internal int FindNodeOffset( string name ) {
int c = this.Count;
for (int i = 0; i < c; i++) {
XmlNode node = (XmlNode) nodes[i];
if (name == node.Name)
return i;
}
return -1;
}
internal int FindNodeOffset( string localName, string namespaceURI ) {
int c = this.Count;
for (int i = 0; i < c; i++) {
XmlNode node = (XmlNode) nodes[i];
if (node.LocalName == localName && node.NamespaceURI == namespaceURI)
return i;
}
return -1;
}
internal virtual XmlNode AddNode( XmlNode node ) {
XmlNode oldParent;
if ( node.NodeType == XmlNodeType.Attribute )
oldParent = ((XmlAttribute)node).OwnerElement;
else
oldParent = node.ParentNode;
string nodeValue = node.Value;
XmlNodeChangedEventArgs args = parent.GetEventArgs( node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert );
if (args != null)
parent.BeforeEvent( args );
nodes.Add( node );
node.SetParent( parent );
if (args != null)
parent.AfterEvent( args );
return node;
}
internal virtual XmlNode AddNodeForLoad(XmlNode node, XmlDocument doc) {
XmlNodeChangedEventArgs args = doc.GetInsertEventArgsForLoad(node, parent);
if (args != null) {
doc.BeforeEvent(args);
}
nodes.Add(node);
node.SetParent(parent);
if (args != null) {
doc.AfterEvent(args);
}
return node;
}
internal virtual XmlNode RemoveNodeAt( int i ) {
XmlNode oldNode = (XmlNode)nodes[i];
string oldNodeValue = oldNode.Value;
XmlNodeChangedEventArgs args = parent.GetEventArgs( oldNode, parent, null, oldNodeValue, oldNodeValue, XmlNodeChangedAction.Remove );
if (args != null)
parent.BeforeEvent( args );
nodes.RemoveAt(i);
oldNode.SetParent( null );
if (args != null)
parent.AfterEvent( args );
return oldNode;
}
internal XmlNode ReplaceNodeAt( int i, XmlNode node ) {
XmlNode oldNode = RemoveNodeAt( i );
InsertNodeAt( i, node );
return oldNode;
}
internal virtual XmlNode InsertNodeAt( int i, XmlNode node ) {
XmlNode oldParent;
if ( node.NodeType == XmlNodeType.Attribute )
oldParent = ((XmlAttribute)node).OwnerElement;
else
oldParent = node.ParentNode;
string nodeValue = node.Value;
XmlNodeChangedEventArgs args = parent.GetEventArgs( node, oldParent, parent, nodeValue, nodeValue, XmlNodeChangedAction.Insert );
if (args != null)
parent.BeforeEvent( args );
nodes.Insert( i, node );
node.SetParent( parent );
if (args != null)
parent.AfterEvent( args );
return node;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// Original source from https://github.com/PowerShell/PowerShell/blob/f8d6b2f9fefe8467061f04986644aa47c2d10038/src/System.Management.Automation/engine/PSVersionInfo.cs
// Modified to remove PSObj and PSTraceSource use. Includes parsing fix from https://github.com/PowerShell/PowerShell/pull/16608
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace OmniSharp
{
/// <summary>
/// An implementation of semantic versioning (https://semver.org)
/// </summary>
public sealed class SemanticVersion : IComparable, IComparable<SemanticVersion>, IEquatable<SemanticVersion>
{
private const string VersionSansRegEx = @"^(?<major>(0|[1-9]\d*))\.(?<minor>(0|[1-9]\d*))\.(?<patch>(0|[1-9]\d*))$";
private const string LabelRegEx = @"^((?<preLabel>[0-9A-Za-z][0-9A-Za-z\-\.]*))?(\+(?<buildLabel>[0-9A-Za-z][0-9A-Za-z\-\.]*))?$";
private const string LabelUnitRegEx = @"^[0-9A-Za-z][0-9A-Za-z\-\.]*$";
private string versionString;
/// <summary>
/// Construct a SemanticVersion from a string.
/// </summary>
/// <param name="version">The version to parse.</param>
/// <exception cref="FormatException"></exception>
/// <exception cref="OverflowException"></exception>
public SemanticVersion(string version)
{
var v = SemanticVersion.Parse(version);
Major = v.Major;
Minor = v.Minor;
Patch = v.Patch < 0 ? 0 : v.Patch;
PreReleaseLabel = v.PreReleaseLabel;
BuildLabel = v.BuildLabel;
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <param name="patch">The patch version.</param>
/// <param name="preReleaseLabel">The pre-release label for the version.</param>
/// <param name="buildLabel">The build metadata for the version.</param>
/// <exception cref="FormatException">
/// If <paramref name="preReleaseLabel"/> don't match 'LabelUnitRegEx'.
/// If <paramref name="buildLabel"/> don't match 'LabelUnitRegEx'.
/// </exception>
public SemanticVersion(int major, int minor, int patch, string preReleaseLabel, string buildLabel)
: this(major, minor, patch)
{
if (!string.IsNullOrEmpty(preReleaseLabel))
{
if (!Regex.IsMatch(preReleaseLabel, LabelUnitRegEx)) throw new FormatException(nameof(preReleaseLabel));
PreReleaseLabel = preReleaseLabel;
}
if (!string.IsNullOrEmpty(buildLabel))
{
if (!Regex.IsMatch(buildLabel, LabelUnitRegEx)) throw new FormatException(nameof(buildLabel));
BuildLabel = buildLabel;
}
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <param name="patch">The minor version.</param>
/// <param name="label">The label for the version.</param>
/// <exception cref="PSArgumentException">
/// <exception cref="FormatException">
/// If <paramref name="label"/> don't match 'LabelRegEx'.
/// </exception>
public SemanticVersion(int major, int minor, int patch, string label)
: this(major, minor, patch)
{
// We presume the SymVer :
// 1) major.minor.patch-label
// 2) 'label' starts with letter or digit.
if (!string.IsNullOrEmpty(label))
{
var match = Regex.Match(label, LabelRegEx);
if (!match.Success) throw new FormatException(nameof(label));
PreReleaseLabel = match.Groups["preLabel"].Value;
BuildLabel = match.Groups["buildLabel"].Value;
}
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <param name="patch">The minor version.</param>
/// <exception cref="PSArgumentException">
/// If <paramref name="major"/>, <paramref name="minor"/>, or <paramref name="patch"/> is less than 0.
/// </exception>
public SemanticVersion(int major, int minor, int patch)
{
if (major < 0) throw new ArgumentException("Major version cannot be less than 0", nameof(major));
if (minor < 0) throw new ArgumentException("Minor version cannot be less than 0", nameof(minor));
if (patch < 0) throw new ArgumentException("Patch version cannot be less than 0", nameof(patch));
Major = major;
Minor = minor;
Patch = patch;
// We presume:
// PreReleaseLabel = null;
// BuildLabel = null;
}
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <param name="minor">The minor version.</param>
/// <exception cref="PSArgumentException">
/// If <paramref name="major"/> or <paramref name="minor"/> is less than 0.
/// </exception>
public SemanticVersion(int major, int minor) : this(major, minor, 0) { }
/// <summary>
/// Construct a SemanticVersion.
/// </summary>
/// <param name="major">The major version.</param>
/// <exception cref="PSArgumentException">
/// If <paramref name="major"/> is less than 0.
/// </exception>
public SemanticVersion(int major) : this(major, 0, 0) { }
/// <summary>
/// The major version number, never negative.
/// </summary>
public int Major { get; }
/// <summary>
/// The minor version number, never negative.
/// </summary>
public int Minor { get; }
/// <summary>
/// The patch version, -1 if not specified.
/// </summary>
public int Patch { get; }
/// <summary>
/// PreReleaseLabel position in the SymVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'.
/// </summary>
public string PreReleaseLabel { get; }
/// <summary>
/// BuildLabel position in the SymVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'.
/// </summary>
public string BuildLabel { get; }
/// <summary>
/// Parse <paramref name="version"/> and return the result if it is a valid <see cref="SemanticVersion"/>, otherwise throws an exception.
/// </summary>
/// <param name="version">The string to parse.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="FormatException"></exception>
/// <exception cref="OverflowException"></exception>
public static SemanticVersion Parse(string version)
{
if (version == null) throw new ArgumentNullException(nameof(version));
if (version == string.Empty) throw new FormatException(nameof(version));
var r = new VersionResult();
r.Init(true);
TryParseVersion(version, ref r);
return r._parsedVersion;
}
/// <summary>
/// Parse <paramref name="version"/> and return true if it is a valid <see cref="SemanticVersion"/>, otherwise return false.
/// No exceptions are raised.
/// </summary>
/// <param name="version">The string to parse.</param>
/// <param name="result">The return value when the string is a valid <see cref="SemanticVersion"/></param>
public static bool TryParse(string version, out SemanticVersion result)
{
if (version != null)
{
var r = new VersionResult();
r.Init(false);
if (TryParseVersion(version, ref r))
{
result = r._parsedVersion;
return true;
}
}
result = null;
return false;
}
private static bool TryParseVersion(string version, ref VersionResult result)
{
if (version.EndsWith("-") || version.EndsWith("+") || version.EndsWith("."))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
string versionSansLabel = null;
var major = 0;
var minor = 0;
var patch = 0;
string preLabel = null;
string buildLabel = null;
// We parse the SymVer 'version' string 'major.minor.patch-PreReleaseLabel+BuildLabel'.
var dashIndex = version.IndexOf('-');
var plusIndex = version.IndexOf('+');
if (dashIndex > plusIndex)
{
// 'PreReleaseLabel' can contains dashes.
if (plusIndex == -1)
{
// No buildLabel: buildLabel == null
// Format is 'major.minor.patch-PreReleaseLabel'
preLabel = version.Substring(dashIndex + 1);
versionSansLabel = version.Substring(0, dashIndex);
}
else
{
// No PreReleaseLabel: preLabel == null
// Format is 'major.minor.patch+BuildLabel'
buildLabel = version.Substring(plusIndex + 1);
versionSansLabel = version.Substring(0, plusIndex);
dashIndex = -1;
}
}
else
{
if (plusIndex == -1)
{
// Here dashIndex == plusIndex == -1
// No preLabel - preLabel == null;
// No buildLabel - buildLabel == null;
// Format is 'major.minor.patch'
versionSansLabel = version;
}
else if (dashIndex == -1)
{
// No PreReleaseLabel: preLabel == null
// Format is 'major.minor.patch+BuildLabel'
buildLabel = version.Substring(plusIndex + 1);
versionSansLabel = version.Substring(0, plusIndex);
}
else
{
// Format is 'major.minor.patch-PreReleaseLabel+BuildLabel'
preLabel = version.Substring(dashIndex + 1, plusIndex - dashIndex - 1);
buildLabel = version.Substring(plusIndex + 1);
versionSansLabel = version.Substring(0, dashIndex);
}
}
if ((dashIndex != -1 && string.IsNullOrEmpty(preLabel)) ||
(plusIndex != -1 && string.IsNullOrEmpty(buildLabel)) ||
string.IsNullOrEmpty(versionSansLabel))
{
// We have dash and no preReleaseLabel or
// we have plus and no buildLabel or
// we have no main version part (versionSansLabel==null)
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
var match = Regex.Match(versionSansLabel, VersionSansRegEx);
if (!match.Success)
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (!int.TryParse(match.Groups["major"].Value, out major))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (match.Groups["minor"].Success && !int.TryParse(match.Groups["minor"].Value, out minor))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (match.Groups["patch"].Success && !int.TryParse(match.Groups["patch"].Value, out patch))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
if (preLabel != null && !Regex.IsMatch(preLabel, LabelUnitRegEx) ||
(buildLabel != null && !Regex.IsMatch(buildLabel, LabelUnitRegEx)))
{
result.SetFailure(ParseFailureKind.FormatException);
return false;
}
result._parsedVersion = new SemanticVersion(major, minor, patch, preLabel, buildLabel);
return true;
}
/// <summary>
/// Implement ToString()
/// </summary>
public override string ToString()
{
if (versionString == null)
{
var result = new StringBuilder();
result.Append(Major).Append('.').Append(Minor).Append('.').Append(Patch);
if (!string.IsNullOrEmpty(PreReleaseLabel))
{
result.Append('-').Append(PreReleaseLabel);
}
if (!string.IsNullOrEmpty(BuildLabel))
{
result.Append('+').Append(BuildLabel);
}
versionString = result.ToString();
}
return versionString;
}
/// <summary>
/// Implement Compare.
/// </summary>
public static int Compare(SemanticVersion versionA, SemanticVersion versionB)
{
if (versionA != null)
{
return versionA.CompareTo(versionB);
}
if (versionB != null)
{
return -1;
}
return 0;
}
/// <summary>
/// Implement <see cref="IComparable.CompareTo"/>
/// </summary>
public int CompareTo(object version)
{
if (version == null)
{
return 1;
}
return CompareTo(version as SemanticVersion);
}
/// <summary>
/// Implement <see cref="IComparable{T}.CompareTo"/>.
/// Meets SymVer 2.0 p.11 https://semver.org/
/// </summary>
public int CompareTo(SemanticVersion value)
{
if (value is null)
return 1;
if (Major != value.Major)
return Major > value.Major ? 1 : -1;
if (Minor != value.Minor)
return Minor > value.Minor ? 1 : -1;
if (Patch != value.Patch)
return Patch > value.Patch ? 1 : -1;
// SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata).
return ComparePreLabel(this.PreReleaseLabel, value.PreReleaseLabel);
}
/// <summary>
/// Override <see cref="object.Equals(object)"/>
/// </summary>
public override bool Equals(object obj)
{
return Equals(obj as SemanticVersion);
}
/// <summary>
/// Implement <see cref="IEquatable{T}.Equals(T)"/>
/// </summary>
public bool Equals(SemanticVersion other)
{
// SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata).
return other != null &&
(Major == other.Major) && (Minor == other.Minor) && (Patch == other.Patch) &&
string.Equals(PreReleaseLabel, other.PreReleaseLabel, StringComparison.Ordinal);
}
/// <summary>
/// Override <see cref="object.GetHashCode()"/>
/// </summary>
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
/// <summary>
/// Overloaded == operator.
/// </summary>
public static bool operator ==(SemanticVersion v1, SemanticVersion v2)
{
if (v1 is null)
{
return v2 is null;
}
return v1.Equals(v2);
}
/// <summary>
/// Overloaded != operator.
/// </summary>
public static bool operator !=(SemanticVersion v1, SemanticVersion v2)
{
return !(v1 == v2);
}
/// <summary>
/// Overloaded < operator.
/// </summary>
public static bool operator <(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) < 0);
}
/// <summary>
/// Overloaded <= operator.
/// </summary>
public static bool operator <=(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) <= 0);
}
/// <summary>
/// Overloaded > operator.
/// </summary>
public static bool operator >(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) > 0);
}
/// <summary>
/// Overloaded >= operator.
/// </summary>
public static bool operator >=(SemanticVersion v1, SemanticVersion v2)
{
return (Compare(v1, v2) >= 0);
}
private static int ComparePreLabel(string preLabel1, string preLabel2)
{
// Symver 2.0 standard p.9
// Pre-release versions have a lower precedence than the associated normal version.
// Comparing each dot separated identifier from left to right
// until a difference is found as follows:
// identifiers consisting of only digits are compared numerically
// and identifiers with letters or hyphens are compared lexically in ASCII sort order.
// Numeric identifiers always have lower precedence than non-numeric identifiers.
// A larger set of pre-release fields has a higher precedence than a smaller set,
// if all of the preceding identifiers are equal.
if (string.IsNullOrEmpty(preLabel1)) { return string.IsNullOrEmpty(preLabel2) ? 0 : 1; }
if (string.IsNullOrEmpty(preLabel2)) { return -1; }
var units1 = preLabel1.Split('.');
var units2 = preLabel2.Split('.');
var minLength = units1.Length < units2.Length ? units1.Length : units2.Length;
for (int i = 0; i < minLength; i++)
{
var ac = units1[i];
var bc = units2[i];
int number1, number2;
var isNumber1 = Int32.TryParse(ac, out number1);
var isNumber2 = Int32.TryParse(bc, out number2);
if (isNumber1 && isNumber2)
{
if (number1 != number2) { return number1 < number2 ? -1 : 1; }
}
else
{
if (isNumber1) { return -1; }
if (isNumber2) { return 1; }
int result = string.CompareOrdinal(ac, bc);
if (result != 0) { return result; }
}
}
return units1.Length.CompareTo(units2.Length);
}
internal enum ParseFailureKind
{
ArgumentException,
ArgumentOutOfRangeException,
FormatException
}
internal struct VersionResult
{
internal SemanticVersion _parsedVersion;
internal ParseFailureKind _failure;
internal string _exceptionArgument;
internal bool _canThrow;
internal void Init(bool canThrow)
{
_canThrow = canThrow;
}
internal void SetFailure(ParseFailureKind failure)
{
SetFailure(failure, string.Empty);
}
internal void SetFailure(ParseFailureKind failure, string argument)
{
_failure = failure;
_exceptionArgument = argument;
if (_canThrow)
{
throw GetVersionParseException();
}
}
internal Exception GetVersionParseException()
{
switch (_failure)
{
case ParseFailureKind.ArgumentException:
return new ArgumentException("version");
case ParseFailureKind.ArgumentOutOfRangeException:
throw new ArgumentOutOfRangeException("version");
case ParseFailureKind.FormatException:
// Regenerate the FormatException as would be thrown by Int32.Parse()
try
{
int.Parse(_exceptionArgument, CultureInfo.InvariantCulture);
}
catch (FormatException e)
{
return e;
}
catch (OverflowException e)
{
return e;
}
break;
}
return new ArgumentException("version");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Streams;
namespace Orleans
{
/// <summary>
/// Client runtime for connecting to Orleans system
/// </summary>
[Obsolete("This type is obsolete and may be removed in a future release. Use ClientBuilder to create an instance of IClusterClient instead.")]
public static class GrainClient
{
/// <summary>
/// Whether the client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
public static bool IsInitialized => isFullyInitialized && client.IsInitialized;
internal static ClientConfiguration CurrentConfig => client.Configuration();
internal static bool TestOnlyNoConnect { get; set; }
private static bool isFullyInitialized = false;
private static IInternalClusterClient client;
private static readonly object initLock = new Object();
public static IClusterClient Instance => client;
public static IGrainFactory GrainFactory => GetGrainFactory();
/// <summary>delegate to configure logging, default to none logger configured</summary>
public static Action<ILoggingBuilder> ConfigureLoggingDelegate { get; set; } = builder => { };
/// <summary>delegate to add some configuration to the client</summary>
public static Action<IClientBuilder> ConfigureClientDelegate { get; set; } = builder => { };
private static IGrainFactory GetGrainFactory()
{
if (!IsInitialized)
{
throw new OrleansException("You must initialize the Grain Client before accessing the GrainFactory");
}
return client;
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file.
/// </summary>
public static void Initialize()
{
ClientConfiguration config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFilePath">A relative or absolute pathname for the client configuration file.</param>
public static void Initialize(string configFilePath)
{
Initialize(new FileInfo(configFilePath));
}
/// <summary>
/// Initializes the client runtime from the provided client configuration file.
/// If an error occurs reading the specified configuration file, the initialization fails.
/// </summary>
/// <param name="configFile">The client configuration file.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public static void Initialize(FileInfo configFile)
{
ClientConfiguration config;
try
{
config = ClientConfiguration.LoadFromFile(configFile.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error loading client configuration file {0}: {1}", configFile.FullName, ex);
throw;
}
if (config == null)
{
Console.WriteLine("Error loading client configuration file {0}:", configFile.FullName);
throw new ArgumentException(string.Format("Error loading client configuration file {0}:", configFile.FullName), nameof(configFile));
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
public static void Initialize(ClientConfiguration config)
{
if (config == null)
{
Console.WriteLine("Initialize was called with null ClientConfiguration object.");
throw new ArgumentException("Initialize was called with null ClientConfiguration object.", nameof(config));
}
InternalInitialize(config);
}
/// <summary>
/// Initializes the client runtime from the standard client configuration file using the provided gateway address.
/// Any gateway addresses specified in the config file will be ignored and the provided gateway address wil be used instead.
/// </summary>
/// <param name="gatewayAddress">IP address and port of the gateway silo</param>
/// <param name="overrideConfig">Whether the specified gateway endpoint should override / replace the values from config file, or be additive</param>
public static void Initialize(IPEndPoint gatewayAddress, bool overrideConfig = true)
{
var config = ClientConfiguration.StandardLoad();
if (config == null)
{
Console.WriteLine("Error loading standard client configuration file.");
throw new ArgumentException("Error loading standard client configuration file");
}
if (overrideConfig)
{
config.Gateways = new List<IPEndPoint>(new[] { gatewayAddress });
}
else if (!config.Gateways.Contains(gatewayAddress))
{
config.Gateways.Add(gatewayAddress);
}
config.PreferedGatewayIndex = config.Gateways.IndexOf(gatewayAddress);
InternalInitialize(config);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void InternalInitialize(ClientConfiguration config)
{
var builder = new ClientBuilder()
.ConfigureApplicationParts(parts => parts.ConfigureDefaults())
.UseConfiguration(config)
.ConfigureLogging(ConfigureLoggingDelegate);
ConfigureClientDelegate?.Invoke(builder);
var clusterClient = (IInternalClusterClient)builder.Build();
if (TestOnlyNoConnect)
{
Trace.TraceInformation("TestOnlyNoConnect - Returning before connecting to cluster.");
}
else
{
// Finish initializing this client connection to the Orleans cluster
DoInternalInitialize(clusterClient);
}
}
/// <summary>
/// Initializes client runtime from client configuration object.
/// </summary>
private static void DoInternalInitialize(IInternalClusterClient clusterClient)
{
if (IsInitialized)
return;
lock (initLock)
{
if (!IsInitialized)
{
try
{
// this is probably overkill, but this ensures isFullyInitialized false
// before we make a call that makes RuntimeClient.Current not null
isFullyInitialized = false;
client = clusterClient; // Keep reference, to avoid GC problems
client.Connect().GetAwaiter().GetResult();
// this needs to be the last successful step inside the lock so
// IsInitialized doesn't return true until we're fully initialized
isFullyInitialized = true;
}
catch (Exception exc)
{
// just make sure to fully Uninitialize what we managed to partially initialize, so we don't end up in inconsistent state and can later on re-initialize.
Console.WriteLine("Initialization failed. {0}", exc);
InternalUninitialize();
throw;
}
}
}
}
/// <summary>
/// Uninitializes client runtime.
/// </summary>
public static void Uninitialize()
{
lock (initLock)
{
InternalUninitialize();
}
}
/// <summary>
/// Test hook to uninitialize client without cleanup
/// </summary>
public static void HardKill()
{
lock (initLock)
{
InternalUninitialize(false);
}
}
/// <summary>
/// This is the lock free version of uninitialize so we can share
/// it between the public method and error paths inside initialize.
/// This should only be called inside a lock(initLock) block.
/// </summary>
private static void InternalUninitialize(bool cleanup = true)
{
// Update this first so IsInitialized immediately begins returning
// false. Since this method should be protected externally by
// a lock(initLock) we should be able to reset everything else
// before the next init attempt.
isFullyInitialized = false;
try
{
if (cleanup)
{
client?.Close().GetAwaiter().GetResult();
}
else
{
client?.AbortAsync().GetAwaiter().GetResult();
}
}
catch (Exception)
{
}
finally
{
client?.Dispose();
client = null;
}
}
/// <summary>
/// Check that the runtime is initialized correctly, and throw InvalidOperationException if not
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
private static void CheckInitialized()
{
if (!IsInitialized)
throw new InvalidOperationException("Runtime is not initialized. Call Client.Initialize method to initialize the runtime.");
}
/// <summary>
/// Set a timeout for responses on this Orleans client.
/// </summary>
/// <param name="timeout"></param>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static void SetResponseTimeout(TimeSpan timeout)
{
CheckInitialized();
RuntimeClient.SetResponseTimeout(timeout);
}
/// <summary>
/// Get a timeout of responses on this Orleans client.
/// </summary>
/// <returns>The response timeout.</returns>
/// <exception cref="InvalidOperationException">Thrown if Orleans runtime is not correctly initialized before this call.</exception>
public static TimeSpan GetResponseTimeout()
{
CheckInitialized();
return RuntimeClient.GetResponseTimeout();
}
/// <summary>
/// Global pre-call interceptor function
/// Synchronous callback made just before a message is about to be constructed and sent by a client to a grain.
/// This call will be made from the same thread that constructs the message to be sent, so any thread-local settings
/// such as <c>Orleans.RequestContext</c> will be picked up.
/// The action receives an InvokeMethodRequest with details of the method to be invoked, including InterfaceId and MethodId,
/// and a <see cref="IGrain"/> which is the GrainReference this request is being sent through
/// </summary>
/// <remarks>This callback method should return promptly and do a minimum of work, to avoid blocking calling thread or impacting throughput.</remarks>
public static ClientInvokeCallback ClientInvokeCallback
{
get
{
CheckInitialized();
return RuntimeClient.ClientInvokeCallback;
}
set
{
CheckInitialized();
RuntimeClient.ClientInvokeCallback = value;
}
}
internal static IStreamProviderRuntime CurrentStreamProviderRuntime
{
get
{
CheckInitialized();
return client.StreamProviderRuntime;
}
}
public static IStreamProvider GetStreamProvider(string name)
{
CheckInitialized();
return client.GetStreamProvider(name);
}
public static event ConnectionToClusterLostHandler ClusterConnectionLost
{
add
{
CheckInitialized();
RuntimeClient.ClusterConnectionLost += value;
}
remove
{
CheckInitialized();
RuntimeClient.ClusterConnectionLost -= value;
}
}
private static OutsideRuntimeClient RuntimeClient => client.ServiceProvider.GetRequiredService<OutsideRuntimeClient>();
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Represents a runtime execution context for C# scripts.
/// </summary>
internal abstract class ScriptEngine
{
public static readonly ImmutableArray<string> DefaultReferenceSearchPaths;
// state captured by session at creation time:
private ScriptOptions _options = ScriptOptions.Default;
private readonly ScriptBuilder _builder;
static ScriptEngine()
{
DefaultReferenceSearchPaths = ImmutableArray.Create(RuntimeEnvironment.GetRuntimeDirectory());
}
internal ScriptEngine(MetadataFileReferenceProvider metadataReferenceProvider)
{
if (metadataReferenceProvider == null)
{
metadataReferenceProvider = _options.AssemblyResolver.Provider;
}
_builder = new ScriptBuilder();
_options = _options.WithReferenceProvider(metadataReferenceProvider);
string initialBaseDirectory;
try
{
initialBaseDirectory = Directory.GetCurrentDirectory();
}
catch
{
initialBaseDirectory = null;
}
_options = _options.WithBaseDirectory(initialBaseDirectory);
}
public MetadataFileReferenceProvider MetadataReferenceProvider
{
get { return _options.AssemblyResolver.Provider; }
}
internal ScriptBuilder Builder
{
get { return _builder; }
}
// TODO (tomat): Consider exposing FileResolver and removing BaseDirectory.
// We would need WithAssemblySearchPaths on FileResolver to implement SetReferenceSearchPaths
internal MetadataFileReferenceResolver MetadataReferenceResolver
{
get
{
return _options.AssemblyResolver.PathResolver;
}
// for testing
set
{
Debug.Assert(value != null);
_options = _options.WithReferenceResolver(value);
}
}
internal abstract Script Create(string code, ScriptOptions options, Type globalsType, Type returnType);
#region Session
public Session CreateSession() // TODO (tomat): bool isCancellable = false
{
return new Session(this, _options, null);
}
public Session CreateSession(object hostObject) // TODO (tomat): bool isCancellable = false
{
if (hostObject == null)
{
throw new ArgumentNullException(nameof(hostObject));
}
return new Session(this, _options, hostObject, hostObject.GetType());
}
public Session CreateSession(object hostObject, Type hostObjectType) // TODO (tomat): bool isCancellable = false
{
if (hostObject == null)
{
throw new ArgumentNullException(nameof(hostObject));
}
if (hostObjectType == null)
{
throw new ArgumentNullException(nameof(hostObjectType));
}
Type actualType = hostObject.GetType();
if (!hostObjectType.IsAssignableFrom(actualType))
{
throw new ArgumentException(String.Format(ScriptingResources.CantAssignTo, actualType, hostObjectType), "hostObjectType");
}
return new Session(this, _options, hostObject, hostObjectType);
}
public Session CreateSession<THostObject>(THostObject hostObject) // TODO (tomat): bool isCancellable = false
where THostObject : class
{
if (hostObject == null)
{
throw new ArgumentNullException(nameof(hostObject));
}
return new Session(this, _options, hostObject, typeof(THostObject));
}
#endregion
#region State
/// <summary>
/// The base directory used to resolve relative paths to assembly references and
/// relative paths that appear in source code compiled by this script engine.
/// </summary>
/// <remarks>
/// If null relative paths won't be resolved and an error will be reported when the compiler encounters such paths.
/// The value can be changed at any point in time. However the new value doesn't affect already compiled submissions.
/// The initial value is the current working directory if the current process, or null if not available.
/// Changing the base directory doesn't affect the process current working directory used by <see cref="System.IO"/> APIs.
/// </remarks>
public string BaseDirectory
{
get
{
return _options.BaseDirectory;
}
set
{
_options = _options.WithBaseDirectory(value);
}
}
public ImmutableArray<string> ReferenceSearchPaths
{
get { return _options.SearchPaths; }
}
public void SetReferenceSearchPaths(params string[] paths)
{
SetReferenceSearchPaths(ImmutableArray.CreateRange<string>(paths));
}
public void SetReferenceSearchPaths(IEnumerable<string> paths)
{
SetReferenceSearchPaths(ImmutableArray.CreateRange<string>(paths));
}
public void SetReferenceSearchPaths(ImmutableArray<string> paths)
{
MetadataFileReferenceResolver.ValidateSearchPaths(paths, "paths");
_options = _options.WithSearchPaths(paths);
}
/// <summary>
/// Returns a list of assemblies that are currently referenced by the engine.
/// </summary>
public ImmutableArray<MetadataReference> GetReferences()
{
return _options.References;
}
/// <summary>
/// Adds a reference to specified assembly.
/// </summary>
/// <param name="assemblyDisplayNameOrPath">Assembly display name or path.</param>
/// <exception cref="ArgumentNullException"><paramref name="assemblyDisplayNameOrPath"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="assemblyDisplayNameOrPath"/> is empty.</exception>
/// <exception cref="FileNotFoundException">Assembly file can't be found.</exception>
public void AddReference(string assemblyDisplayNameOrPath)
{
if (assemblyDisplayNameOrPath == null)
{
throw new ArgumentNullException(nameof(assemblyDisplayNameOrPath));
}
_options = _options.AddReferences(assemblyDisplayNameOrPath);
}
/// <summary>
/// Adds a reference to specified assembly.
/// </summary>
/// <param name="assembly">Runtime assembly. The assembly must be loaded from a file on disk. In-memory assemblies are not supported.</param>
/// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception>
public void AddReference(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
_options = _options.AddReferences(assembly);
}
/// <summary>
/// Adds a reference to specified assembly.
/// </summary>
/// <param name="reference">Assembly reference.</param>
/// <exception cref="ArgumentException"><paramref name="reference"/> is not an assembly reference (it's a module).</exception>
/// <exception cref="ArgumentNullException"><paramref name="reference"/> is null.</exception>
public void AddReference(MetadataReference reference)
{
if (reference == null)
{
throw new ArgumentNullException(nameof(reference));
}
if (reference.Properties.Kind != MetadataImageKind.Assembly)
{
throw new ArgumentException(ScriptingResources.ExpectedAnAssemblyReference, nameof(reference));
}
_options = _options.AddReferences(reference);
}
/// <summary>
/// Returns a list of imported namespaces.
/// </summary>
public ImmutableArray<string> GetImportedNamespaces()
{
return _options.Namespaces;
}
/// <summary>
/// Imports a namespace, an equivalent of executing "using <paramref name="namespace"/>;" (C#) or "Imports <paramref name="namespace"/>" (VB).
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="namespace"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="namespace"/> is not a valid namespace name.</exception>
public void ImportNamespace(string @namespace)
{
ValidateNamespace(@namespace);
// we don't report duplicates to get the same behavior as evaluating "using NS;" twice.
_options = _options.AddNamespaces(@namespace);
}
internal static void ValidateNamespace(string @namespace)
{
if (@namespace == null)
{
throw new ArgumentNullException(nameof(@namespace));
}
// Only check that the namespace is a CLR namespace name.
// If the namespace doesn't exist an error will be reported when compiling the next submission.
if (!@namespace.IsValidClrNamespaceName())
{
throw new ArgumentException("Invalid namespace name", nameof(@namespace));
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using ServiceStack.DataAnnotations;
using System.ComponentModel.DataAnnotations;
namespace ServiceStack.OrmLite.Tests
{
[TestFixture]
public class OrmLiteGetScalarTests:OrmLiteTestBase
{
[Test]
public void Can_get_scalar_value(){
List<Author> authors = new List<Author>();
authors.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London", FloatProperty=10.25f, DoubleProperty=3.23 });
authors.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota",FloatProperty=7.59f,DoubleProperty=4.23 });
authors.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London",FloatProperty=15.5f,DoubleProperty=5.42 });
authors.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota",FloatProperty=0.57f, DoubleProperty=8.76});
authors.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=8.43f, DoubleProperty=7.35});
authors.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=1.25f, DoubleProperty=0.3652});
authors.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota", FloatProperty=1.5f, DoubleProperty=100.563});
authors.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena", FloatProperty=3.5f,DoubleProperty=7.23 });
authors.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena", FloatProperty=0.25f,DoubleProperty=9.23 });
authors.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London", FloatProperty=9.95f,DoubleProperty=4.91 });
authors.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin",FloatProperty=4.44f,DoubleProperty=6.41 });
authors.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid", FloatProperty=6.67f, DoubleProperty=8.05 });
authors.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid", FloatProperty=1.25f, DoubleProperty=3.99});
authors.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10,
City = "Mexico",
LastActivity= DateTime.Today,
NRate=5,
FloatProperty=1.25f,
NFloatProperty=3.15f,
DoubleProperty= 1.25,
NDoubleProperty= 8.25
});
using (var db = ConnectionString.OpenDbConnection())
{
db.CreateTable<Author>(true);
db.DeleteAll<Author>();
db.InsertAll(authors);
var expectedDate = authors.Max(e=>e.Birthday);
var r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday) );
Assert.That(expectedDate, Is.EqualTo(r1));
expectedDate = authors.Where(e=>e.City=="London").Max(e=>e.Birthday);
r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="London" );
Assert.That(expectedDate, Is.EqualTo(r1));
r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="SinCity" );
Assert.That( default(DateTime), Is.EqualTo(r1));
var expectedNullableDate= authors.Max(e=>e.LastActivity);
DateTime? r2 = db.GetScalar<Author,DateTime?>(e=> Sql.Max(e.LastActivity));
Assert.That(expectedNullableDate, Is.EqualTo(r2));
expectedNullableDate= authors.Where(e=> e.City=="Bogota").Max(e=>e.LastActivity);
r2 = db.GetScalar<Author,DateTime?>(
e=> Sql.Max(e.LastActivity),
e=> e.City=="Bogota" );
Assert.That(expectedNullableDate, Is.EqualTo(r2));
r2 = db.GetScalar<Author, DateTime?>( e => Sql.Max(e.LastActivity), e=>e.City=="SinCity" );
Assert.That( default(DateTime?), Is.EqualTo(r2));
var expectedDecimal= authors.Max(e=>e.Earnings);
decimal r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings));
Assert.That(expectedDecimal, Is.EqualTo(r3));
expectedDecimal= authors.Where(e=>e.City=="London").Max(e=>e.Earnings);
r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="London");
Assert.That(expectedDecimal, Is.EqualTo(r3));
r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="SinCity");
Assert.That( default(decimal), Is.EqualTo(r3));
var expectedNullableDecimal= authors.Max(e=>e.NEarnings);
decimal? r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings));
Assert.That(expectedNullableDecimal, Is.EqualTo(r4));
expectedNullableDecimal= authors.Where(e=>e.City=="London").Max(e=>e.NEarnings);
r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="London");
Assert.That(expectedNullableDecimal, Is.EqualTo(r4));
r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="SinCity");
Assert.That( default(decimal?), Is.EqualTo(r4));
var expectedDouble =authors.Max(e=>e.DoubleProperty);
double r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty));
Assert.That(expectedDouble, Is.EqualTo(r5));
expectedDouble =authors.Where(e=>e.City=="London").Max(e=>e.DoubleProperty);
r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="London");
Assert.That(expectedDouble, Is.EqualTo(r5));
r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="SinCity");
Assert.That(default(double),Is.EqualTo(r5));
var expectedNullableDouble =authors.Max(e=>e.NDoubleProperty);
double? r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty));
Assert.That(expectedNullableDouble, Is.EqualTo(r6));
expectedNullableDouble =authors.Where(e=>e.City=="London").Max(e=>e.NDoubleProperty);
r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="London");
Assert.That(expectedNullableDouble, Is.EqualTo(r6));
r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="SinCity");
Assert.That(default(double?),Is.EqualTo(r6));
var expectedFloat =authors.Max(e=>e.FloatProperty);
var r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty));
Assert.That(expectedFloat, Is.EqualTo(r7));
expectedFloat =authors.Where(e=>e.City=="London").Max(e=>e.FloatProperty);
r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="London");
Assert.That(expectedFloat, Is.EqualTo(r7));
r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="SinCity");
Assert.That(default(float),Is.EqualTo(r7));
var expectedNullableFloat =authors.Max(e=>e.NFloatProperty);
var r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty));
Assert.That(expectedNullableFloat, Is.EqualTo(r8));
expectedNullableFloat =authors.Where(e=>e.City=="London").Max(e=>e.NFloatProperty);
r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="London");
Assert.That(expectedNullableFloat, Is.EqualTo(r8));
r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="SinCity");
Assert.That(default(float?),Is.EqualTo(r8));
var expectedString=authors.Min(e=>e.Name);
var r9 = db.GetScalar<Author,string>(e=> Sql.Min(e.Name));
Assert.That(expectedString, Is.EqualTo(r9));
expectedString=authors.Where(e=>e.City=="London").Min(e=>e.Name);
r9 = db.GetScalar<Author,string>(e=> Sql.Min(e.Name), e=>e.City=="London");
Assert.That(expectedString, Is.EqualTo(r9));
r9 = db.GetScalar<Author,string>(e=> Sql.Max(e.Name), e=>e.City=="SinCity");
Assert.IsNullOrEmpty(r9);
//Can't MIN(bit)/MAX(bit) in SQL Server
var expectedBool=authors.Min(e=>e.Active);
var r10 = db.GetScalar<Author, bool>(e => Sql.Count(e.Active));
Assert.That(expectedBool, Is.EqualTo(r10));
expectedBool=authors.Max(e=>e.Active);
r10 = db.GetScalar<Author, bool>(e => Sql.Count(e.Active));
Assert.That(expectedBool, Is.EqualTo(r10));
r10 = db.GetScalar<Author, bool>(e => Sql.Count(e.Active), e => e.City == "SinCity");
Assert.IsFalse(r10);
var expectedShort =authors.Max(e=>e.Rate);
var r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate));
Assert.That(expectedShort, Is.EqualTo(r11));
expectedShort =authors.Where(e=>e.City=="London").Max(e=>e.Rate);
r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="London");
Assert.That(expectedShort, Is.EqualTo(r11));
r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="SinCity");
Assert.That(default(short),Is.EqualTo(r7));
var expectedNullableShort =authors.Max(e=>e.NRate);
var r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate));
Assert.That(expectedNullableShort, Is.EqualTo(r12));
expectedNullableShort =authors.Where(e=>e.City=="London").Max(e=>e.NRate);
r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="London");
Assert.That(expectedNullableShort, Is.EqualTo(r12));
r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="SinCity");
Assert.That(default(short?),Is.EqualTo(r12));
}
}
}
public class Author
{
public Author(){}
[AutoIncrement]
[Alias("AuthorID")]
public Int32 Id { get; set;}
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set;}
public DateTime Birthday { get; set;}
public DateTime? LastActivity { get; set;}
public decimal Earnings { get; set;}
public decimal? NEarnings { get; set;}
public bool Active { get; set; }
[StringLength(80)]
[Alias("JobCity")]
public string City { get; set;}
[StringLength(80)]
[Alias("Comment")]
public string Comments { get; set;}
public short Rate{ get; set;}
public short? NRate{ get; set;}
public float FloatProperty { get; set;}
public float? NFloatProperty { get; set;}
public double DoubleProperty { get; set;}
public double? NDoubleProperty { get; set;}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Text.RegularExpressions;
using Gallio.Framework.Assertions;
using MbUnit.Framework;
namespace MbUnit.Tests.Framework
{
[TestsOn(typeof(Assert))]
public class AssertTest_Strings : BaseAssertTest
{
#region Contains
[Test]
public void Contains_simple_test()
{
Assert.Contains("Abcdef", "cde");
}
[Test]
public void Contains_fails_when_simple_substring_is_not_found()
{
AssertionFailure[] failures = Capture(() => Assert.Contains("ABCDEF","xyz"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to contain a particular substring.", failures[0].Description);
Assert.AreEqual("Expected Substring", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"xyz\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"ABCDEF\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test, ExpectedArgumentNullException("Value cannot be null.")]
public void Contains_fails_when_expected_substring_is_null()
{
Assert.Contains("Abcdef", null);
}
[Test]
public void Contains_fail_test_with_custom_message()
{
AssertionFailure[] failures = Capture(() => Assert.Contains("ABCDEF", "xyz","{0} message", "custom"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to contain a particular substring.", failures[0].Description);
Assert.AreEqual("Expected Substring", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"xyz\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"ABCDEF\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("custom message", failures[0].Message);
}
[Test]
public void Contains_with_comparison_type_simple_test()
{
Assert.Contains("Abcdef", "CDe", StringComparison.OrdinalIgnoreCase);
}
#endregion
#region DoesNotContain
[Test]
public void DoesNotContain_simple_test()
{
Assert.DoesNotContain("Abcdef", "xyz");
}
[Test]
public void DoesNotContain_should_not_find_substring_with_different_casing()
{
Assert.DoesNotContain("Abcdef", "ABC");
}
[Test]
public void DoesNotContain_fails_when_simple_substring_is_found()
{
AssertionFailure[] failures = Capture(() => Assert.DoesNotContain("ABCDEF", "ABCDE"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to not contain a particular substring.", failures[0].Description);
Assert.AreEqual("Unexpected Substring", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"ABCDE\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"ABCDEF\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test, ExpectedArgumentNullException("Value cannot be null.")]
public void DoesNotContain_fails_when_expected_substring_is_null()
{
Assert.DoesNotContain("Abcdef", null);
}
[Test]
public void DoesNotContain_fail_test_with_custom_message()
{
AssertionFailure[] failures = Capture(() => Assert.DoesNotContain("ABCDEF", "BCD", "{0} message", "custom"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to not contain a particular substring.", failures[0].Description);
Assert.AreEqual("Unexpected Substring", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"BCD\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"ABCDEF\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("custom message", failures[0].Message);
}
[Test]
public void DoesNotContain_with_comparison_type_simple_test()
{
Assert.DoesNotContain("Abcdef", "xyz", StringComparison.OrdinalIgnoreCase);
}
[Test]
public void DoesNotContain_with_comparison_type_fail_test_with_custom_message()
{
AssertionFailure[] failures = Capture(() => Assert.DoesNotContain("ABCDEF", "bcD", StringComparison.OrdinalIgnoreCase, "{0} message", "custom"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to not contain a particular substring.", failures[0].Description);
Assert.AreEqual("Comparison Type", failures[0].LabeledValues[0].Label);
Assert.AreEqual("{OrdinalIgnoreCase}", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Unexpected Substring", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"bcD\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("\"ABCDEF\"", failures[0].LabeledValues[2].FormattedValue.ToString());
Assert.AreEqual("custom message", failures[0].Message);
}
#endregion
#region AreEqual
[Test]
public void AreEqualIgnoreCase_Test_with_non_null_values()
{
Assert.AreEqual("test", "TeSt", StringComparison.InvariantCultureIgnoreCase);
}
[Test]
public void AreEqualIgnoreCase_fails_when_simple_values_different()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.AreEqual("test", "tEsm", StringComparison.InvariantCultureIgnoreCase));
Assert.Count(1, failures);
Assert.AreEqual("Expected values to be equal according to string comparison type.", failures[0].Description);
Assert.AreEqual("Comparison Type", failures[0].LabeledValues[0].Label);
Assert.AreEqual("{InvariantCultureIgnoreCase}", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Expected Value", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"test\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("Actual Value", failures[0].LabeledValues[2].Label);
Assert.AreEqual("\"tEsm\"", failures[0].LabeledValues[2].FormattedValue.ToString());
}
[Test]
public void AreEqualIgnoreCase_fails_when_one_of_the_values_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.AreEqual("test", null, StringComparison.InvariantCultureIgnoreCase));
Assert.Count(1, failures);
Assert.AreEqual("{InvariantCultureIgnoreCase}", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"test\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("null", failures[0].LabeledValues[2].FormattedValue.ToString());
}
[Test]
public void AreEqualIgnoreCase_fails_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.AreEqual(null, "test", "{0} message {1}", "MB1", "Mb2", StringComparison.InvariantCultureIgnoreCase));
Assert.Count(1, failures);
Assert.AreEqual("null", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"test\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
#endregion
#region FullMatch
[Test]
public void FullMatch_sucessful_tests_with_Regex()
{
Assert.FullMatch("mbTest", new Regex(@"[\w]{6}"));
}
[Test]
public void FullMatch_sucessful_with_pattern()
{
Assert.FullMatch("mbTest", @"[\w]{6}");
}
[Test, ExpectedArgumentNullException]
public void FullMatch_test_for_ArgumentNullException_when_regex_is_null()
{
const Regex re = null;
Assert.FullMatch("mbTest", re);
}
[Test, ExpectedArgumentNullException]
public void FullMatch_test_for_ArgumentNullException_when_pattern_is_null()
{
const string pattern = null;
Assert.FullMatch("mbTest", pattern);
}
[Test]
public void FullMatch_fails_when_testValue_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.FullMatch(null, new Regex(@"[\d]{6}")));
Assert.Count(1, failures);
}
[Test]
public void FullMatch_fails_when_testValue_does_not_match_regex_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.FullMatch("mbTest", new Regex(@"[\d]{6}")));
Assert.Count(1, failures);
Assert.AreEqual("Expected a string to exactly match a regular expression pattern.", failures[0].Description);
Assert.AreEqual("Actual Value", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Regex Pattern", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"[\\\\d]{6}\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test]
public void FullMatch_fails_when_testValue_matches_regex_pattern_but_lenght_is_different()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.FullMatch("mbTest", new Regex(@"[\w]{7}")));
Assert.Count(1, failures);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("\"[\\\\w]{7}\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test]
public void FullMatch_fail_test_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.FullMatch("mbTest", new Regex(@"[\w]{7}"), "{0} message {1}", "MB1", "Mb2"));
Assert.Count(1, failures);
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
#endregion
#region Like
[Test]
public void Like_sucessful_tests_with_Regex()
{
Assert.Like("mbTest", new Regex(@"[\w]+"));
}
[Test]
public void Like_sucessful_with_pattern()
{
Assert.Like("mbTest", @"[\w]*");
}
[Test]
public void Like_fails_when_testValue_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.Like(null, new Regex(@"[\d]+")));
Assert.Count(1, failures);
}
[Test, ExpectedArgumentNullException]
public void Like_test_for_ArgumentNullException_when_regex_is_null()
{
const Regex re = null;
Assert.Like("mbTest", re);
}
[Test, ExpectedArgumentNullException]
public void Like_test_for_ArgumentNullException_when_pattern_is_null()
{
const string pattern = null;
Assert.Like("mbTest", pattern);
}
[Test]
public void Like_fails_when_testValue_does_not_match_regex_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.Like("mbTest", new Regex(@"[\d]+")));
Assert.Count(1, failures);
Assert.AreEqual("Expected a string to contain a full or partial match of a regular expression pattern.", failures[0].Description);
Assert.AreEqual("Actual Value", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Regex Pattern", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"[\\\\d]+\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test]
public void Like_fail_test_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.Like("mbTest", new Regex(@"[\w]{7}"), "{0} message {1}", "MB1", "Mb2"));
Assert.Count(1, failures);
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
#endregion
#region NotLike
[Test]
public void NotLike_sucessful_tests_with_Regex()
{
Assert.NotLike("mbTest", new Regex(@"[\d]+"));
}
[Test]
public void NotLike_sucessful_with_pattern()
{
Assert.NotLike("mbTest", @"[\d]{2}");
}
[Test]
public void NotLike_fails_when_testValue_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.NotLike(null, new Regex(@"[\w]+")));
Assert.Count(1, failures);
}
[Test, ExpectedArgumentNullException]
public void NotLike_test_for_ArgumentNullException_when_regex_is_null()
{
const Regex re = null;
Assert.NotLike("mbTest", re);
}
[Test, ExpectedArgumentNullException]
public void NotLike_test_for_ArgumentNullException_when_pattern_is_null()
{
const string pattern = null;
Assert.NotLike("mbTest", pattern);
}
[Test]
public void NotLike_fails_when_testValue_does_not_match_regex_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.NotLike("mbTest", new Regex(@"[\w]+")));
Assert.Count(1, failures);
Assert.AreEqual("Expected a string to not contain a full or partial match of a regular expression pattern.", failures[0].Description);
Assert.AreEqual("Actual Value", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Regex Pattern", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"[\\\\w]+\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test]
public void NotLike_fail_test_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.NotLike("mbTest", new Regex(@"[\w]{6}"), "{0} message {1}", "MB1", "Mb2"));
Assert.Count(1, failures);
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
#endregion
#region StartsWith
[Test]
public void StartsWith_sucessful_tests()
{
Assert.StartsWith("mbTest", "mbT");
}
[Test]
public void StartsWith_fails_when_testValue_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.StartsWith(null, ""));
Assert.Count(1, failures);
}
[Test, ExpectedArgumentNullException]
public void StartsWith_test_for_ArgumentNullException_when_pattern_is_null()
{
Assert.StartsWith("mbTest", null);
}
[Test]
public void StartsWith_fails_when_testValue_does_not_start_with_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.StartsWith("mbTest", "jb"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to start with the specified text.", failures[0].Description);
Assert.AreEqual("Actual Value", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Expected Text", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"jb\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test]
public void StartsWith_fail_test_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.StartsWith("mbTest", "jb", "{0} message {1}", "MB1", "Mb2"));
Assert.Count(1, failures);
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
[Test]
public void StartsWith_with_comparison_type_sucessful_tests()
{
Assert.StartsWith("mbTest", "MBT", StringComparison.OrdinalIgnoreCase);
}
[Test]
public void StartsWith_with_comparison_type_fails_when_testValue_does_not_start_with_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.StartsWith("mbTest", "jb", StringComparison.OrdinalIgnoreCase));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to start with the specified text.", failures[0].Description);
Assert.AreEqual("Comparison Type", failures[0].LabeledValues[0].Label);
Assert.AreEqual("{OrdinalIgnoreCase}", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Actual Value", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("Expected Text", failures[0].LabeledValues[2].Label);
Assert.AreEqual("\"jb\"", failures[0].LabeledValues[2].FormattedValue.ToString());
}
#endregion
#region EndsWith
[Test]
public void EndsWith_sucessful_tests()
{
Assert.EndsWith("mbTest", "est");
}
[Test]
public void EndsWith_fails_when_testValue_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.EndsWith(null, ""));
Assert.Count(1, failures);
}
[Test, ExpectedArgumentNullException]
public void EndsWith_test_for_ArgumentNullException_when_pattern_is_null()
{
Assert.EndsWith("mbTest", null);
}
[Test]
public void EndsWith_fails_when_testValue_does_not_start_with_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.EndsWith("mbTest", "jb"));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to end with the specified text.", failures[0].Description);
Assert.AreEqual("Actual Value", failures[0].LabeledValues[0].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Expected Text", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"jb\"", failures[0].LabeledValues[1].FormattedValue.ToString());
}
[Test]
public void EndsWith_fail_test_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.EndsWith("mbTest", "jb", "{0} message {1}", "MB1", "Mb2"));
Assert.Count(1, failures);
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
[Test]
public void EndsWith_with_comparison_type_sucessful_tests()
{
Assert.EndsWith("mbTest", "EsT", StringComparison.OrdinalIgnoreCase);
}
[Test]
public void EndsWith_with_comparison_type_fails_when_testValue_is_null()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.EndsWith(null, "", StringComparison.OrdinalIgnoreCase));
Assert.Count(1, failures);
}
[Test, ExpectedArgumentNullException]
public void EndsWith_with_comparison_type_test_for_ArgumentNullException_when_pattern_is_null()
{
Assert.EndsWith("mbTest", null, StringComparison.OrdinalIgnoreCase);
}
[Test]
public void EndsWith_with_comparison_type_fails_when_testValue_does_not_start_with_pattern()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.EndsWith("mbTest", "jb", StringComparison.OrdinalIgnoreCase));
Assert.Count(1, failures);
Assert.AreEqual("Expected string to end with the specified text.", failures[0].Description);
Assert.AreEqual("Comparison Type", failures[0].LabeledValues[0].Label);
Assert.AreEqual("{OrdinalIgnoreCase}", failures[0].LabeledValues[0].FormattedValue.ToString());
Assert.AreEqual("Actual Value", failures[0].LabeledValues[1].Label);
Assert.AreEqual("\"mbTest\"", failures[0].LabeledValues[1].FormattedValue.ToString());
Assert.AreEqual("Expected Text", failures[0].LabeledValues[2].Label);
Assert.AreEqual("\"jb\"", failures[0].LabeledValues[2].FormattedValue.ToString());
}
[Test]
public void EndsWith_with_comparison_type_fail_test_with_custom_message()
{
AssertionFailure[] failures = AssertTest.Capture(() => Assert.EndsWith("mbTest", "jb", StringComparison.OrdinalIgnoreCase, "{0} message {1}", "MB1", "Mb2"));
Assert.Count(1, failures);
Assert.AreEqual("MB1 message Mb2", failures[0].Message);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype01.gettype01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype01.gettype01;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
dynamic v3 = (iVariance<Animal>)v1;
if (typeof(Variance<Tiger>).ToString() != v2.GetType().ToString())
return 1;
if (typeof(Variance<Tiger>).ToString() != v3.GetType().ToString())
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype02.gettype02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype02.gettype02;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Animal>();
iVariance<Tiger> v2 = v1;
dynamic v3 = (iVariance<Tiger>)v1;
if (typeof(Variance<Animal>).ToString() != v2.GetType().ToString())
return 1;
if (typeof(Variance<Animal>).ToString() != v3.GetType().ToString())
return 1;
return 0;
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype03.gettype03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype03.gettype03;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
dynamic f3 = (Foo<Tiger>)f1;
if (typeof(Foo<Animal>).ToString() != f2.GetType().ToString())
return 1;
if (typeof(Foo<Animal>).ToString() != f3.GetType().ToString())
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype04.gettype04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.gettype04.gettype04;
// <Area>variance</Area>
// <Title> Expression based tests</Title>
// <Description> getType tests</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Tiger>)(() =>
{
return new Tiger();
}
);
Foo<Animal> f2 = f1;
dynamic f3 = (Foo<Animal>)f1;
if (typeof(Foo<Tiger>).ToString() != f2.GetType().ToString())
return 1;
if (typeof(Foo<Tiger>).ToString() != f3.GetType().ToString())
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is01.is01
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is01.is01;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
dynamic v3 = (iVariance<Animal>)v1;
if (!(v2 is iVariance<Animal>))
return 1;
if (!(v3 is iVariance<Animal>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is02.is02
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is02.is02;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Variance<Tiger> v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
dynamic v3 = (iVariance<Animal>)v1;
if (!(v2 is iVariance<Animal>))
return 1;
if (!(v3 is iVariance<Animal>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is03.is03
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is03.is03;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
dynamic f3 = (Foo<Tiger>)f1;
if (!(f2 is Foo<Tiger>))
return 1;
if (!(f3 is Foo<Tiger>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is04.is04
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is04.is04;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
private delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Foo<Animal> f1 = (Animal a) =>
{
}
;
Foo<Tiger> f2 = f1;
dynamic f3 = (Foo<Tiger>)f1;
if (!(f2 is Foo<Animal>))
return 1;
if (!(f3 is Foo<Animal>))
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is05.is05
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is05.is05;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
if (v1 is iVariance<Animal>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is06.is06
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is06.is06;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a covariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
iVariance<Animal> v2 = v1;
if (v1 is iVariance<Tiger>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is07.is07
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is07.is07;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
if (f1 is Foo<Tiger>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is08.is08
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is08.is08;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f2 = f1;
if (f1 is Foo<Animal>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is09.is09
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is09.is09;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a invariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
if (v1 is iVariance<Animal>)
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is10.is10
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is10.is10;
// <Area>variance</Area>
// <Title> expressions - Is Keyword</Title>
// <Description> using the is keyword on a invariant public interface </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v1 = new Variance<Tiger>();
if (v1 is iVariance<Tiger>)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is11.is11
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is11.is11;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with contravariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
private delegate void Foo<T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
if (f1 is Foo<Tiger>)
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is12.is12
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.expr.is12.is12;
// <Area>variance</Area>
// <Title> expressions - is keyword</Title>
// <Description> is keyword with invariant delegates</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
private delegate void Foo<T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f1 = (Foo<Animal>)((Animal a) =>
{
}
);
if (f1 is Foo<Animal>)
return 0;
else
return 1;
}
}
//</Code>
}
| |
/*
* 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.Drawing;
using System.IO;
using System.Net;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenMetaverse.StructuredData;
using Nwc.XmlRpc;
using log4net;
using OpenSim.Services.Connectors.Simulation;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class GatekeeperServiceConnector : SimulationServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static UUID m_HGMapImage = new UUID("00000000-0000-1111-9999-000000000013");
private IAssetService m_AssetService;
public GatekeeperServiceConnector()
: base()
{
}
public GatekeeperServiceConnector(IAssetService assService)
{
m_AssetService = assService;
}
protected override string AgentPath()
{
return "foreignagent/";
}
protected override string ObjectPath()
{
return "foreignobject/";
}
public bool LinkRegion(GridRegion info, out UUID regionID, out ulong realHandle, out string externalName, out string imageURL, out string reason, out int sizeX, out int sizeY)
{
regionID = UUID.Zero;
imageURL = string.Empty;
realHandle = 0;
externalName = string.Empty;
reason = string.Empty;
sizeX = (int)Constants.RegionSize;
sizeY = (int)Constants.RegionSize;
Hashtable hash = new Hashtable();
hash["region_name"] = info.RegionName;
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("link_region", paramList);
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Linking to " + info.ServerURI);
XmlRpcResponse response = null;
try
{
response = request.Send(info.ServerURI, 10000);
}
catch (Exception e)
{
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
reason = "Error contacting remote server";
return false;
}
if (response.IsFault)
{
reason = response.FaultString;
m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
return false;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (success)
{
UUID.TryParse((string)hash["uuid"], out regionID);
//m_log.Debug(">> HERE, uuid: " + regionID);
if ((string)hash["handle"] != null)
{
realHandle = Convert.ToUInt64((string)hash["handle"]);
//m_log.Debug(">> HERE, realHandle: " + realHandle);
}
if (hash["region_image"] != null)
{
imageURL = (string)hash["region_image"];
//m_log.Debug(">> HERE, imageURL: " + imageURL);
}
if (hash["external_name"] != null)
{
externalName = (string)hash["external_name"];
//m_log.Debug(">> HERE, externalName: " + externalName);
}
if (hash["size_x"] != null)
{
Int32.TryParse((string)hash["size_x"], out sizeX);
}
if (hash["size_y"] != null)
{
Int32.TryParse((string)hash["size_y"], out sizeY);
}
}
}
catch (Exception e)
{
reason = "Error parsing return arguments";
m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
return false;
}
return true;
}
public UUID GetMapImage(UUID regionID, string imageURL, string storagePath)
{
if (m_AssetService == null)
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: No AssetService defined. Map tile not retrieved.");
return m_HGMapImage;
}
UUID mapTile = m_HGMapImage;
string filename = string.Empty;
try
{
//m_log.Debug("JPEG: " + imageURL);
string name = regionID.ToString();
filename = Path.Combine(storagePath, name + ".jpg");
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: Map image at {0}, cached at {1}", imageURL, filename);
if (!File.Exists(filename))
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: downloading...");
using(WebClient c = new WebClient())
c.DownloadFile(imageURL, filename);
}
else
{
m_log.DebugFormat("[GATEKEEPER SERVICE CONNECTOR]: using cached image");
}
byte[] imageData = null;
using (Bitmap bitmap = new Bitmap(filename))
{
//m_log.Debug("Size: " + m.PhysicalDimension.Height + "-" + m.PhysicalDimension.Width);
imageData = OpenJPEG.EncodeFromImage(bitmap, true);
}
AssetBase ass = new AssetBase(UUID.Random(), "region " + name, (sbyte)AssetType.Texture, regionID.ToString());
// !!! for now
//info.RegionSettings.TerrainImageID = ass.FullID;
ass.Data = imageData;
m_AssetService.Store(ass);
// finally
mapTile = ass.FullID;
}
catch // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Info("[GATEKEEPER SERVICE CONNECTOR]: Failed getting/storing map image, because it is probably already in the cache");
}
return mapTile;
}
public GridRegion GetHyperlinkRegion(GridRegion gatekeeper, UUID regionID, UUID agentID, string agentHomeURI, out string message)
{
Hashtable hash = new Hashtable();
hash["region_uuid"] = regionID.ToString();
if (agentID != UUID.Zero)
{
hash["agent_id"] = agentID.ToString();
if (agentHomeURI != null)
hash["agent_home_uri"] = agentHomeURI;
}
IList paramList = new ArrayList();
paramList.Add(hash);
XmlRpcRequest request = new XmlRpcRequest("get_region", paramList);
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: contacting " + gatekeeper.ServerURI);
XmlRpcResponse response = null;
try
{
response = request.Send(gatekeeper.ServerURI, 10000);
}
catch (Exception e)
{
message = "Error contacting grid.";
m_log.Debug("[GATEKEEPER SERVICE CONNECTOR]: Exception " + e.Message);
return null;
}
if (response.IsFault)
{
message = "Error contacting grid.";
m_log.ErrorFormat("[GATEKEEPER SERVICE CONNECTOR]: remote call returned an error: {0}", response.FaultString);
return null;
}
hash = (Hashtable)response.Value;
//foreach (Object o in hash)
// m_log.Debug(">> " + ((DictionaryEntry)o).Key + ":" + ((DictionaryEntry)o).Value);
try
{
bool success = false;
Boolean.TryParse((string)hash["result"], out success);
if (hash["message"] != null)
message = (string)hash["message"];
else if (success)
message = null;
else
message = "The teleport destination could not be found."; // probably the dest grid is old and doesn't send 'message', but the most common problem is that the region is unavailable
if (success)
{
GridRegion region = new GridRegion();
UUID.TryParse((string)hash["uuid"], out region.RegionID);
//m_log.Debug(">> HERE, uuid: " + region.RegionID);
int n = 0;
if (hash["x"] != null)
{
Int32.TryParse((string)hash["x"], out n);
region.RegionLocX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["y"] != null)
{
Int32.TryParse((string)hash["y"], out n);
region.RegionLocY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["size_x"] != null)
{
Int32.TryParse((string)hash["size_x"], out n);
region.RegionSizeX = n;
//m_log.Debug(">> HERE, x: " + region.RegionLocX);
}
if (hash["size_y"] != null)
{
Int32.TryParse((string)hash["size_y"], out n);
region.RegionSizeY = n;
//m_log.Debug(">> HERE, y: " + region.RegionLocY);
}
if (hash["region_name"] != null)
{
region.RegionName = (string)hash["region_name"];
//m_log.Debug(">> HERE, region_name: " + region.RegionName);
}
if (hash["hostname"] != null)
{
region.ExternalHostName = (string)hash["hostname"];
//m_log.Debug(">> HERE, hostname: " + region.ExternalHostName);
}
if (hash["http_port"] != null)
{
uint p = 0;
UInt32.TryParse((string)hash["http_port"], out p);
region.HttpPort = p;
//m_log.Debug(">> HERE, http_port: " + region.HttpPort);
}
if (hash["internal_port"] != null)
{
int p = 0;
Int32.TryParse((string)hash["internal_port"], out p);
region.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), p);
//m_log.Debug(">> HERE, internal_port: " + region.InternalEndPoint);
}
if (hash["server_uri"] != null)
{
region.ServerURI = (string)hash["server_uri"];
//m_log.Debug(">> HERE, server_uri: " + region.ServerURI);
}
// Successful return
return region;
}
}
catch (Exception e)
{
message = "Error parsing response from grid.";
m_log.Error("[GATEKEEPER SERVICE CONNECTOR]: Got exception while parsing hyperlink response " + e.StackTrace);
return null;
}
return null;
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************************/
// #define SHOW_DK2_VARIABLES
// Use the Unity new GUI with Unity 4.6 or above.
#if UNITY_4_6 || UNITY_5_0
#define USE_NEW_GUI
#endif
using System;
using System.Collections;
using UnityEngine;
#if USE_NEW_GUI
using UnityEngine.UI;
# endif
//-------------------------------------------------------------------------------------
// ***** OVRMainMenu
//
/// <summary>
/// OVRMainMenu is used to control the loading of different scenes. It also renders out
/// a menu that allows a user to modify various Rift settings, and allow for storing
/// these settings for recall later.
///
/// A user of this component can add as many scenes that they would like to be able to
/// have access to.
///
/// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience,
/// but can safely removed from it and added to another GameObject that is used for general
/// Unity logic.
///
/// </summary>
public class OVRMainMenu : MonoBehaviour
{
/// <summary>
/// The amount of time in seconds that it takes for the menu to fade in.
/// </summary>
public float FadeInTime = 2.0f;
/// <summary>
/// An optional texture that appears before the menu fades in.
/// </summary>
public UnityEngine.Texture FadeInTexture = null;
/// <summary>
/// An optional font that replaces Unity's default Arial.
/// </summary>
public Font FontReplace = null;
/// <summary>
/// The key that toggles the menu.
/// </summary>
public KeyCode MenuKey = KeyCode.Space;
/// <summary>
/// The key that quits the application.
/// </summary>
public KeyCode QuitKey = KeyCode.Escape;
/// <summary>
/// Scene names to show on-screen for each of the scenes in Scenes.
/// </summary>
public string [] SceneNames;
/// <summary>
/// The set of scenes that the user can jump to.
/// </summary>
public string [] Scenes;
private bool ScenesVisible = false;
// Spacing for scenes menu
private int StartX = 490;
private int StartY = 250;
private int WidthX = 300;
private int WidthY = 23;
// Spacing for variables that users can change
private int VRVarsSX = 553;
private int VRVarsSY = 250;
private int VRVarsWidthX = 175;
private int VRVarsWidthY = 23;
private int StepY = 25;
// Handle to OVRCameraRig
private OVRCameraRig CameraController = null;
// Handle to OVRPlayerController
private OVRPlayerController PlayerController = null;
// Controller buttons
private bool PrevStartDown;
private bool PrevHatDown;
private bool PrevHatUp;
private bool ShowVRVars;
private bool OldSpaceHit;
// FPS
private float UpdateInterval = 0.5f;
private float Accum = 0;
private int Frames = 0;
private float TimeLeft = 0;
private string strFPS = "FPS: 0";
private string strIPD = "IPD: 0.000";
/// <summary>
/// Prediction (in ms)
/// </summary>
public float PredictionIncrement = 0.001f; // 1 ms
private string strPrediction = "Pred: OFF";
private string strFOV = "FOV: 0.0f";
private string strHeight = "Height: 0.0f";
/// <summary>
/// Controls how quickly the player's speed and rotation change based on input.
/// </summary>
public float SpeedRotationIncrement = 0.05f;
private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f";
private bool LoadingLevel = false;
private float AlphaFadeValue = 1.0f;
private int CurrentLevel = 0;
// Rift detection
private bool HMDPresent = false;
private float RiftPresentTimeout = 0.0f;
private string strRiftPresent = "";
// Replace the GUI with our own texture and 3D plane that
// is attached to the rendder camera for true 3D placement
private OVRGUI GuiHelper = new OVRGUI();
private GameObject GUIRenderObject = null;
private RenderTexture GUIRenderTexture = null;
// We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI
// Enable the UsingNewGUI option in the editor,
// if you want to use new GUI and Unity version is higher than 4.6
#if USE_NEW_GUI
private GameObject NewGUIObject = null;
private GameObject RiftPresentGUIObject = null;
#endif
/// <summary>
/// We can set the layer to be anything we want to, this allows
/// a specific camera to render it.
/// </summary>
public string LayerName = "Default";
/// <summary>
/// Crosshair rendered onto 3D plane.
/// </summary>
public UnityEngine.Texture CrosshairImage = null;
private OVRCrosshair Crosshair = new OVRCrosshair();
// Resolution Eye Texture
private string strResolutionEyeTexture = "Resolution: 0 x 0";
// Latency values
private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f";
// Vision mode on/off
private bool VisionMode = true;
#if SHOW_DK2_VARIABLES
private string strVisionMode = "Vision Enabled: ON";
#endif
// We want to hold onto GridCube, for potential sharing
// of the menu RenderTarget
OVRGridCube GridCube = null;
// We want to hold onto the VisionGuide so we can share
// the menu RenderTarget
OVRVisionGuide VisionGuide = null;
#region MonoBehaviour Message Handlers
/// <summary>
/// Awake this instance.
/// </summary>
void Awake()
{
// Find camera controller
OVRCameraRig[] CameraControllers;
CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>();
if(CameraControllers.Length == 0)
Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached.");
else if (CameraControllers.Length > 1)
Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached.");
else{
CameraController = CameraControllers[0];
#if USE_NEW_GUI
OVRUGUI.CameraController = CameraController;
#endif
}
// Find player controller
OVRPlayerController[] PlayerControllers;
PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>();
if(PlayerControllers.Length == 0)
Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached.");
else if (PlayerControllers.Length > 1)
Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached.");
else{
PlayerController = PlayerControllers[0];
#if USE_NEW_GUI
OVRUGUI.PlayerController = PlayerController;
#endif
}
#if USE_NEW_GUI
// Create canvas for using new GUI
NewGUIObject = new GameObject();
NewGUIObject.name = "OVRGUIMain";
NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform;
RectTransform r = NewGUIObject.AddComponent<RectTransform>();
r.sizeDelta = new Vector2(100f, 100f);
r.localScale = new Vector3(0.001f, 0.001f, 0.001f);
r.localPosition = new Vector3(0.01f, 0.17f, 0.53f);
r.localEulerAngles = Vector3.zero;
Canvas c = NewGUIObject.AddComponent<Canvas>();
c.renderMode = RenderMode.WorldSpace;
c.pixelPerfect = false;
#endif
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
AlphaFadeValue = 1.0f;
CurrentLevel = 0;
PrevStartDown = false;
PrevHatDown = false;
PrevHatUp = false;
ShowVRVars = false;
OldSpaceHit = false;
strFPS = "FPS: 0";
LoadingLevel = false;
ScenesVisible = false;
// Set the GUI target
GUIRenderObject = GameObject.Instantiate(Resources.Load("OVRGUIObjectMain")) as GameObject;
if(GUIRenderObject != null)
{
// Chnge the layer
GUIRenderObject.layer = LayerMask.NameToLayer(LayerName);
if(GUIRenderTexture == null)
{
int w = Screen.width;
int h = Screen.height;
// We don't need a depth buffer on this texture
GUIRenderTexture = new RenderTexture(w, h, 0);
GuiHelper.SetPixelResolution(w, h);
// NOTE: All GUI elements are being written with pixel values based
// from DK1 (1280x800). These should change to normalized locations so
// that we can scale more cleanly with varying resolutions
GuiHelper.SetDisplayResolution(1280.0f, 800.0f);
}
}
// Attach GUI texture to GUI object and GUI object to Camera
if(GUIRenderTexture != null && GUIRenderObject != null)
{
GUIRenderObject.GetComponent<Renderer>().material.mainTexture = GUIRenderTexture;
if(CameraController != null)
{
// Grab transform of GUI object
Vector3 ls = GUIRenderObject.transform.localScale;
Vector3 lp = GUIRenderObject.transform.localPosition;
Quaternion lr = GUIRenderObject.transform.localRotation;
// Attach the GUI object to the camera
GUIRenderObject.transform.parent = CameraController.centerEyeAnchor;
// Reset the transform values (we will be maintaining state of the GUI object
// in local state)
GUIRenderObject.transform.localScale = ls;
GUIRenderObject.transform.localPosition = lp;
GUIRenderObject.transform.localRotation = lr;
// Deactivate object until we have completed the fade-in
// Also, we may want to deactive the render object if there is nothing being rendered
// into the UI
GUIRenderObject.SetActive(false);
}
}
// Make sure to hide cursor
if(Application.isEditor == false)
{
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
// CameraController updates
if(CameraController != null)
{
// Add a GridCube component to this object
GridCube = gameObject.AddComponent<OVRGridCube>();
GridCube.SetOVRCameraController(ref CameraController);
// Add a VisionGuide component to this object
VisionGuide = gameObject.AddComponent<OVRVisionGuide>();
VisionGuide.SetOVRCameraController(ref CameraController);
VisionGuide.SetFadeTexture(ref FadeInTexture);
VisionGuide.SetVisionGuideLayer(ref LayerName);
}
// Crosshair functionality
Crosshair.Init();
Crosshair.SetCrosshairTexture(ref CrosshairImage);
Crosshair.SetOVRCameraController (ref CameraController);
Crosshair.SetOVRPlayerController(ref PlayerController);
// Check for HMD and sensor
CheckIfRiftPresent();
#if USE_NEW_GUI
if (!string.IsNullOrEmpty(strRiftPresent)){
ShowRiftPresentGUI();
}
#endif
}
/// <summary>
/// Update this instance.
/// </summary>
void Update()
{
if(LoadingLevel == true)
return;
// Main update
UpdateFPS();
// CameraController updates
if(CameraController != null)
{
UpdateIPD();
UpdateRecenterPose();
UpdateVisionMode();
UpdateFOV();
UpdateEyeHeightOffset();
UpdateResolutionEyeTexture();
UpdateLatencyValues();
}
// PlayerController updates
if(PlayerController != null)
{
UpdateSpeedAndRotationScaleMultiplier();
UpdatePlayerControllerMovement();
}
// MainMenu updates
UpdateSelectCurrentLevel();
// Device updates
UpdateDeviceDetection();
// Crosshair functionality
Crosshair.UpdateCrosshair();
#if USE_NEW_GUI
if (ShowVRVars && RiftPresentTimeout <= 0.0f)
{
NewGUIObject.SetActive(true);
UpdateNewGUIVars();
OVRUGUI.UpdateGUI();
}
else
{
NewGUIObject.SetActive(false);
}
#endif
// Toggle Fullscreen
if(Input.GetKeyDown(KeyCode.F11))
Screen.fullScreen = !Screen.fullScreen;
if (Input.GetKeyDown(KeyCode.M))
OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode;
// Escape Application
if (Input.GetKeyDown(QuitKey))
Application.Quit();
}
/// <summary>
/// Updates Variables for new GUI.
/// </summary>
#if USE_NEW_GUI
void UpdateNewGUIVars()
{
#if SHOW_DK2_VARIABLES
// Print out Vision Mode
OVRUGUI.strVisionMode = strVisionMode;
#endif
// Print out FPS
OVRUGUI.strFPS = strFPS;
// Don't draw these vars if CameraController is not present
if (CameraController != null)
{
OVRUGUI.strPrediction = strPrediction;
OVRUGUI.strIPD = strIPD;
OVRUGUI.strFOV = strFOV;
OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture;
OVRUGUI.strLatencies = strLatencies;
}
// Don't draw these vars if PlayerController is not present
if (PlayerController != null)
{
OVRUGUI.strHeight = strHeight;
OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler;
}
OVRUGUI.strRiftPresent = strRiftPresent;
}
#endif
void OnGUI()
{
// Important to keep from skipping render events
if (Event.current.type != EventType.Repaint)
return;
#if !USE_NEW_GUI
// Fade in screen
if(AlphaFadeValue > 0.0f)
{
AlphaFadeValue -= Mathf.Clamp01(Time.deltaTime / FadeInTime);
if(AlphaFadeValue < 0.0f)
{
AlphaFadeValue = 0.0f;
}
else
{
GUI.color = new Color(0, 0, 0, AlphaFadeValue);
GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture );
return;
}
}
#endif
// We can turn on the render object so we can render the on-screen menu
if(GUIRenderObject != null)
{
if (ScenesVisible ||
ShowVRVars ||
Crosshair.IsCrosshairVisible() ||
RiftPresentTimeout > 0.0f ||
VisionGuide.GetFadeAlphaValue() > 0.0f)
{
GUIRenderObject.SetActive(true);
}
else
{
GUIRenderObject.SetActive(false);
}
}
//***
// Set the GUI matrix to deal with portrait mode
Vector3 scale = Vector3.one;
Matrix4x4 svMat = GUI.matrix; // save current matrix
// substitute matrix - only scale is altered from standard
GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
// Cache current active render texture
RenderTexture previousActive = RenderTexture.active;
// if set, we will render to this texture
if(GUIRenderTexture != null && GUIRenderObject.activeSelf)
{
RenderTexture.active = GUIRenderTexture;
GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f));
}
// Update OVRGUI functions (will be deprecated eventually when 2D renderingc
// is removed from GUI)
GuiHelper.SetFontReplace(FontReplace);
// If true, we are displaying information about the Rift not being detected
// So do not show anything else
if(GUIShowRiftDetected() != true)
{
GUIShowLevels();
GUIShowVRVariables();
}
// The cross-hair may need to go away at some point, unless someone finds it
// useful
Crosshair.OnGUICrosshair();
// Since we want to draw into the main GUI that is shared within the MainMenu,
// we call the OVRVisionGuide GUI function here
VisionGuide.OnGUIVisionGuide();
// Restore active render texture
if (GUIRenderObject.activeSelf)
{
RenderTexture.active = previousActive;
}
// ***
// Restore previous GUI matrix
GUI.matrix = svMat;
}
#endregion
#region Internal State Management Functions
/// <summary>
/// Updates the FPS.
/// </summary>
void UpdateFPS()
{
TimeLeft -= Time.deltaTime;
Accum += Time.timeScale/Time.deltaTime;
++Frames;
// Interval ended - update GUI text and start new interval
if( TimeLeft <= 0.0 )
{
// display two fractional digits (f2 format)
float fps = Accum / Frames;
if(ShowVRVars == true)// limit gc
strFPS = System.String.Format("FPS: {0:F2}",fps);
TimeLeft += UpdateInterval;
Accum = 0.0f;
Frames = 0;
}
}
/// <summary>
/// Updates the IPD.
/// </summary>
void UpdateIPD()
{
if(ShowVRVars == true) // limit gc
{
strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f);
}
}
void UpdateRecenterPose()
{
if(Input.GetKeyDown(KeyCode.R))
{
OVRManager.display.RecenterPose();
}
}
/// <summary>
/// Updates the vision mode.
/// </summary>
void UpdateVisionMode()
{
if (Input.GetKeyDown(KeyCode.F2))
{
VisionMode = !VisionMode;
OVRManager.tracker.isEnabled = VisionMode;
#if SHOW_DK2_VARIABLES
strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF";
#endif
}
}
/// <summary>
/// Updates the FOV.
/// </summary>
void UpdateFOV()
{
if(ShowVRVars == true)// limit gc
{
OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left);
strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y);
}
}
/// <summary>
/// Updates resolution of eye texture
/// </summary>
void UpdateResolutionEyeTexture()
{
if (ShowVRVars == true) // limit gc
{
OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left);
OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Right);
float scale = OVRManager.instance.nativeTextureScale * OVRManager.instance.virtualTextureScale;
float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x));
float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y));
strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h);
}
}
/// <summary>
/// Updates latency values
/// </summary>
void UpdateLatencyValues()
{
#if !UNITY_ANDROID || UNITY_EDITOR
if (ShowVRVars == true) // limit gc
{
OVRDisplay.LatencyData latency = OVRManager.display.latency;
if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f)
strLatencies = System.String.Format("Ren : N/A TWrp: N/A PostPresent: N/A");
else
strLatencies = System.String.Format("Ren : {0:F3} TWrp: {1:F3} PostPresent: {2:F3}",
latency.render,
latency.timeWarp,
latency.postPresent);
}
#endif
}
/// <summary>
/// Updates the eye height offset.
/// </summary>
void UpdateEyeHeightOffset()
{
if(ShowVRVars == true)// limit gc
{
float eyeHeight = OVRManager.profile.eyeHeight;
strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight);
}
}
/// <summary>
/// Updates the speed and rotation scale multiplier.
/// </summary>
void UpdateSpeedAndRotationScaleMultiplier()
{
float moveScaleMultiplier = 0.0f;
PlayerController.GetMoveScaleMultiplier(ref moveScaleMultiplier);
if(Input.GetKeyDown(KeyCode.Alpha7))
moveScaleMultiplier -= SpeedRotationIncrement;
else if (Input.GetKeyDown(KeyCode.Alpha8))
moveScaleMultiplier += SpeedRotationIncrement;
PlayerController.SetMoveScaleMultiplier(moveScaleMultiplier);
float rotationScaleMultiplier = 0.0f;
PlayerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier);
if(Input.GetKeyDown(KeyCode.Alpha9))
rotationScaleMultiplier -= SpeedRotationIncrement;
else if (Input.GetKeyDown(KeyCode.Alpha0))
rotationScaleMultiplier += SpeedRotationIncrement;
PlayerController.SetRotationScaleMultiplier(rotationScaleMultiplier);
if(ShowVRVars == true)// limit gc
strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}",
moveScaleMultiplier,
rotationScaleMultiplier);
}
/// <summary>
/// Updates the player controller movement.
/// </summary>
void UpdatePlayerControllerMovement()
{
if(PlayerController != null)
PlayerController.SetHaltUpdateMovement(ScenesVisible);
}
/// <summary>
/// Updates the select current level.
/// </summary>
void UpdateSelectCurrentLevel()
{
ShowLevels();
if (!ScenesVisible)
return;
CurrentLevel = GetCurrentLevel();
if (Scenes.Length != 0
&& (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.A)
|| Input.GetKeyDown(KeyCode.Return)))
{
LoadingLevel = true;
Application.LoadLevelAsync(Scenes[CurrentLevel]);
}
}
/// <summary>
/// Shows the levels.
/// </summary>
/// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns>
bool ShowLevels()
{
if (Scenes.Length == 0)
{
ScenesVisible = false;
return ScenesVisible;
}
bool curStartDown = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Start);
bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown(KeyCode.RightShift);
PrevStartDown = curStartDown;
if (startPressed)
{
ScenesVisible = !ScenesVisible;
}
return ScenesVisible;
}
/// <summary>
/// Gets the current level.
/// </summary>
/// <returns>The current level.</returns>
int GetCurrentLevel()
{
bool curHatDown = false;
if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true)
curHatDown = true;
bool curHatUp = false;
if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true)
curHatUp = true;
if((PrevHatDown == false) && (curHatDown == true) ||
Input.GetKeyDown(KeyCode.DownArrow))
{
CurrentLevel = (CurrentLevel + 1) % SceneNames.Length;
}
else if((PrevHatUp == false) && (curHatUp == true) ||
Input.GetKeyDown(KeyCode.UpArrow))
{
CurrentLevel--;
if(CurrentLevel < 0)
CurrentLevel = SceneNames.Length - 1;
}
PrevHatDown = curHatDown;
PrevHatUp = curHatUp;
return CurrentLevel;
}
#endregion
#region Internal GUI Functions
/// <summary>
/// Show the GUI levels.
/// </summary>
void GUIShowLevels()
{
if(ScenesVisible == true)
{
// Darken the background by rendering fade texture
GUI.color = new Color(0, 0, 0, 0.5f);
GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture );
GUI.color = Color.white;
if(LoadingLevel == true)
{
string loading = "LOADING...";
GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow);
return;
}
for (int i = 0; i < SceneNames.Length; i++)
{
Color c;
if(i == CurrentLevel)
c = Color.yellow;
else
c = Color.black;
int y = StartY + (i * StepY);
GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames[i], c);
}
}
}
/// <summary>
/// Show the VR variables.
/// </summary>
void GUIShowVRVariables()
{
bool SpaceHit = Input.GetKey(MenuKey);
if ((OldSpaceHit == false) && (SpaceHit == true))
{
if (ShowVRVars == true)
{
ShowVRVars = false;
}
else
{
ShowVRVars = true;
#if USE_NEW_GUI
OVRUGUI.InitUIComponent = ShowVRVars;
#endif
}
}
OldSpaceHit = SpaceHit;
// Do not render if we are not showing
if (ShowVRVars == false)
return;
#if !USE_NEW_GUI
int y = VRVarsSY;
#if SHOW_DK2_VARIABLES
// Print out Vision Mode
GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strVisionMode, Color.green);
#endif
// Draw FPS
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strFPS, Color.green);
// Don't draw these vars if CameraController is not present
if (CameraController != null)
{
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strPrediction, Color.white);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strIPD, Color.yellow);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strFOV, Color.white);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strResolutionEyeTexture, Color.white);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strLatencies, Color.white);
}
// Don't draw these vars if PlayerController is not present
if (PlayerController != null)
{
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strHeight, Color.yellow);
GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY,
ref strSpeedRotationMultipler, Color.white);
}
#endif
}
// RIFT DETECTION
/// <summary>
/// Checks to see if HMD and / or sensor is available, and displays a
/// message if it is not.
/// </summary>
void CheckIfRiftPresent()
{
HMDPresent = OVRManager.display.isPresent;
if (!HMDPresent)
{
RiftPresentTimeout = 15.0f;
if (!HMDPresent)
strRiftPresent = "NO HMD DETECTED";
#if USE_NEW_GUI
OVRUGUI.strRiftPresent = strRiftPresent;
#endif
}
}
/// <summary>
/// Show if Rift is detected.
/// </summary>
/// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns>
bool GUIShowRiftDetected()
{
#if !USE_NEW_GUI
if(RiftPresentTimeout > 0.0f)
{
GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY,
ref strRiftPresent, Color.white);
return true;
}
#else
if(RiftPresentTimeout < 0.0f)
DestroyImmediate(RiftPresentGUIObject);
#endif
return false;
}
/// <summary>
/// Updates the device detection.
/// </summary>
void UpdateDeviceDetection()
{
if(RiftPresentTimeout > 0.0f)
RiftPresentTimeout -= Time.deltaTime;
}
/// <summary>
/// Show rift present GUI with new GUI
/// </summary>
void ShowRiftPresentGUI()
{
#if USE_NEW_GUI
RiftPresentGUIObject = new GameObject();
RiftPresentGUIObject.name = "RiftPresentGUIMain";
RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform;
RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>();
r.sizeDelta = new Vector2(100f, 100f);
r.localPosition = new Vector3(0.01f, 0.17f, 0.53f);
r.localEulerAngles = Vector3.zero;
r.localScale = new Vector3(0.001f, 0.001f, 0.001f);
Canvas c = RiftPresentGUIObject.AddComponent<Canvas>();
c.renderMode = RenderMode.WorldSpace;
c.pixelPerfect = false;
OVRUGUI.RiftPresentGUI(RiftPresentGUIObject);
#endif
}
#endregion
}
| |
using System;
using System.Text;
using Xunit;
using Medo.Security.Checksum;
namespace Tests.Medo.Security.Checksum {
public class Crc8Tests {
[Fact(DisplayName = "Crc8: Default")]
public void Default() {
string expected = "0xDF";
var crc = new Crc8();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: AUTOSAR")]
public void Autosar() {
string expected = "0x2F";
var crc = Crc8.GetAutosar();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: AUTOSAR (2)")]
public void Autosar_2() {
var crc = Crc8.GetAutosar();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xDF, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: BLUETOOTH")]
public void Bluetooth() {
string expected = "0x8F";
var crc = Crc8.GetBluetooth();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: BLUETOOTH (2)")]
public void Bluetooth_2() {
var crc = Crc8.GetBluetooth();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x26, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: CDMA2000")]
public void Cdma2000() {
string expected = "0xCE";
var crc = Crc8.GetCdma2000();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: CDMA2000 (2)")]
public void Cdma2000_2() {
var crc = Crc8.GetCdma2000();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xDA, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: DARC")]
public void Darc() {
string expected = "0x24";
var crc = Crc8.GetDarc();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: DARC (2)")]
public void Darc_2() {
var crc = Crc8.GetDarc();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x15, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: DVB-S2")]
public void DvbS2() {
string expected = "0x3E";
var crc = Crc8.GetDvbS2();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: DVB-S2 (2)")]
public void DvbS2_2() {
var crc = Crc8.GetDvbS2();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xBC, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: GSM-A")]
public void GsmA() {
string expected = "0xBB";
var crc = Crc8.GetGsmA();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: GSM-A (2)")]
public void GsmA_2() {
var crc = Crc8.GetGsmA();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x37, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: GSM-B")]
public void GsmB() {
string expected = "0xD6";
var crc = Crc8.GetGsmB();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: GSM-B (2)")]
public void GsmB_2() {
var crc = Crc8.GetGsmB();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x94, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: HITAG")]
public void Hitag() {
string expected = "0xEA";
var crc = Crc8.GetHitag();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: HITAG (2)")]
public void Hitag_2() {
var crc = Crc8.GetHitag();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xB4, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-432-1")]
public void I4321() {
string expected = "0x8A";
var crc = Crc8.GetI4321();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: I-432-1 (2)")]
public void I4321_2() {
var crc = Crc8.GetI4321();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA1, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-432-1 / CCITT (A)")]
public void Ccitt_A() {
var crc = Crc8.GetCcitt();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA1, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-432-1 / ITU (A)")]
public void Itu_A() {
var crc = Crc8.GetItu();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA1, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-CODE")]
public void ICode() {
string expected = "0xA4";
var crc = Crc8.GetICode();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: I-CODE (2)")]
public void ICode_2() {
var crc = Crc8.GetICode();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x7E, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-CODE (3)")]
public void ICode_3() {
var crc = Crc8.GetICode();
Assert.Equal(0xFD, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-CODE (4)")]
public void ICode_4() {
var crc = Crc8.GetICode();
crc.ComputeHash(new byte[] { 0x30 });
Assert.Equal(0xB4, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-CODE (5)")]
public void ICode_5() {
var crc = Crc8.GetICode();
crc.ComputeHash(new byte[] { 0x30, 0x00 });
Assert.Equal(0x18, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-CODE (6)")]
public void ICode_6() {
var crc = Crc8.GetICode();
crc.ComputeHash(new byte[] { 0x30, 0x00, 0x00 });
Assert.Equal(0x25, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: I-CODE (7)")]
public void ICode_7() {
var crc = Crc8.GetICode();
crc.ComputeHash(new byte[] { 0x30, 0x00, 0x00, 0x25 });
Assert.Equal(0x00, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: LTE")]
public void Lte() {
string expected = "0xDF";
var crc = Crc8.GetLte();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: LTE (2)")]
public void Lte_2() {
var crc = Crc8.GetLte();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xEA, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: MAXIM-DOW")]
public void MaximDow() {
string expected = "0x80";
var crc = Crc8.GetMaximDow();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: MAXIM-DOW (2)")]
public void MaximDow_2() {
var crc = Crc8.GetMaximDow();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA1, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: MAXIM-DOW / DALLAS (A)")]
public void Dallas_A() {
var crc = Crc8.GetDallas();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA1, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: MAXIM-DOW / MAXIM (A)")]
public void Maxim_A() {
var crc = Crc8.GetMaxim();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xA1, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: MIFARE-MAD")]
public void MifareMad() {
string expected = "0x11";
var crc = Crc8.GetMifareMad();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: MIFARE-MAD (2)")]
public void MifareMad_2() {
var crc = Crc8.GetMifareMad();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x99, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: MIFARE-MAD (3)")]
public void MifareMad_3() {
var crc = Crc8.GetMifareMad();
crc.ComputeHash(new byte[] { 0x01, 0x01, 0x08, 0x01, 0x08, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x03, 0x10, 0x03, 0x10, 0x02, 0x10, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x30 });
Assert.Equal(0x89, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: MIFARE-MAD / MIFARE (A)")]
public void Mifare_A() {
var crc = Crc8.GetMifare();
crc.ComputeHash(new byte[] { 0x01, 0x01, 0x08, 0x01, 0x08, 0x01, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x03, 0x10, 0x03, 0x10, 0x02, 0x10, 0x02, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x30 });
Assert.Equal(0x89, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: NRSC-5")]
public void Nrsc5() {
string expected = "0xE3";
var crc = Crc8.GetNrsc5();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: NRSC-5 (2)")]
public void Nrsc5_2() {
var crc = Crc8.GetNrsc5();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xF7, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: OPENSAFETY")]
public void OpenSafety() {
string expected = "0x15";
var crc = Crc8.GetOpenSafety();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: OPENSAFETY (2)")]
public void OpenSafety_2() {
var crc = Crc8.GetOpenSafety();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x3E, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: ROHC")]
public void Rohc() {
string expected = "0xA2";
var crc = Crc8.GetRohc();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: ROHC (2)")]
public void Rohc_2() {
var crc = Crc8.GetRohc();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xD0, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: SAE-J1850")]
public void SaeJ1850() {
string expected = "0x15";
var crc = Crc8.GetSaeJ1850();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: SAE-J1850 (2)")]
public void SaeJ1850_2() {
var crc = Crc8.GetSaeJ1850();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x4B, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: SMBUS")]
public void SMBus() {
string expected = "0xDF";
var crc = Crc8.GetSMBus();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: SMBUS (2)")]
public void SMBus_2() {
var crc = Crc8.GetSMBus();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0xF4, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: TECH-3250")]
public void Tech3250() {
string expected = "0x70";
var crc = Crc8.GetTech3250();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: TECH-3250 (2)")]
public void Tech3250_2() {
var crc = Crc8.GetTech3250();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x97, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: WCDMA2000")]
public void Wcdma2000() {
string expected = "0xD3";
var crc = Crc8.GetWcdma2000();
crc.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal(expected, $"0x{crc.HashAsByte:X2}");
Assert.Equal(expected, "0x" + BitConverter.ToString(crc.Hash).Replace("-", ""));
}
[Fact(DisplayName = "Crc8: WCDMA2000 (2)")]
public void Wcdma2000_2() {
var crc = Crc8.GetWcdma2000();
crc.ComputeHash(Encoding.ASCII.GetBytes("123456789"));
Assert.Equal(0x25, crc.HashAsByte);
}
[Fact(DisplayName = "Crc8: Reuse same instance")]
public void Reuse() {
var checksum = Crc8.GetDallas();
checksum.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal("80", checksum.HashAsByte.ToString("X2"));
checksum.ComputeHash(Encoding.ASCII.GetBytes("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
Assert.Equal("80", checksum.HashAsByte.ToString("X2"));
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Handlers;
namespace TheArtOfDev.HtmlRenderer.Core.Dom
{
/// <summary>
/// Represents a word inside an inline box
/// </summary>
/// <remarks>
/// Because of performance, words of text are the most atomic
/// element in the project. It should be characters, but come on,
/// imagine the performance when drawing char by char on the device.<br/>
/// It may change for future versions of the library.
/// </remarks>
internal abstract class CssRect
{
#region Fields and Consts
/// <summary>
/// the CSS box owner of the word
/// </summary>
private readonly CssBox _ownerBox;
/// <summary>
/// Rectangle
/// </summary>
private RRect _rect;
/// <summary>
/// If the word is selected this points to the selection handler for more data
/// </summary>
private SelectionHandler _selection;
#endregion
/// <summary>
/// Init.
/// </summary>
/// <param name="owner">the CSS box owner of the word</param>
protected CssRect(CssBox owner)
{
_ownerBox = owner;
}
/// <summary>
/// Gets the Box where this word belongs.
/// </summary>
public CssBox OwnerBox
{
get { return _ownerBox; }
}
/// <summary>
/// Gets or sets the bounds of the rectangle
/// </summary>
public RRect Rectangle
{
get { return _rect; }
set { _rect = value; }
}
/// <summary>
/// Left of the rectangle
/// </summary>
public double Left
{
get { return _rect.X; }
set { _rect.X = value; }
}
/// <summary>
/// Top of the rectangle
/// </summary>
public double Top
{
get { return _rect.Y; }
set { _rect.Y = value; }
}
/// <summary>
/// Width of the rectangle
/// </summary>
public double Width
{
get { return _rect.Width; }
set { _rect.Width = value; }
}
/// <summary>
/// Get the full width of the word including the spacing.
/// </summary>
public double FullWidth
{
get { return _rect.Width + ActualWordSpacing; }
}
/// <summary>
/// Gets the actual width of whitespace between words.
/// </summary>
public double ActualWordSpacing
{
get { return (OwnerBox != null ? (HasSpaceAfter ? OwnerBox.ActualWordSpacing : 0) + (IsImage ? OwnerBox.ActualWordSpacing : 0) : 0); }
}
/// <summary>
/// Height of the rectangle
/// </summary>
public double Height
{
get { return _rect.Height; }
set { _rect.Height = value; }
}
/// <summary>
/// Gets or sets the right of the rectangle. When setting, it only affects the Width of the rectangle.
/// </summary>
public double Right
{
get { return Rectangle.Right; }
set { Width = value - Left; }
}
/// <summary>
/// Gets or sets the bottom of the rectangle. When setting, it only affects the Height of the rectangle.
/// </summary>
public double Bottom
{
get { return Rectangle.Bottom; }
set { Height = value - Top; }
}
/// <summary>
/// If the word is selected this points to the selection handler for more data
/// </summary>
public SelectionHandler Selection
{
get { return _selection; }
set { _selection = value; }
}
/// <summary>
/// was there a whitespace before the word chars (before trim)
/// </summary>
public virtual bool HasSpaceBefore
{
get { return false; }
}
/// <summary>
/// was there a whitespace after the word chars (before trim)
/// </summary>
public virtual bool HasSpaceAfter
{
get { return false; }
}
/// <summary>
/// Gets the image this words represents (if one exists)
/// </summary>
public virtual RImage Image
{
get { return null; }
// ReSharper disable ValueParameterNotUsed
set { }
// ReSharper restore ValueParameterNotUsed
}
/// <summary>
/// Gets if the word represents an image.
/// </summary>
public virtual bool IsImage
{
get { return false; }
}
/// <summary>
/// Gets a bool indicating if this word is composed only by spaces.
/// Spaces include tabs and line breaks
/// </summary>
public virtual bool IsSpaces
{
get { return true; }
}
/// <summary>
/// Gets if the word is composed by only a line break
/// </summary>
public virtual bool IsLineBreak
{
get { return false; }
}
/// <summary>
/// Gets the text of the word
/// </summary>
public virtual string Text
{
get { return null; }
}
/// <summary>
/// is the word is currently selected
/// </summary>
public bool Selected
{
get { return _selection != null; }
}
/// <summary>
/// the selection start index if the word is partially selected (-1 if not selected or fully selected)
/// </summary>
public int SelectedStartIndex
{
get { return _selection != null ? _selection.GetSelectingStartIndex(this) : -1; }
}
/// <summary>
/// the selection end index if the word is partially selected (-1 if not selected or fully selected)
/// </summary>
public int SelectedEndIndexOffset
{
get { return _selection != null ? _selection.GetSelectedEndIndexOffset(this) : -1; }
}
/// <summary>
/// the selection start offset if the word is partially selected (-1 if not selected or fully selected)
/// </summary>
public double SelectedStartOffset
{
get { return _selection != null ? _selection.GetSelectedStartOffset(this) : -1; }
}
/// <summary>
/// the selection end offset if the word is partially selected (-1 if not selected or fully selected)
/// </summary>
public double SelectedEndOffset
{
get { return _selection != null ? _selection.GetSelectedEndOffset(this) : -1; }
}
/// <summary>
/// Gets or sets an offset to be considered in measurements
/// </summary>
internal double LeftGlyphPadding
{
get { return OwnerBox != null ? OwnerBox.ActualFont.LeftPadding : 0; }
}
/// <summary>
/// Represents this word for debugging purposes
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0} ({1} char{2})", Text.Replace(' ', '-').Replace("\n", "\\n"), Text.Length, Text.Length != 1 ? "s" : string.Empty);
}
}
}
| |
// 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 Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.SymReaderInterop;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed class CompilationContext
{
private static readonly SymbolDisplayFormat s_fullNameFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
internal readonly CSharpCompilation Compilation;
internal readonly Binder NamespaceBinder; // Internal for test purposes.
private readonly MetadataDecoder _metadataDecoder;
private readonly MethodSymbol _currentFrame;
private readonly ImmutableArray<LocalSymbol> _locals;
private readonly ImmutableDictionary<string, DisplayClassVariable> _displayClassVariables;
private readonly ImmutableHashSet<string> _hoistedParameterNames;
private readonly ImmutableArray<LocalSymbol> _localsForBinding;
private readonly CSharpSyntaxNode _syntax;
private readonly bool _methodNotType;
/// <summary>
/// Create a context to compile expressions within a method scope.
/// </summary>
internal CompilationContext(
CSharpCompilation compilation,
MetadataDecoder metadataDecoder,
MethodSymbol currentFrame,
ImmutableArray<LocalSymbol> locals,
ImmutableSortedSet<int> inScopeHoistedLocalIndices,
MethodDebugInfo methodDebugInfo,
CSharpSyntaxNode syntax)
{
Debug.Assert(string.IsNullOrEmpty(methodDebugInfo.DefaultNamespaceName));
Debug.Assert((syntax == null) || (syntax is ExpressionSyntax) || (syntax is LocalDeclarationStatementSyntax));
// TODO: syntax.SyntaxTree should probably be added to the compilation,
// but it isn't rooted by a CompilationUnitSyntax so it doesn't work (yet).
_currentFrame = currentFrame;
_syntax = syntax;
_methodNotType = !locals.IsDefault;
// NOTE: Since this is done within CompilationContext, it will not be cached.
// CONSIDER: The values should be the same everywhere in the module, so they
// could be cached.
// (Catch: what happens in a type context without a method def?)
this.Compilation = GetCompilationWithExternAliases(compilation, methodDebugInfo.ExternAliasRecords);
_metadataDecoder = metadataDecoder;
// Each expression compile should use a unique compilation
// to ensure expression-specific synthesized members can be
// added (anonymous types, for instance).
Debug.Assert(this.Compilation != compilation);
this.NamespaceBinder = CreateBinderChain(
this.Compilation,
(PEModuleSymbol)currentFrame.ContainingModule,
currentFrame.ContainingNamespace,
methodDebugInfo.ImportRecordGroups,
_metadataDecoder);
if (_methodNotType)
{
_locals = locals;
ImmutableArray<string> displayClassVariableNamesInOrder;
GetDisplayClassVariables(
currentFrame,
_locals,
inScopeHoistedLocalIndices,
out displayClassVariableNamesInOrder,
out _displayClassVariables,
out _hoistedParameterNames);
Debug.Assert(displayClassVariableNamesInOrder.Length == _displayClassVariables.Count);
_localsForBinding = GetLocalsForBinding(_locals, displayClassVariableNamesInOrder, _displayClassVariables);
}
else
{
_locals = ImmutableArray<LocalSymbol>.Empty;
_displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
_localsForBinding = ImmutableArray<LocalSymbol>.Empty;
}
// Assert that the cheap check for "this" is equivalent to the expensive check for "this".
Debug.Assert(
_displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName()) ==
_displayClassVariables.Values.Any(v => v.Kind == DisplayClassVariableKind.This));
}
internal CommonPEModuleBuilder CompileExpression(
InspectionContext inspectionContext,
string typeName,
string methodName,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
Debug.Assert(inspectionContext != null);
var properties = default(ResultProperties);
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
inspectionContext,
this.Compilation,
_metadataDecoder,
_syntax,
method,
this.NamespaceBinder,
hasDisplayClassThis,
_methodNotType);
var statementSyntax = _syntax as StatementSyntax;
return (statementSyntax == null) ?
BindExpression(binder, (ExpressionSyntax)_syntax, diags, out properties) :
BindStatement(binder, statementSyntax, diags, out properties);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = properties;
return module;
}
internal CommonPEModuleBuilder CompileAssignment(
InspectionContext inspectionContext,
string typeName,
string methodName,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics,
out ResultProperties resultProperties)
{
Debug.Assert(inspectionContext != null);
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var synthesizedType = new EENamedTypeSymbol(
Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
methodName,
this,
(method, diags) =>
{
var hasDisplayClassThis = _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName());
var binder = ExtendBinderChain(
inspectionContext,
this.Compilation,
_metadataDecoder,
_syntax,
method,
this.NamespaceBinder,
hasDisplayClassThis,
methodNotType: true);
return BindAssignment(binder, (ExpressionSyntax)_syntax, diags);
});
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: ImmutableArray.Create((NamedTypeSymbol)synthesizedType),
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
// Should be no name mangling since the caller provided explicit names.
Debug.Assert(synthesizedType.MetadataName == typeName);
Debug.Assert(synthesizedType.GetMembers()[0].MetadataName == methodName);
resultProperties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect);
return module;
}
private static string GetNextMethodName(ArrayBuilder<MethodSymbol> builder)
{
return string.Format("<>m{0}", builder.Count);
}
/// <summary>
/// Generate a class containing methods that represent
/// the set of arguments and locals at the current scope.
/// </summary>
internal CommonPEModuleBuilder CompileGetLocals(
string typeName,
ArrayBuilder<LocalAndMethod> localBuilder,
bool argumentsOnly,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
var objectType = this.Compilation.GetSpecialType(SpecialType.System_Object);
var allTypeParameters = _currentFrame.GetAllTypeParameters();
var additionalTypes = ArrayBuilder<NamedTypeSymbol>.GetInstance();
EENamedTypeSymbol typeVariablesType = null;
if (!argumentsOnly && (allTypeParameters.Length > 0))
{
// Generate a generic type with matching type parameters.
// A null instance of the type will be used to represent the
// "Type variables" local.
typeVariablesType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
ExpressionCompilerConstants.TypeVariablesClassName,
(m, t) => ImmutableArray.Create<MethodSymbol>(new EEConstructorSymbol(t)),
allTypeParameters,
(t1, t2) => allTypeParameters.SelectAsArray((tp, i, t) => (TypeParameterSymbol)new SimpleTypeParameterSymbol(t, i, tp.Name), t2));
additionalTypes.Add(typeVariablesType);
}
var synthesizedType = new EENamedTypeSymbol(
this.Compilation.SourceModule.GlobalNamespace,
objectType,
_syntax,
_currentFrame,
typeName,
(m, container) =>
{
var methodBuilder = ArrayBuilder<MethodSymbol>.GetInstance();
if (!argumentsOnly)
{
// "this" for non-static methods that are not display class methods or
// display class methods where the display class contains "<>4__this".
if (!m.IsStatic && (!IsDisplayClassType(m.ContainingType) || _displayClassVariables.ContainsKey(GeneratedNames.ThisProxyFieldName())))
{
var methodName = GetNextMethodName(methodBuilder);
var method = this.GetThisMethod(container, methodName);
localBuilder.Add(new LocalAndMethod("this", methodName, DkmClrCompilationResultFlags.None)); // Note: writable in dev11.
methodBuilder.Add(method);
}
}
// Hoisted method parameters (represented as locals in the EE).
if (!_hoistedParameterNames.IsEmpty)
{
int localIndex = 0;
foreach (var local in _localsForBinding)
{
// Since we are showing hoisted method parameters first, the parameters may appear out of order
// in the Locals window if only some of the parameters are hoisted. This is consistent with the
// behavior of the old EE.
var localName = local.Name;
if (_hoistedParameterNames.Contains(local.Name))
{
AppendLocalAndMethod(localBuilder, methodBuilder, localName, this.GetLocalMethod, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
}
// Method parameters (except those that have been hoisted).
int parameterIndex = m.IsStatic ? 0 : 1;
foreach (var parameter in m.Parameters)
{
var parameterName = parameter.Name;
if (!_hoistedParameterNames.Contains(parameterName))
{
AppendLocalAndMethod(localBuilder, methodBuilder, parameterName, this.GetParameterMethod, container, parameterIndex, DkmClrCompilationResultFlags.None);
}
parameterIndex++;
}
if (!argumentsOnly)
{
// Locals.
int localIndex = 0;
foreach (var local in _localsForBinding)
{
var localName = local.Name;
if (!_hoistedParameterNames.Contains(localName))
{
AppendLocalAndMethod(localBuilder, methodBuilder, localName, this.GetLocalMethod, container, localIndex, GetLocalResultFlags(local));
}
localIndex++;
}
// "Type variables".
if ((object)typeVariablesType != null)
{
var methodName = GetNextMethodName(methodBuilder);
var returnType = typeVariablesType.Construct(allTypeParameters.Cast<TypeParameterSymbol, TypeSymbol>());
var method = this.GetTypeVariablesMethod(container, methodName, returnType);
localBuilder.Add(new LocalAndMethod(ExpressionCompilerConstants.TypeVariablesLocalName, methodName, DkmClrCompilationResultFlags.ReadOnlyResult));
methodBuilder.Add(method);
}
}
return methodBuilder.ToImmutableAndFree();
});
additionalTypes.Add(synthesizedType);
var module = CreateModuleBuilder(
this.Compilation,
synthesizedType.Methods,
additionalTypes: additionalTypes.ToImmutableAndFree(),
testData: testData,
diagnostics: diagnostics);
Debug.Assert(module != null);
this.Compilation.Compile(
module,
win32Resources: null,
xmlDocStream: null,
generateDebugInfo: false,
diagnostics: diagnostics,
filterOpt: null,
cancellationToken: CancellationToken.None);
return diagnostics.HasAnyErrors() ? null : module;
}
private static void AppendLocalAndMethod(
ArrayBuilder<LocalAndMethod> localBuilder,
ArrayBuilder<MethodSymbol> methodBuilder,
string name,
Func<EENamedTypeSymbol, string, string, int, MethodSymbol> getMethod,
EENamedTypeSymbol container,
int localOrParameterIndex,
DkmClrCompilationResultFlags resultFlags)
{
// Note: The native EE doesn't do this, but if we don't escape keyword identifiers,
// the ResultProvider needs to be able to disambiguate cases like "this" and "@this",
// which it can't do correctly without semantic information.
name = SyntaxHelpers.EscapeKeywordIdentifiers(name);
var methodName = GetNextMethodName(methodBuilder);
var method = getMethod(container, methodName, name, localOrParameterIndex);
localBuilder.Add(new LocalAndMethod(name, methodName, resultFlags));
methodBuilder.Add(method);
}
private static EEAssemblyBuilder CreateModuleBuilder(
CSharpCompilation compilation,
ImmutableArray<MethodSymbol> methods,
ImmutableArray<NamedTypeSymbol> additionalTypes,
Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData,
DiagnosticBag diagnostics)
{
// Each assembly must have a unique name.
var emitOptions = new EmitOptions(outputNameOverride: ExpressionCompilerUtilities.GenerateUniqueName());
string runtimeMetadataVersion = compilation.GetRuntimeMetadataVersion(emitOptions, diagnostics);
var serializationProperties = compilation.ConstructModuleSerializationProperties(emitOptions, runtimeMetadataVersion);
return new EEAssemblyBuilder(compilation.SourceAssembly, emitOptions, methods, serializationProperties, additionalTypes, testData);
}
internal EEMethodSymbol CreateMethod(
EENamedTypeSymbol container,
string methodName,
CSharpSyntaxNode syntax,
GenerateMethodBody generateMethodBody)
{
return new EEMethodSymbol(
container,
methodName,
syntax.Location,
_currentFrame,
_locals,
_localsForBinding,
_displayClassVariables,
generateMethodBody);
}
private EEMethodSymbol GetLocalMethod(EENamedTypeSymbol container, string methodName, string localName, int localIndex)
{
var syntax = SyntaxFactory.IdentifierName(localName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var local = method.LocalsForBinding[localIndex];
var expression = new BoundLocal(syntax, local, constantValueOpt: local.GetConstantValue(null, null, diagnostics), type: local.Type) { WasCompilerGenerated = true };
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetParameterMethod(EENamedTypeSymbol container, string methodName, string parameterName, int parameterIndex)
{
var syntax = SyntaxFactory.IdentifierName(parameterName);
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var parameter = method.Parameters[parameterIndex];
var expression = new BoundParameter(syntax, parameter) { WasCompilerGenerated = true };
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetThisMethod(EENamedTypeSymbol container, string methodName)
{
var syntax = SyntaxFactory.ThisExpression();
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var expression = new BoundThisReference(syntax, GetNonDisplayClassContainer(container.SubstitutedSourceType)) { WasCompilerGenerated = true };
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
});
}
private EEMethodSymbol GetTypeVariablesMethod(EENamedTypeSymbol container, string methodName, NamedTypeSymbol typeVariablesType)
{
var syntax = SyntaxFactory.IdentifierName("");
return this.CreateMethod(container, methodName, syntax, (method, diagnostics) =>
{
var type = method.TypeMap.SubstituteNamedType(typeVariablesType);
var expression = new BoundObjectCreationExpression(syntax, type.InstanceConstructors[0]) { WasCompilerGenerated = true };
var statement = new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
return statement;
});
}
private static BoundStatement BindExpression(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics, out ResultProperties resultProperties)
{
var flags = DkmClrCompilationResultFlags.None;
// In addition to C# expressions, the native EE also supports
// type names which are bound to a representation of the type
// (but not System.Type) that the user can expand to see the
// base type. Instead, we only allow valid C# expressions.
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
if (MayHaveSideEffectsVisitor.MayHaveSideEffects(expression))
{
flags |= DkmClrCompilationResultFlags.PotentialSideEffect;
}
var expressionType = expression.Type;
if ((object)expressionType == null)
{
expression = binder.CreateReturnConversion(
syntax,
diagnostics,
expression,
binder.Compilation.GetSpecialType(SpecialType.System_Object));
if (diagnostics.HasAnyErrors())
{
resultProperties = default(ResultProperties);
return null;
}
}
else if (expressionType.SpecialType == SpecialType.System_Void)
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
Debug.Assert(expression.ConstantValue == null);
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, isConstant: false);
return new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true };
}
else if (expressionType.SpecialType == SpecialType.System_Boolean)
{
flags |= DkmClrCompilationResultFlags.BoolResult;
}
if (!IsAssignableExpression(binder, expression))
{
flags |= DkmClrCompilationResultFlags.ReadOnlyResult;
}
resultProperties = expression.ExpressionSymbol.GetResultProperties(flags, expression.ConstantValue != null);
return new BoundReturnStatement(syntax, expression) { WasCompilerGenerated = true };
}
private static BoundStatement BindStatement(Binder binder, StatementSyntax syntax, DiagnosticBag diagnostics, out ResultProperties properties)
{
properties = new ResultProperties(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
return binder.BindStatement(syntax, diagnostics);
}
private static bool IsAssignableExpression(Binder binder, BoundExpression expression)
{
// NOTE: Surprisingly, binder.CheckValueKind will return true (!) for readonly fields
// in contexts where they cannot be assigned - it simply reports a diagnostic.
// Presumably, this is done to avoid producing a confusing error message about the
// field not being an lvalue.
var diagnostics = DiagnosticBag.GetInstance();
var result = binder.CheckValueKind(expression, Binder.BindValueKind.Assignment, diagnostics) &&
!diagnostics.HasAnyErrors();
diagnostics.Free();
return result;
}
private static BoundStatement BindAssignment(Binder binder, ExpressionSyntax syntax, DiagnosticBag diagnostics)
{
var expression = binder.BindValue(syntax, diagnostics, Binder.BindValueKind.RValue);
if (diagnostics.HasAnyErrors())
{
return null;
}
return new BoundExpressionStatement(expression.Syntax, expression) { WasCompilerGenerated = true };
}
private static Binder CreateBinderChain(
CSharpCompilation compilation,
PEModuleSymbol module,
NamespaceSymbol @namespace,
ImmutableArray<ImmutableArray<ImportRecord>> importRecordGroups,
MetadataDecoder metadataDecoder)
{
var stack = ArrayBuilder<string>.GetInstance();
while ((object)@namespace != null)
{
stack.Push(@namespace.Name);
@namespace = @namespace.ContainingNamespace;
}
var binder = (new BuckStopsHereBinder(compilation)).WithAdditionalFlags(
BinderFlags.SuppressObsoleteChecks |
BinderFlags.IgnoreAccessibility |
BinderFlags.UnsafeRegion |
BinderFlags.UncheckedRegion |
BinderFlags.AllowManagedAddressOf |
BinderFlags.AllowAwaitInUnsafeContext);
var hasImports = !importRecordGroups.IsDefault;
var numImportStringGroups = hasImports ? importRecordGroups.Length : 0;
var currentStringGroup = numImportStringGroups - 1;
// PERF: We used to call compilation.GetCompilationNamespace on every iteration,
// but that involved walking up to the global namespace, which we have to do
// anyway. Instead, we'll inline the functionality into our own walk of the
// namespace chain.
@namespace = compilation.GlobalNamespace;
while (stack.Count > 0)
{
var namespaceName = stack.Pop();
if (namespaceName.Length > 0)
{
// We're re-getting the namespace, rather than using the one containing
// the current frame method, because we want the merged namespace.
@namespace = @namespace.GetNestedNamespace(namespaceName);
Debug.Assert((object)@namespace != null,
$"We worked backwards from symbols to names, but no symbol exists for name '{namespaceName}'");
}
else
{
Debug.Assert((object)@namespace == (object)compilation.GlobalNamespace);
}
Imports imports = null;
if (hasImports)
{
if (currentStringGroup < 0)
{
Debug.WriteLine($"No import string group for namespace '{@namespace}'");
break;
}
var importsBinder = new InContainerBinder(@namespace, binder);
imports = BuildImports(compilation, module, importRecordGroups[currentStringGroup], importsBinder, metadataDecoder);
currentStringGroup--;
}
binder = new InContainerBinder(@namespace, binder, imports);
}
stack.Free();
if (currentStringGroup >= 0)
{
// CONSIDER: We could lump these into the outermost namespace. It's probably not worthwhile since
// the usings are already for the wrong method.
Debug.WriteLine($"Found {currentStringGroup + 1} import string groups without corresponding namespaces");
}
return binder;
}
private static CSharpCompilation GetCompilationWithExternAliases(CSharpCompilation compilation, ImmutableArray<ExternAliasRecord> externAliasRecords)
{
if (externAliasRecords.IsDefaultOrEmpty)
{
return compilation.Clone();
}
var updatedReferences = ArrayBuilder<MetadataReference>.GetInstance();
var assembliesAndModulesBuilder = ArrayBuilder<Symbol>.GetInstance();
foreach (var reference in compilation.References)
{
updatedReferences.Add(reference);
assembliesAndModulesBuilder.Add(compilation.GetAssemblyOrModuleSymbol(reference));
}
Debug.Assert(assembliesAndModulesBuilder.Count == updatedReferences.Count);
var assembliesAndModules = assembliesAndModulesBuilder.ToImmutableAndFree();
foreach (var externAliasRecord in externAliasRecords)
{
int index = externAliasRecord.GetIndexOfTargetAssembly(assembliesAndModules, compilation.Options.AssemblyIdentityComparer);
if (index < 0)
{
Debug.WriteLine($"Unable to find corresponding assembly reference for extern alias '{externAliasRecord}'");
continue;
}
var externAlias = externAliasRecord.Alias;
var assemblyReference = updatedReferences[index];
var oldAliases = assemblyReference.Properties.Aliases;
var newAliases = oldAliases.IsEmpty
? ImmutableArray.Create(MetadataReferenceProperties.GlobalAlias, externAlias)
: oldAliases.Concat(ImmutableArray.Create(externAlias));
// NOTE: Dev12 didn't emit custom debug info about "global", so we don't have
// a good way to distinguish between a module aliased with both (e.g.) "X" and
// "global" and a module aliased with only "X". As in Dev12, we assume that
// "global" is a valid alias to remain at least as permissive as source.
// NOTE: In the event that this introduces ambiguities between two assemblies
// (e.g. because one was "global" in source and the other was "X"), it should be
// possible to disambiguate as long as each assembly has a distinct extern alias,
// not necessarily used in source.
Debug.Assert(newAliases.Contains(MetadataReferenceProperties.GlobalAlias));
// Replace the value in the map with the updated reference.
updatedReferences[index] = assemblyReference.WithAliases(newAliases);
}
compilation = compilation.WithReferences(updatedReferences);
updatedReferences.Free();
return compilation;
}
private static Binder ExtendBinderChain(
InspectionContext inspectionContext,
CSharpCompilation compilation,
MetadataDecoder metadataDecoder,
CSharpSyntaxNode syntax,
EEMethodSymbol method,
Binder binder,
bool hasDisplayClassThis,
bool methodNotType)
{
var substitutedSourceMethod = GetSubstitutedSourceMethod(method.SubstitutedSourceMethod, hasDisplayClassThis);
var substitutedSourceType = substitutedSourceMethod.ContainingType;
var stack = ArrayBuilder<NamedTypeSymbol>.GetInstance();
for (var type = substitutedSourceType; (object)type != null; type = type.ContainingType)
{
stack.Add(type);
}
while (stack.Count > 0)
{
substitutedSourceType = stack.Pop();
binder = new InContainerBinder(substitutedSourceType, binder);
if (substitutedSourceType.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceType.TypeArguments, binder);
}
}
stack.Free();
if (substitutedSourceMethod.Arity > 0)
{
binder = new WithTypeArgumentsBinder(substitutedSourceMethod.TypeArguments, binder);
}
if (methodNotType)
{
// Method locals and parameters shadow pseudo-variables.
binder = new PlaceholderLocalBinder(inspectionContext, new EETypeNameDecoder(compilation, metadataDecoder.ModuleSymbol), syntax, method, binder);
}
binder = new EEMethodBinder(method, substitutedSourceMethod, binder);
if (methodNotType)
{
binder = new SimpleLocalScopeBinder(method.LocalsForBinding, binder);
}
return binder;
}
private static Imports BuildImports(CSharpCompilation compilation, PEModuleSymbol module, ImmutableArray<ImportRecord> importRecords, InContainerBinder binder, MetadataDecoder metadataDecoder)
{
// We make a first pass to extract all of the extern aliases because other imports may depend on them.
var externsBuilder = ArrayBuilder<AliasAndExternAliasDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
if (importRecord.TargetKind != ImportTargetKind.Assembly)
{
continue;
}
var alias = importRecord.Alias;
IdentifierNameSyntax aliasNameSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasNameSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{alias}'");
continue;
}
var externAliasSyntax = SyntaxFactory.ExternAliasDirective(aliasNameSyntax.Identifier);
var aliasSymbol = new AliasSymbol(binder, externAliasSyntax); // Binder is only used to access compilation.
externsBuilder.Add(new AliasAndExternAliasDirective(aliasSymbol, externAliasDirective: null)); // We have one, but we pass null for consistency.
}
var externs = externsBuilder.ToImmutableAndFree();
if (externs.Any())
{
// NB: This binder (and corresponding Imports) is only used to bind the other imports.
// We'll merge the externs into a final Imports object and return that to be used in
// the actual binder chain.
binder = new InContainerBinder(
binder.Container,
binder,
Imports.FromCustomDebugInfo(binder.Compilation, new Dictionary<string, AliasAndUsingDirective>(), ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty, externs));
}
var usingAliases = new Dictionary<string, AliasAndUsingDirective>();
var usingsBuilder = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance();
foreach (var importRecord in importRecords)
{
switch (importRecord.TargetKind)
{
case ImportTargetKind.Type:
{
var portableImportRecord = importRecord as PortableImportRecord;
TypeSymbol typeSymbol = portableImportRecord != null
? portableImportRecord.GetTargetType(metadataDecoder)
: metadataDecoder.GetTypeSymbolForSerializedType(importRecord.TargetString);
Debug.Assert((object)typeSymbol != null);
if (typeSymbol.IsErrorType())
{
// Type is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
else if (importRecord.Alias == null && !typeSymbol.IsStatic)
{
// Only static types can be directly imported.
continue;
}
if (!TryAddImport(importRecord.Alias, typeSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Namespace:
{
var namespaceName = importRecord.TargetString;
NameSyntax targetSyntax;
if (!SyntaxHelpers.TryParseDottedName(namespaceName, out targetSyntax))
{
// DevDiv #999086: Some previous version of VS apparently generated type aliases as "UA{alias} T{alias-qualified type name}".
// Neither Roslyn nor Dev12 parses such imports. However, Roslyn discards them, rather than interpreting them as "UA{alias}"
// (which will rarely work and never be correct).
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid target '{importRecord.TargetString}'");
continue;
}
NamespaceSymbol namespaceSymbol;
var portableImportRecord = importRecord as PortableImportRecord;
if (portableImportRecord != null)
{
var targetAssembly = portableImportRecord.GetTargetAssembly<ModuleSymbol, AssemblySymbol>(module, module.Module);
if ((object)targetAssembly == null)
{
namespaceSymbol = BindNamespace(namespaceName, compilation.GlobalNamespace);
}
else if (targetAssembly.IsMissing)
{
Debug.WriteLine($"Import record '{importRecord}' has invalid assembly reference '{targetAssembly.Identity}'");
continue;
}
else
{
namespaceSymbol = BindNamespace(namespaceName, targetAssembly.GlobalNamespace);
}
}
else
{
var globalNamespace = compilation.GlobalNamespace;
var externAlias = ((NativeImportRecord)importRecord).ExternAlias;
if (externAlias != null)
{
IdentifierNameSyntax externAliasSyntax = null;
if (!TryParseIdentifierNameSyntax(externAlias, out externAliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid extern alias '{externAlias}'");
continue;
}
var unusedDiagnostics = DiagnosticBag.GetInstance();
var aliasSymbol = (AliasSymbol)binder.BindNamespaceAliasSymbol(externAliasSyntax, unusedDiagnostics);
unusedDiagnostics.Free();
if ((object)aliasSymbol == null)
{
Debug.WriteLine($"Import record '{importRecord}' requires unknown extern alias '{externAlias}'");
continue;
}
globalNamespace = (NamespaceSymbol)aliasSymbol.Target;
}
namespaceSymbol = BindNamespace(namespaceName, globalNamespace);
}
if ((object)namespaceSymbol == null)
{
// Namespace is unrecognized. The import may have been
// valid in the original source but unnecessary.
continue; // Don't add anything for this import.
}
if (!TryAddImport(importRecord.Alias, namespaceSymbol, usingsBuilder, usingAliases, binder, importRecord))
{
continue;
}
break;
}
case ImportTargetKind.Assembly:
{
// Handled in first pass (above).
break;
}
default:
{
throw ExceptionUtilities.UnexpectedValue(importRecord.TargetKind);
}
}
}
return Imports.FromCustomDebugInfo(binder.Compilation, usingAliases, usingsBuilder.ToImmutableAndFree(), externs);
}
private static NamespaceSymbol BindNamespace(string namespaceName, NamespaceSymbol globalNamespace)
{
var namespaceSymbol = globalNamespace;
foreach (var name in namespaceName.Split('.'))
{
var members = namespaceSymbol.GetMembers(name);
namespaceSymbol = members.Length == 1
? members[0] as NamespaceSymbol
: null;
if ((object)namespaceSymbol == null)
{
break;
}
}
return namespaceSymbol;
}
private static bool TryAddImport(
string alias,
NamespaceOrTypeSymbol targetSymbol,
ArrayBuilder<NamespaceOrTypeAndUsingDirective> usingsBuilder,
Dictionary<string, AliasAndUsingDirective> usingAliases,
InContainerBinder binder,
ImportRecord importRecord)
{
if (alias == null)
{
usingsBuilder.Add(new NamespaceOrTypeAndUsingDirective(targetSymbol, usingDirective: null));
}
else
{
IdentifierNameSyntax aliasSyntax;
if (!TryParseIdentifierNameSyntax(alias, out aliasSyntax))
{
Debug.WriteLine($"Import record '{importRecord}' has syntactically invalid alias '{alias}'");
return false;
}
var aliasSymbol = AliasSymbol.CreateCustomDebugInfoAlias(targetSymbol, aliasSyntax.Identifier, binder);
usingAliases.Add(alias, new AliasAndUsingDirective(aliasSymbol, usingDirective: null));
}
return true;
}
private static bool TryParseIdentifierNameSyntax(string name, out IdentifierNameSyntax syntax)
{
Debug.Assert(name != null);
if (name == MetadataReferenceProperties.GlobalAlias)
{
syntax = SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword));
return true;
}
NameSyntax nameSyntax;
if (!SyntaxHelpers.TryParseDottedName(name, out nameSyntax) || nameSyntax.Kind() != SyntaxKind.IdentifierName)
{
syntax = null;
return false;
}
syntax = (IdentifierNameSyntax)nameSyntax;
return true;
}
internal CommonMessageProvider MessageProvider
{
get { return this.Compilation.MessageProvider; }
}
private static DkmClrCompilationResultFlags GetLocalResultFlags(LocalSymbol local)
{
// CONSIDER: We might want to prevent the user from modifying pinned locals -
// that's pretty dangerous.
return local.IsConst
? DkmClrCompilationResultFlags.ReadOnlyResult
: DkmClrCompilationResultFlags.None;
}
/// <summary>
/// Generate the set of locals to use for binding.
/// </summary>
private static ImmutableArray<LocalSymbol> GetLocalsForBinding(
ImmutableArray<LocalSymbol> locals,
ImmutableArray<string> displayClassVariableNamesInOrder,
ImmutableDictionary<string, DisplayClassVariable> displayClassVariables)
{
var builder = ArrayBuilder<LocalSymbol>.GetInstance();
foreach (var local in locals)
{
var name = local.Name;
if (name == null)
{
continue;
}
if (GeneratedNames.GetKind(name) != GeneratedNameKind.None)
{
continue;
}
// Although Roslyn doesn't name synthesized locals unless they are well-known to EE,
// Dev12 did so we need to skip them here.
if (GeneratedNames.IsSynthesizedLocalName(name))
{
continue;
}
builder.Add(local);
}
foreach (var variableName in displayClassVariableNamesInOrder)
{
var variable = displayClassVariables[variableName];
switch (variable.Kind)
{
case DisplayClassVariableKind.Local:
case DisplayClassVariableKind.Parameter:
builder.Add(new EEDisplayClassFieldLocalSymbol(variable));
break;
}
}
return builder.ToImmutableAndFree();
}
/// <summary>
/// Return a mapping of captured variables (parameters, locals, and
/// "this") to locals. The mapping is needed to expose the original
/// local identifiers (those from source) in the binder.
/// </summary>
private static void GetDisplayClassVariables(
MethodSymbol method,
ImmutableArray<LocalSymbol> locals,
ImmutableSortedSet<int> inScopeHoistedLocalIndices,
out ImmutableArray<string> displayClassVariableNamesInOrder,
out ImmutableDictionary<string, DisplayClassVariable> displayClassVariables,
out ImmutableHashSet<string> hoistedParameterNames)
{
// Calculated the shortest paths from locals to instances of display
// classes. There should not be two instances of the same display
// class immediately within any particular method.
var displayClassTypes = PooledHashSet<NamedTypeSymbol>.GetInstance();
var displayClassInstances = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
// Add any display class instances from locals (these will contain any hoisted locals).
foreach (var local in locals)
{
var name = local.Name;
if ((name != null) && (GeneratedNames.GetKind(name) == GeneratedNameKind.DisplayClassLocalOrField))
{
var instance = new DisplayClassInstanceFromLocal((EELocalSymbol)local);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
}
var containingType = method.ContainingType;
bool isIteratorOrAsyncMethod = false;
if (IsDisplayClassType(containingType))
{
if (!method.IsStatic)
{
// Add "this" display class instance.
var instance = new DisplayClassInstanceFromThis(method.ThisParameter);
displayClassTypes.Add(instance.Type);
displayClassInstances.Add(new DisplayClassInstanceAndFields(instance));
}
isIteratorOrAsyncMethod = GeneratedNames.GetKind(containingType.Name) == GeneratedNameKind.StateMachineType;
}
if (displayClassInstances.Any())
{
// Find any additional display class instances breadth first.
for (int depth = 0; GetDisplayClassInstances(displayClassTypes, displayClassInstances, depth) > 0; depth++)
{
}
// The locals are the set of all fields from the display classes.
var displayClassVariableNamesInOrderBuilder = ArrayBuilder<string>.GetInstance();
var displayClassVariablesBuilder = PooledDictionary<string, DisplayClassVariable>.GetInstance();
var parameterNames = PooledHashSet<string>.GetInstance();
if (isIteratorOrAsyncMethod)
{
Debug.Assert(IsDisplayClassType(containingType));
foreach (var field in containingType.GetMembers().OfType<FieldSymbol>())
{
// All iterator and async state machine fields (including hoisted locals) have mangled names, except
// for hoisted parameters (whose field names are always the same as the original source parameters).
var fieldName = field.Name;
if (GeneratedNames.GetKind(fieldName) == GeneratedNameKind.None)
{
parameterNames.Add(fieldName);
}
}
}
else
{
foreach (var p in method.Parameters)
{
parameterNames.Add(p.Name);
}
}
var pooledHoistedParameterNames = PooledHashSet<string>.GetInstance();
foreach (var instance in displayClassInstances)
{
GetDisplayClassVariables(
displayClassVariableNamesInOrderBuilder,
displayClassVariablesBuilder,
parameterNames,
inScopeHoistedLocalIndices,
instance,
pooledHoistedParameterNames);
}
hoistedParameterNames = pooledHoistedParameterNames.ToImmutableHashSet<string>();
pooledHoistedParameterNames.Free();
parameterNames.Free();
displayClassVariableNamesInOrder = displayClassVariableNamesInOrderBuilder.ToImmutableAndFree();
displayClassVariables = displayClassVariablesBuilder.ToImmutableDictionary();
displayClassVariablesBuilder.Free();
}
else
{
hoistedParameterNames = ImmutableHashSet<string>.Empty;
displayClassVariableNamesInOrder = ImmutableArray<string>.Empty;
displayClassVariables = ImmutableDictionary<string, DisplayClassVariable>.Empty;
}
displayClassTypes.Free();
displayClassInstances.Free();
}
/// <summary>
/// Return the set of display class instances that can be reached
/// from the given local. A particular display class may be reachable
/// from multiple locals. In those cases, the instance from the
/// shortest path (fewest intermediate fields) is returned.
/// </summary>
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
int depth)
{
Debug.Assert(displayClassInstances.All(p => p.Depth <= depth));
var atDepth = ArrayBuilder<DisplayClassInstanceAndFields>.GetInstance();
atDepth.AddRange(displayClassInstances.Where(p => p.Depth == depth));
Debug.Assert(atDepth.Count > 0);
int n = 0;
foreach (var instance in atDepth)
{
n += GetDisplayClassInstances(displayClassTypes, displayClassInstances, instance);
}
atDepth.Free();
return n;
}
private static int GetDisplayClassInstances(
HashSet<NamedTypeSymbol> displayClassTypes,
ArrayBuilder<DisplayClassInstanceAndFields> displayClassInstances,
DisplayClassInstanceAndFields instance)
{
// Display class instance. The display class fields are variables.
int n = 0;
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldType = field.Type;
var fieldKind = GeneratedNames.GetKind(field.Name);
if (fieldKind == GeneratedNameKind.DisplayClassLocalOrField ||
(fieldKind == GeneratedNameKind.ThisProxyField && GeneratedNames.GetKind(fieldType.Name) == GeneratedNameKind.LambdaDisplayClass)) // Async lambda case.
{
Debug.Assert(!field.IsStatic);
// A local that is itself a display class instance.
if (displayClassTypes.Add((NamedTypeSymbol)fieldType))
{
var other = instance.FromField(field);
displayClassInstances.Add(other);
n++;
}
}
}
return n;
}
private static void GetDisplayClassVariables(
ArrayBuilder<string> displayClassVariableNamesInOrderBuilder,
Dictionary<string, DisplayClassVariable> displayClassVariablesBuilder,
HashSet<string> parameterNames,
ImmutableSortedSet<int> inScopeHoistedLocalIndices,
DisplayClassInstanceAndFields instance,
HashSet<string> hoistedParameterNames)
{
// Display class instance. The display class fields are variables.
foreach (var member in instance.Type.GetMembers())
{
if (member.Kind != SymbolKind.Field)
{
continue;
}
var field = (FieldSymbol)member;
var fieldName = field.Name;
DisplayClassVariableKind variableKind;
string variableName;
GeneratedNameKind fieldKind;
int openBracketOffset;
int closeBracketOffset;
GeneratedNames.TryParseGeneratedName(fieldName, out fieldKind, out openBracketOffset, out closeBracketOffset);
switch (fieldKind)
{
case GeneratedNameKind.DisplayClassLocalOrField:
// A local that is itself a display class instance.
Debug.Assert(!field.IsStatic);
continue;
case GeneratedNameKind.HoistedLocalField:
// Filter out hoisted locals that are known to be out-of-scope at the current IL offset.
// Hoisted locals with invalid indices will be included since more information is better
// than less in error scenarios.
int slotIndex;
if (GeneratedNames.TryParseSlotIndex(fieldName, out slotIndex) && !inScopeHoistedLocalIndices.Contains(slotIndex))
{
continue;
}
variableName = fieldName.Substring(openBracketOffset + 1, closeBracketOffset - openBracketOffset - 1);
variableKind = DisplayClassVariableKind.Local;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.ThisProxyField:
// A reference to "this".
variableName = fieldName;
variableKind = DisplayClassVariableKind.This;
Debug.Assert(!field.IsStatic);
break;
case GeneratedNameKind.None:
// A reference to a parameter or local.
variableName = fieldName;
if (parameterNames.Contains(variableName))
{
variableKind = DisplayClassVariableKind.Parameter;
hoistedParameterNames.Add(variableName);
}
else
{
variableKind = DisplayClassVariableKind.Local;
}
Debug.Assert(!field.IsStatic);
break;
default:
continue;
}
if (displayClassVariablesBuilder.ContainsKey(variableName))
{
// Only expecting duplicates for async state machine
// fields (that should be at the top-level).
Debug.Assert(displayClassVariablesBuilder[variableName].DisplayClassFields.Count() == 1);
Debug.Assert(instance.Fields.Count() >= 1); // greater depth
Debug.Assert(variableKind == DisplayClassVariableKind.Parameter);
}
else if (variableKind != DisplayClassVariableKind.This || GeneratedNames.GetKind(instance.Type.ContainingType.Name) != GeneratedNameKind.LambdaDisplayClass)
{
// In async lambdas, the hoisted "this" field in the state machine type will point to the display class instance, if there is one.
// In such cases, we want to add the display class "this" to the map instead (or nothing, if it lacks one).
displayClassVariableNamesInOrderBuilder.Add(variableName);
displayClassVariablesBuilder.Add(variableName, instance.ToVariable(variableName, variableKind, field));
}
}
}
private static bool IsDisplayClassType(NamedTypeSymbol type)
{
switch (GeneratedNames.GetKind(type.Name))
{
case GeneratedNameKind.LambdaDisplayClass:
case GeneratedNameKind.StateMachineType:
return true;
default:
return false;
}
}
private static NamedTypeSymbol GetNonDisplayClassContainer(NamedTypeSymbol type)
{
// 1) Display class and state machine types are always nested within the types
// that use them (so that they can access private members of those types).
// 2) The native compiler used to produce nested display classes for nested lambdas,
// so we may have to walk out more than one level.
while (IsDisplayClassType(type))
{
type = type.ContainingType;
}
Debug.Assert((object)type != null);
return type;
}
/// <summary>
/// Identifies the method in which binding should occur.
/// </summary>
/// <param name="candidateSubstitutedSourceMethod">
/// The symbol of the method that is currently on top of the callstack, with
/// EE type parameters substituted in place of the original type parameters.
/// </param>
/// <param name="hasDisplayClassThis">
/// True if "this" is available via a display class in the current context.
/// </param>
/// <returns>
/// If <paramref name="candidateSubstitutedSourceMethod"/> is compiler-generated,
/// then we will attempt to determine which user-defined method caused it to be
/// generated. For example, if <paramref name="candidateSubstitutedSourceMethod"/>
/// is a state machine MoveNext method, then we will try to find the iterator or
/// async method for which it was generated. If we are able to find the original
/// method, then we will substitute in the EE type parameters. Otherwise, we will
/// return <paramref name="candidateSubstitutedSourceMethod"/>.
/// </returns>
/// <remarks>
/// In the event that the original method is overloaded, we may not be able to determine
/// which overload actually corresponds to the state machine. In particular, we do not
/// have information about the signature of the original method (i.e. number of parameters,
/// parameter types and ref-kinds, return type). However, we conjecture that this
/// level of uncertainty is acceptable, since parameters are managed by a separate binder
/// in the synthesized binder chain and we have enough information to check the other method
/// properties that are used during binding (e.g. static-ness, generic arity, type parameter
/// constraints).
/// </remarks>
internal static MethodSymbol GetSubstitutedSourceMethod(
MethodSymbol candidateSubstitutedSourceMethod,
bool hasDisplayClassThis)
{
var candidateSubstitutedSourceType = candidateSubstitutedSourceMethod.ContainingType;
string desiredMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceType.Name, GeneratedNameKind.StateMachineType, out desiredMethodName) ||
GeneratedNames.TryParseSourceMethodNameFromGeneratedName(candidateSubstitutedSourceMethod.Name, GeneratedNameKind.LambdaMethod, out desiredMethodName))
{
// We could be in the MoveNext method of an async lambda.
string tempMethodName;
if (GeneratedNames.TryParseSourceMethodNameFromGeneratedName(desiredMethodName, GeneratedNameKind.LambdaMethod, out tempMethodName))
{
desiredMethodName = tempMethodName;
var containing = candidateSubstitutedSourceType.ContainingType;
Debug.Assert((object)containing != null);
if (GeneratedNames.GetKind(containing.Name) == GeneratedNameKind.LambdaDisplayClass)
{
candidateSubstitutedSourceType = containing;
hasDisplayClassThis = candidateSubstitutedSourceType.MemberNames.Select(GeneratedNames.GetKind).Contains(GeneratedNameKind.ThisProxyField);
}
}
var desiredTypeParameters = candidateSubstitutedSourceType.OriginalDefinition.TypeParameters;
// We need to use a ThreeState, rather than a bool, because we can't distinguish between
// a roslyn lambda that only captures "this" and a dev12 lambda that captures nothing
// (neither introduces a display class). This is unnecessary in the state machine case,
// because then "this" is hoisted unconditionally.
var isDesiredMethodStatic = hasDisplayClassThis
? ThreeState.False
: (GeneratedNames.GetKind(candidateSubstitutedSourceType.Name) == GeneratedNameKind.StateMachineType)
? ThreeState.True
: ThreeState.Unknown;
// Type containing the original iterator, async, or lambda-containing method.
var substitutedSourceType = GetNonDisplayClassContainer(candidateSubstitutedSourceType);
foreach (var candidateMethod in substitutedSourceType.GetMembers().OfType<MethodSymbol>())
{
if (IsViableSourceMethod(candidateMethod, desiredMethodName, desiredTypeParameters, isDesiredMethodStatic))
{
return desiredTypeParameters.Length == 0
? candidateMethod
: candidateMethod.Construct(candidateSubstitutedSourceType.TypeArguments);
}
}
Debug.Assert(false, "Why didn't we find a substituted source method for " + candidateSubstitutedSourceMethod + "?");
}
return candidateSubstitutedSourceMethod;
}
private static bool IsViableSourceMethod(MethodSymbol candidateMethod, string desiredMethodName, ImmutableArray<TypeParameterSymbol> desiredTypeParameters, ThreeState isDesiredMethodStatic)
{
return
!candidateMethod.IsAbstract &&
(isDesiredMethodStatic == ThreeState.Unknown || isDesiredMethodStatic.Value() == candidateMethod.IsStatic) &&
candidateMethod.Name == desiredMethodName &&
HaveSameConstraints(candidateMethod.TypeParameters, desiredTypeParameters);
}
private static bool HaveSameConstraints(ImmutableArray<TypeParameterSymbol> candidateTypeParameters, ImmutableArray<TypeParameterSymbol> desiredTypeParameters)
{
int arity = candidateTypeParameters.Length;
if (arity != desiredTypeParameters.Length)
{
return false;
}
else if (arity == 0)
{
return true;
}
var indexedTypeParameters = IndexedTypeParameterSymbol.Take(arity);
var candidateTypeMap = new TypeMap(candidateTypeParameters, indexedTypeParameters, allowAlpha: true);
var desiredTypeMap = new TypeMap(desiredTypeParameters, indexedTypeParameters, allowAlpha: true);
return MemberSignatureComparer.HaveSameConstraints(candidateTypeParameters, candidateTypeMap, desiredTypeParameters, desiredTypeMap);
}
private struct DisplayClassInstanceAndFields
{
internal readonly DisplayClassInstance Instance;
internal readonly ConsList<FieldSymbol> Fields;
internal DisplayClassInstanceAndFields(DisplayClassInstance instance) :
this(instance, ConsList<FieldSymbol>.Empty)
{
Debug.Assert(IsDisplayClassType(instance.Type));
}
private DisplayClassInstanceAndFields(DisplayClassInstance instance, ConsList<FieldSymbol> fields)
{
this.Instance = instance;
this.Fields = fields;
}
internal NamedTypeSymbol Type
{
get { return this.Fields.Any() ? (NamedTypeSymbol)this.Fields.Head.Type : this.Instance.Type; }
}
internal int Depth
{
get { return this.Fields.Count(); }
}
internal DisplayClassInstanceAndFields FromField(FieldSymbol field)
{
Debug.Assert(IsDisplayClassType((NamedTypeSymbol)field.Type));
return new DisplayClassInstanceAndFields(this.Instance, this.Fields.Prepend(field));
}
internal DisplayClassVariable ToVariable(string name, DisplayClassVariableKind kind, FieldSymbol field)
{
return new DisplayClassVariable(name, kind, this.Instance, this.Fields.Prepend(field));
}
}
}
}
| |
using BgeniiusUniversity.DAL;
using BgeniiusUniversity.Models;
namespace BgeniiusUniversity.Migrations
{
using BgeniiusUniversity.Models;
using BgeniiusUniversity.DAL;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(SchoolContext context)
{
var students = new List<Student>
{
new Student { FirstMidName = "Carson", LastName = "Alexander",
EnrollmentDate = DateTime.Parse("2010-09-01") },
new Student { FirstMidName = "Meredith", LastName = "Alonso",
EnrollmentDate = DateTime.Parse("2012-09-01") },
new Student { FirstMidName = "Arturo", LastName = "Anand",
EnrollmentDate = DateTime.Parse("2013-09-01") },
new Student { FirstMidName = "Gytis", LastName = "Barzdukas",
EnrollmentDate = DateTime.Parse("2012-09-01") },
new Student { FirstMidName = "Yan", LastName = "Li",
EnrollmentDate = DateTime.Parse("2012-09-01") },
new Student { FirstMidName = "Peggy", LastName = "Justice",
EnrollmentDate = DateTime.Parse("2011-09-01") },
new Student { FirstMidName = "Laura", LastName = "Norman",
EnrollmentDate = DateTime.Parse("2013-09-01") },
new Student { FirstMidName = "Nino", LastName = "Olivetto",
EnrollmentDate = DateTime.Parse("2005-09-01") }
};
students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var instructors = new List<Instructor>
{
new Instructor { FirstMidName = "Kim", LastName = "Abercrombie",
HireDate = DateTime.Parse("1995-03-11") },
new Instructor { FirstMidName = "Fadi", LastName = "Fakhouri",
HireDate = DateTime.Parse("2002-07-06") },
new Instructor { FirstMidName = "Roger", LastName = "Harui",
HireDate = DateTime.Parse("1998-07-01") },
new Instructor { FirstMidName = "Candace", LastName = "Kapoor",
HireDate = DateTime.Parse("2001-01-15") },
new Instructor { FirstMidName = "Roger", LastName = "Zheng",
HireDate = DateTime.Parse("2004-02-12") }
};
instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
context.SaveChanges();
var departments = new List<Department>
{
new Department { Name = "English", Budget = 350000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Abercrombie").ID },
new Department { Name = "Mathematics", Budget = 100000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID },
new Department { Name = "Engineering", Budget = 350000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Harui").ID },
new Department { Name = "Economics", Budget = 100000,
StartDate = DateTime.Parse("2007-09-01"),
InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID }
};
departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
var courses = new List<Course>
{
new Course {CourseID = 1050, Title = "Chemistry", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 1045, Title = "Calculus", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 3141, Title = "Trigonometry", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 2021, Title = "Composition", Credits = 3,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
Instructors = new List<Instructor>()
},
new Course {CourseID = 2042, Title = "Literature", Credits = 4,
DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
Instructors = new List<Instructor>()
},
};
courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s));
context.SaveChanges();
var officeAssignments = new List<OfficeAssignment>
{
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID,
Location = "Smith 17" },
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Harui").ID,
Location = "Gowan 27" },
new OfficeAssignment {
InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID,
Location = "Thompson 304" },
};
officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.InstructorID, s));
context.SaveChanges();
AddOrUpdateInstructor(context, "Chemistry", "Kapoor");
AddOrUpdateInstructor(context, "Chemistry", "Harui");
AddOrUpdateInstructor(context, "Microeconomics", "Zheng");
AddOrUpdateInstructor(context, "Macroeconomics", "Zheng");
AddOrUpdateInstructor(context, "Calculus", "Fakhouri");
AddOrUpdateInstructor(context, "Trigonometry", "Harui");
AddOrUpdateInstructor(context, "Composition", "Abercrombie");
AddOrUpdateInstructor(context, "Literature", "Abercrombie");
context.SaveChanges();
var enrollments = new List<Enrollment>
{
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID,
Grade = Grade.A
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID,
Grade = Grade.C
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alexander").ID,
CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Alonso").ID,
CourseID = courses.Single(c => c.Title == "Composition" ).CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Anand").ID,
CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Anand").ID,
CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Barzdukas").ID,
CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Li").ID,
CourseID = courses.Single(c => c.Title == "Composition").CourseID,
Grade = Grade.B
},
new Enrollment {
StudentID = students.Single(s => s.LastName == "Justice").ID,
CourseID = courses.Single(c => c.Title == "Literature").CourseID,
Grade = Grade.B
}
};
foreach (Enrollment e in enrollments)
{
var enrollmentInDataBase = context.Enrollments.Where(
s =>
s.Student.ID == e.StudentID &&
s.Course.CourseID == e.CourseID).SingleOrDefault();
if (enrollmentInDataBase == null)
{
context.Enrollments.Add(e);
}
}
context.SaveChanges();
}
void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName)
{
var crs = context.Courses.SingleOrDefault(c => c.Title == courseTitle);
var inst = crs.Instructors.SingleOrDefault(i => i.LastName == instructorName);
if (inst == null)
crs.Instructors.Add(context.Instructors.Single(i => i.LastName == instructorName));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System
{
/*
Customized format patterns:
P.S. Format in the table below is the internal number format used to display the pattern.
Patterns Format Description Example
========= ========== ===================================== ========
"h" "0" hour (12-hour clock)w/o leading zero 3
"hh" "00" hour (12-hour clock)with leading zero 03
"hh*" "00" hour (12-hour clock)with leading zero 03
"H" "0" hour (24-hour clock)w/o leading zero 8
"HH" "00" hour (24-hour clock)with leading zero 08
"HH*" "00" hour (24-hour clock) 08
"m" "0" minute w/o leading zero
"mm" "00" minute with leading zero
"mm*" "00" minute with leading zero
"s" "0" second w/o leading zero
"ss" "00" second with leading zero
"ss*" "00" second with leading zero
"f" "0" second fraction (1 digit)
"ff" "00" second fraction (2 digit)
"fff" "000" second fraction (3 digit)
"ffff" "0000" second fraction (4 digit)
"fffff" "00000" second fraction (5 digit)
"ffffff" "000000" second fraction (6 digit)
"fffffff" "0000000" second fraction (7 digit)
"F" "0" second fraction (up to 1 digit)
"FF" "00" second fraction (up to 2 digit)
"FFF" "000" second fraction (up to 3 digit)
"FFFF" "0000" second fraction (up to 4 digit)
"FFFFF" "00000" second fraction (up to 5 digit)
"FFFFFF" "000000" second fraction (up to 6 digit)
"FFFFFFF" "0000000" second fraction (up to 7 digit)
"t" first character of AM/PM designator A
"tt" AM/PM designator AM
"tt*" AM/PM designator PM
"d" "0" day w/o leading zero 1
"dd" "00" day with leading zero 01
"ddd" short weekday name (abbreviation) Mon
"dddd" full weekday name Monday
"dddd*" full weekday name Monday
"M" "0" month w/o leading zero 2
"MM" "00" month with leading zero 02
"MMM" short month name (abbreviation) Feb
"MMMM" full month name Febuary
"MMMM*" full month name Febuary
"y" "0" two digit year (year % 100) w/o leading zero 0
"yy" "00" two digit year (year % 100) with leading zero 00
"yyy" "D3" year 2000
"yyyy" "D4" year 2000
"yyyyy" "D5" year 2000
...
"z" "+0;-0" timezone offset w/o leading zero -8
"zz" "+00;-00" timezone offset with leading zero -08
"zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30
"zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00
"K" -Local "zzz", e.g. -08:00
-Utc "'Z'", representing UTC
-Unspecified ""
-DateTimeOffset "zzzzz" e.g -07:30:15
"g*" the current era name A.D.
":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss")
"/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy")
"'" quoted string 'ABC' will insert ABC into the formatted string.
'"' quoted string "ABC" will insert ABC into the formatted string.
"%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year.
"\" escaped character E.g. '\d' insert the character 'd' into the format string.
other characters insert the character into the format string.
Pre-defined format characters:
(U) to indicate Universal time is used.
(G) to indicate Gregorian calendar is used.
Format Description Real format Example
========= ================================= ====================== =======================
"d" short date culture-specific 10/31/1999
"D" long data culture-specific Sunday, October 31, 1999
"f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM
"F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM
"g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM
"G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM
"m"/"M" Month/Day date culture-specific October 31
(G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z
(G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT
(G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
('T' for local time)
"t" short time culture-specific 2:00 AM
"T" long time culture-specific 2:00:00 AM
(G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z
based on ISO 8601.
(U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM
(long date + long time) format
"y"/"Y" Year/Month day culture-specific October, 1999
*/
//This class contains only static members and does not require the serializable attribute.
internal static
class DateTimeFormat
{
internal const int MaxSecondsFractionDigits = 7;
internal static readonly TimeSpan NullOffset = TimeSpan.MinValue;
internal static char[] allStandardFormats =
{
'd', 'D', 'f', 'F', 'g', 'G',
'm', 'M', 'o', 'O', 'r', 'R',
's', 't', 'T', 'u', 'U', 'y', 'Y',
};
internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK";
internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz";
private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat;
internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames;
internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames;
internal const string Gmt = "GMT";
internal static String[] fixedNumberFormats = new String[] {
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
};
////////////////////////////////////////////////////////////////////////////
//
// Format the positive integer value to a string and perfix with assigned
// length of leading zero.
//
// Parameters:
// value: The value to format
// len: The maximum length for leading zero.
// If the digits of the value is greater than len, no leading zero is added.
//
// Notes:
// The function can format to Int32.MaxValue.
//
////////////////////////////////////////////////////////////////////////////
internal static void FormatDigits(StringBuilder outputBuffer, int value, int len)
{
Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
FormatDigits(outputBuffer, value, len, false);
}
internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit)
{
Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
// Limit the use of this function to be two-digits, so that we have the same behavior
// as RTM bits.
if (!overrideLengthLimit && len > 2)
{
len = 2;
}
char* buffer = stackalloc char[16];
char* p = buffer + 16;
int n = value;
do
{
*--p = (char)(n % 10 + '0');
n /= 10;
} while ((n != 0) && (p > buffer));
int digits = (int)(buffer + 16 - p);
//If the repeat count is greater than 0, we're trying
//to emulate the "00" format, so we have to prepend
//a zero if the string only has one character.
while ((digits < len) && (p > buffer))
{
*--p = '0';
digits++;
}
outputBuffer.Append(p, digits);
}
private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits)
{
outputBuffer.Append(HebrewNumber.ToString(digits));
}
internal static int ParseRepeatPattern(ReadOnlySpan<char> format, int pos, char patternChar)
{
int len = format.Length;
int index = pos + 1;
while ((index < len) && (format[index] == patternChar))
{
index++;
}
return (index - pos);
}
private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
{
Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
if (repeat == 3)
{
return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
}
// Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't
// want a clone of DayNames, which will hurt perf.
return (dtfi.GetDayName((DayOfWeek)dayOfWeek));
}
private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
{
Debug.Assert(month >= 1 && month <= 12, "month >=1 && month <= 12");
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
}
// Call GetMonthName() here, instead of accessing MonthNames property, because we don't
// want a clone of MonthNames, which will hurt perf.
return (dtfi.GetMonthName(month));
}
//
// FormatHebrewMonthName
//
// Action: Return the Hebrew month name for the specified DateTime.
// Returns: The month name string for the specified DateTime.
// Arguments:
// time the time to format
// month The month is the value of HebrewCalendar.GetMonth(time).
// repeat Return abbreviated month name if repeat=3, or full month name if repeat=4
// dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar.
// Exceptions: None.
//
/* Note:
If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this:
1 Hebrew 1st Month
2 Hebrew 2nd Month
.. ...
6 Hebrew 6th Month
7 Hebrew 6th Month II (used only in a leap year)
8 Hebrew 7th Month
9 Hebrew 8th Month
10 Hebrew 9th Month
11 Hebrew 10th Month
12 Hebrew 11th Month
13 Hebrew 12th Month
Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7.
*/
private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
{
Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time)))
{
// This month is in a leap year
return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
}
// This is in a regular year.
if (month >= 7)
{
month++;
}
if (repeatCount == 3)
{
return (dtfi.GetAbbreviatedMonthName(month));
}
return (dtfi.GetMonthName(month));
}
//
// The pos should point to a quote character. This method will
// append to the result StringBuilder the string encloed by the quote character.
//
internal static int ParseQuoteString(ReadOnlySpan<char> format, int pos, StringBuilder result)
{
//
// NOTE : pos will be the index of the quote character in the 'format' string.
//
int formatLen = format.Length;
int beginPos = pos;
char quoteChar = format[pos++]; // Get the character used to quote the following string.
bool foundQuote = false;
while (pos < formatLen)
{
char ch = format[pos++];
if (ch == quoteChar)
{
foundQuote = true;
break;
}
else if (ch == '\\')
{
// The following are used to support escaped character.
// Escaped character is also supported in the quoted string.
// Therefore, someone can use a format like "'minute:' mm\"" to display:
// minute: 45"
// because the second double quote is escaped.
if (pos < formatLen)
{
result.Append(format[pos++]);
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
throw new FormatException(SR.Format_InvalidString);
}
}
else
{
result.Append(ch);
}
}
if (!foundQuote)
{
// Here we can't find the matching quote.
throw new FormatException(
String.Format(
CultureInfo.CurrentCulture,
SR.Format_BadQuote, quoteChar));
}
//
// Return the character count including the begin/end quote characters and enclosed string.
//
return (pos - beginPos);
}
//
// Get the next character at the index of 'pos' in the 'format' string.
// Return value of -1 means 'pos' is already at the end of the 'format' string.
// Otherwise, return value is the int value of the next character.
//
internal static int ParseNextChar(ReadOnlySpan<char> format, int pos)
{
if (pos >= format.Length - 1)
{
return (-1);
}
return ((int)format[pos + 1]);
}
//
// IsUseGenitiveForm
//
// Actions: Check the format to see if we should use genitive month in the formatting.
// Starting at the position (index) in the (format) string, look back and look ahead to
// see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use
// genitive form. Genitive form is not used if there is more than two "d".
// Arguments:
// format The format string to be scanned.
// index Where we should start the scanning. This is generally where "M" starts.
// tokenLen The len of the current pattern character. This indicates how many "M" that we have.
// patternToMatch The pattern that we want to search. This generally uses "d"
//
private static bool IsUseGenitiveForm(ReadOnlySpan<char> format, int index, int tokenLen, char patternToMatch)
{
int i;
int repeat = 0;
//
// Look back to see if we can find "d" or "ddd"
//
// Find first "d".
for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ };
if (i >= 0)
{
// Find a "d", so look back to see how many "d" that we can find.
while (--i >= 0 && format[i] == patternToMatch)
{
repeat++;
}
//
// repeat == 0 means that we have one (patternToMatch)
// repeat == 1 means that we have two (patternToMatch)
//
if (repeat <= 1)
{
return (true);
}
// Note that we can't just stop here. We may find "ddd" while looking back, and we have to look
// ahead to see if there is "d" or "dd".
}
//
// If we can't find "d" or "dd" by looking back, try look ahead.
//
// Find first "d"
for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ };
if (i < format.Length)
{
repeat = 0;
// Find a "d", so contine the walk to see how may "d" that we can find.
while (++i < format.Length && format[i] == patternToMatch)
{
repeat++;
}
//
// repeat == 0 means that we have one (patternToMatch)
// repeat == 1 means that we have two (patternToMatch)
//
if (repeat <= 1)
{
return (true);
}
}
return (false);
}
//
// FormatCustomized
//
// Actions: Format the DateTime instance using the specified format.
//
private static StringBuilder FormatCustomized(
DateTime dateTime, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset, StringBuilder result)
{
Calendar cal = dtfi.Calendar;
bool resultBuilderIsPooled = false;
if (result == null)
{
resultBuilderIsPooled = true;
result = StringBuilderCache.Acquire();
}
// This is a flag to indicate if we are format the dates using Hebrew calendar.
bool isHebrewCalendar = (cal.ID == CalendarId.HEBREW);
// This is a flag to indicate if we are formating hour/minute/second only.
bool bTimeOnly = true;
int i = 0;
int tokenLen, hour12;
while (i < format.Length)
{
char ch = format[i];
int nextChar;
switch (ch)
{
case 'g':
tokenLen = ParseRepeatPattern(format, i, ch);
result.Append(dtfi.GetEraName(cal.GetEra(dateTime)));
break;
case 'h':
tokenLen = ParseRepeatPattern(format, i, ch);
hour12 = dateTime.Hour % 12;
if (hour12 == 0)
{
hour12 = 12;
}
FormatDigits(result, hour12, tokenLen);
break;
case 'H':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Hour, tokenLen);
break;
case 'm':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Minute, tokenLen);
break;
case 's':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatDigits(result, dateTime.Second, tokenLen);
break;
case 'f':
case 'F':
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen <= MaxSecondsFractionDigits)
{
long fraction = (dateTime.Ticks % Calendar.TicksPerSecond);
fraction = fraction / (long)Math.Pow(10, 7 - tokenLen);
if (ch == 'f')
{
result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
}
else
{
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
if (fraction % 10 == 0)
{
fraction = fraction / 10;
effectiveDigits--;
}
else
{
break;
}
}
if (effectiveDigits > 0)
{
result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
else
{
// No fraction to emit, so see if we should remove decimal also.
if (result.Length > 0 && result[result.Length - 1] == '.')
{
result.Remove(result.Length - 1, 1);
}
}
}
}
else
{
if (resultBuilderIsPooled)
{
StringBuilderCache.Release(result);
}
throw new FormatException(SR.Format_InvalidString);
}
break;
case 't':
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen == 1)
{
if (dateTime.Hour < 12)
{
if (dtfi.AMDesignator.Length >= 1)
{
result.Append(dtfi.AMDesignator[0]);
}
}
else
{
if (dtfi.PMDesignator.Length >= 1)
{
result.Append(dtfi.PMDesignator[0]);
}
}
}
else
{
result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator));
}
break;
case 'd':
//
// tokenLen == 1 : Day of month as digits with no leading zero.
// tokenLen == 2 : Day of month as digits with leading zero for single-digit months.
// tokenLen == 3 : Day of week as a three-leter abbreviation.
// tokenLen >= 4 : Day of week as its full name.
//
tokenLen = ParseRepeatPattern(format, i, ch);
if (tokenLen <= 2)
{
int day = cal.GetDayOfMonth(dateTime);
if (isHebrewCalendar)
{
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, day);
}
else
{
FormatDigits(result, day, tokenLen);
}
}
else
{
int dayOfWeek = (int)cal.GetDayOfWeek(dateTime);
result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi));
}
bTimeOnly = false;
break;
case 'M':
//
// tokenLen == 1 : Month as digits with no leading zero.
// tokenLen == 2 : Month as digits with leading zero for single-digit months.
// tokenLen == 3 : Month as a three-letter abbreviation.
// tokenLen >= 4 : Month as its full name.
//
tokenLen = ParseRepeatPattern(format, i, ch);
int month = cal.GetMonth(dateTime);
if (tokenLen <= 2)
{
if (isHebrewCalendar)
{
// For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
HebrewFormatDigits(result, month);
}
else
{
FormatDigits(result, month, tokenLen);
}
}
else
{
if (isHebrewCalendar)
{
result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi));
}
else
{
if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4)
{
result.Append(
dtfi.internalGetMonthName(
month,
IsUseGenitiveForm(format, i, tokenLen, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular,
false));
}
else
{
result.Append(FormatMonth(month, tokenLen, dtfi));
}
}
}
bTimeOnly = false;
break;
case 'y':
// Notes about OS behavior:
// y: Always print (year % 100). No leading zero.
// yy: Always print (year % 100) with leading zero.
// yyy/yyyy/yyyyy/... : Print year value. No leading zero.
int year = cal.GetYear(dateTime);
tokenLen = ParseRepeatPattern(format, i, ch);
if (dtfi.HasForceTwoDigitYears)
{
FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2);
}
else if (cal.ID == CalendarId.HEBREW)
{
HebrewFormatDigits(result, year);
}
else
{
if (tokenLen <= 2)
{
FormatDigits(result, year % 100, tokenLen);
}
else
{
String fmtPattern = "D" + tokenLen.ToString();
result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture));
}
}
bTimeOnly = false;
break;
case 'z':
tokenLen = ParseRepeatPattern(format, i, ch);
FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result);
break;
case 'K':
tokenLen = 1;
FormatCustomizedRoundripTimeZone(dateTime, offset, result);
break;
case ':':
result.Append(dtfi.TimeSeparator);
tokenLen = 1;
break;
case '/':
result.Append(dtfi.DateSeparator);
tokenLen = 1;
break;
case '\'':
case '\"':
tokenLen = ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
// For example, format string "%d" will print day of month
// without leading zero. Most of the cases, "%" can be ignored.
nextChar = ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
if (nextChar >= 0 && nextChar != '%')
{
char nextCharChar = (char)nextChar;
StringBuilder origStringBuilder = FormatCustomized(dateTime, ReadOnlySpan<char>.DangerousCreate(null, ref nextCharChar, 1), dtfi, offset, result);
Debug.Assert(ReferenceEquals(origStringBuilder, result));
tokenLen = 2;
}
else
{
//
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
if (resultBuilderIsPooled)
{
StringBuilderCache.Release(result);
}
throw new FormatException(SR.Format_InvalidString);
}
break;
case '\\':
// Escaped character. Can be used to insert character into the format string.
// For exmple, "\d" will insert the character 'd' into the string.
//
// NOTENOTE : we can remove this format character if we enforce the enforced quote
// character rule.
// That is, we ask everyone to use single quote or double quote to insert characters,
// then we can remove this character.
//
nextChar = ParseNextChar(format, i);
if (nextChar >= 0)
{
result.Append(((char)nextChar));
tokenLen = 2;
}
else
{
//
// This means that '\' is at the end of the formatting string.
//
if (resultBuilderIsPooled)
{
StringBuilderCache.Release(result);
}
throw new FormatException(SR.Format_InvalidString);
}
break;
default:
// NOTENOTE : we can remove this rule if we enforce the enforced quote
// character rule.
// That is, if we ask everyone to use single quote or double quote to insert characters,
// then we can remove this default block.
result.Append(ch);
tokenLen = 1;
break;
}
i += tokenLen;
}
return result;
}
// output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30"
private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, ReadOnlySpan<char> format, Int32 tokenLen, Boolean timeOnly, StringBuilder result)
{
// See if the instance already has an offset
Boolean dateTimeFormat = (offset == NullOffset);
if (dateTimeFormat)
{
// No offset. The instance is a DateTime and the output should be the local time zone
if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay)
{
// For time only format and a time only input, the time offset on 0001/01/01 is less
// accurate than the system's current offset because of daylight saving time.
offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else if (dateTime.Kind == DateTimeKind.Utc)
{
offset = TimeSpan.Zero;
}
else
{
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
}
if (offset >= TimeSpan.Zero)
{
result.Append('+');
}
else
{
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
}
if (tokenLen <= 1)
{
// 'z' format e.g "-7"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
}
else
{
// 'zz' or longer format e.g "-07"
result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
if (tokenLen >= 3)
{
// 'zzz*' or longer format e.g "-07:30"
result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
}
}
}
// output the 'K' format, which is for round-tripping the data
private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result)
{
// The objective of this format is to round trip the data in the type
// For DateTime it should round-trip the Kind value and preserve the time zone.
// DateTimeOffset instance, it should do so by using the internal time zone.
if (offset == NullOffset)
{
// source is a date time, so behavior depends on the kind.
switch (dateTime.Kind)
{
case DateTimeKind.Local:
// This should output the local offset, e.g. "-07:30"
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
// fall through to shared time zone output code
break;
case DateTimeKind.Utc:
// The 'Z' constant is a marker for a UTC date
result.Append("Z");
return;
default:
// If the kind is unspecified, we output nothing here
return;
}
}
if (offset >= TimeSpan.Zero)
{
result.Append('+');
}
else
{
result.Append('-');
// get a positive offset, so that you don't need a separate code path for the negative numbers.
offset = offset.Negate();
}
AppendNumber(result, offset.Hours, 2);
result.Append(':');
AppendNumber(result, offset.Minutes, 2);
}
internal static String GetRealFormat(ReadOnlySpan<char> format, DateTimeFormatInfo dtfi)
{
String realFormat = null;
switch (format[0])
{
case 'd': // Short Date
realFormat = dtfi.ShortDatePattern;
break;
case 'D': // Long Date
realFormat = dtfi.LongDatePattern;
break;
case 'f': // Full (long date + short time)
realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern;
break;
case 'F': // Full (long date + long time)
realFormat = dtfi.FullDateTimePattern;
break;
case 'g': // General (short date + short time)
realFormat = dtfi.GeneralShortTimePattern;
break;
case 'G': // General (short date + long time)
realFormat = dtfi.GeneralLongTimePattern;
break;
case 'm':
case 'M': // Month/Day Date
realFormat = dtfi.MonthDayPattern;
break;
case 'o':
case 'O':
realFormat = RoundtripFormat;
break;
case 'r':
case 'R': // RFC 1123 Standard
realFormat = dtfi.RFC1123Pattern;
break;
case 's': // Sortable without Time Zone Info
realFormat = dtfi.SortableDateTimePattern;
break;
case 't': // Short Time
realFormat = dtfi.ShortTimePattern;
break;
case 'T': // Long Time
realFormat = dtfi.LongTimePattern;
break;
case 'u': // Universal with Sortable format
realFormat = dtfi.UniversalSortableDateTimePattern;
break;
case 'U': // Universal with Full (long date + long time) format
realFormat = dtfi.FullDateTimePattern;
break;
case 'y':
case 'Y': // Year/Month Date
realFormat = dtfi.YearMonthPattern;
break;
default:
throw new FormatException(SR.Format_InvalidString);
}
return (realFormat);
}
// Expand a pre-defined format string (like "D" for long date) to the real format that
// we are going to use in the date time parsing.
// This method also convert the dateTime if necessary (e.g. when the format is in Universal time),
// and change dtfi if necessary (e.g. when the format should use invariant culture).
//
private static String ExpandPredefinedFormat(ReadOnlySpan<char> format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset)
{
switch (format[0])
{
case 'o':
case 'O': // Round trip format
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'r':
case 'R': // RFC 1123 Standard
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 's': // Sortable without Time Zone Info
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'u': // Universal time in sortable format.
if (offset != NullOffset)
{
// Convert to UTC invariants mean this will be in range
dateTime = dateTime - offset;
}
else if (dateTime.Kind == DateTimeKind.Local)
{
InvalidFormatForLocal(format, dateTime);
}
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
case 'U': // Universal time in culture dependent format.
if (offset != NullOffset)
{
// This format is not supported by DateTimeOffset
throw new FormatException(SR.Format_InvalidString);
}
// Universal time is always in Greogrian calendar.
//
// Change the Calendar to be Gregorian Calendar.
//
dtfi = (DateTimeFormatInfo)dtfi.Clone();
if (dtfi.Calendar.GetType() != typeof(GregorianCalendar))
{
dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
}
dateTime = dateTime.ToUniversalTime();
break;
}
return GetRealFormat(format, dtfi);
}
internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi)
{
return Format(dateTime, format, dtfi, NullOffset);
}
internal static string Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) =>
StringBuilderCache.GetStringAndRelease(FormatStringBuilder(dateTime, format, dtfi, offset));
internal static bool TryFormat(DateTime dateTime, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi) =>
TryFormat(dateTime, destination, out charsWritten, format, dtfi, NullOffset);
internal static bool TryFormat(DateTime dateTime, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset)
{
StringBuilder sb = FormatStringBuilder(dateTime, format, dtfi, offset);
bool success = sb.Length <= destination.Length;
if (success)
{
sb.CopyTo(0, destination, sb.Length);
charsWritten = sb.Length;
}
else
{
charsWritten = 0;
}
StringBuilderCache.Release(sb);
return success;
}
internal static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan<char> format, DateTimeFormatInfo dtfi, TimeSpan offset)
{
Debug.Assert(dtfi != null);
if (format.Length == 0)
{
Boolean timeOnlySpecialCase = false;
if (dateTime.Ticks < Calendar.TicksPerDay)
{
// If the time is less than 1 day, consider it as time of day.
// Just print out the short time format.
//
// This is a workaround for VB, since they use ticks less then one day to be
// time of day. In cultures which use calendar other than Gregorian calendar, these
// alternative calendar may not support ticks less than a day.
// For example, Japanese calendar only supports date after 1868/9/8.
// This will pose a problem when people in VB get the time of day, and use it
// to call ToString(), which will use the general format (short date + long time).
// Since Japanese calendar does not support Gregorian year 0001, an exception will be
// thrown when we try to get the Japanese year for Gregorian year 0001.
// Therefore, the workaround allows them to call ToString() for time of day from a DateTime by
// formatting as ISO 8601 format.
switch (dtfi.Calendar.ID)
{
case CalendarId.JAPAN:
case CalendarId.TAIWAN:
case CalendarId.HIJRI:
case CalendarId.HEBREW:
case CalendarId.JULIAN:
case CalendarId.UMALQURA:
case CalendarId.PERSIAN:
timeOnlySpecialCase = true;
dtfi = DateTimeFormatInfo.InvariantInfo;
break;
}
}
if (offset == NullOffset)
{
// Default DateTime.ToString case.
format = timeOnlySpecialCase ? "s" : "G";
}
else
{
// Default DateTimeOffset.ToString case.
format = timeOnlySpecialCase ? RoundtripDateTimeUnfixed : dtfi.DateTimeOffsetPattern;
}
}
if (format.Length == 1)
{
switch (format[0])
{
case 'O':
case 'o':
return FastFormatRoundtrip(dateTime, offset);
case 'R':
case 'r':
return FastFormatRfc1123(dateTime, offset, dtfi);
}
format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset);
}
return FormatCustomized(dateTime, format, dtfi, offset, result: null);
}
internal static StringBuilder FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi)
{
// ddd, dd MMM yyyy HH:mm:ss GMT
const int Rfc1123FormatLength = 29;
StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength);
if (offset != NullOffset)
{
// Convert to UTC invariants
dateTime = dateTime - offset;
}
dateTime.GetDatePart(out int year, out int month, out int day);
result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]);
result.Append(',');
result.Append(' ');
AppendNumber(result, day, 2);
result.Append(' ');
result.Append(InvariantAbbreviatedMonthNames[month - 1]);
result.Append(' ');
AppendNumber(result, year, 4);
result.Append(' ');
AppendHHmmssTimeOfDay(result, dateTime);
result.Append(' ');
result.Append(Gmt);
return result;
}
internal static StringBuilder FastFormatRoundtrip(DateTime dateTime, TimeSpan offset)
{
// yyyy-MM-ddTHH:mm:ss.fffffffK
const int roundTripFormatLength = 28;
StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength);
dateTime.GetDatePart(out int year, out int month, out int day);
AppendNumber(result, year, 4);
result.Append('-');
AppendNumber(result, month, 2);
result.Append('-');
AppendNumber(result, day, 2);
result.Append('T');
AppendHHmmssTimeOfDay(result, dateTime);
result.Append('.');
long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond;
AppendNumber(result, fraction, 7);
FormatCustomizedRoundripTimeZone(dateTime, offset, result);
return result;
}
private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime)
{
// HH:mm:ss
AppendNumber(result, dateTime.Hour, 2);
result.Append(':');
AppendNumber(result, dateTime.Minute, 2);
result.Append(':');
AppendNumber(result, dateTime.Second, 2);
}
internal static void AppendNumber(StringBuilder builder, long val, int digits)
{
for (int i = 0; i < digits; i++)
{
builder.Append('0');
}
int index = 1;
while (val > 0 && index <= digits)
{
builder[builder.Length - index] = (char)('0' + (val % 10));
val = val / 10;
index++;
}
Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
}
internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
{
Debug.Assert(dtfi != null);
String[] allFormats = null;
String[] results = null;
switch (format)
{
case 'd':
case 'D':
case 'f':
case 'F':
case 'g':
case 'G':
case 'm':
case 'M':
case 't':
case 'T':
case 'y':
case 'Y':
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(dateTime, allFormats[i], dtfi);
}
break;
case 'U':
DateTime universalTime = dateTime.ToUniversalTime();
allFormats = dtfi.GetAllDateTimePatterns(format);
results = new String[allFormats.Length];
for (int i = 0; i < allFormats.Length; i++)
{
results[i] = Format(universalTime, allFormats[i], dtfi);
}
break;
//
// The following ones are special cases because these patterns are read-only in
// DateTimeFormatInfo.
//
case 'r':
case 'R':
case 'o':
case 'O':
case 's':
case 'u':
results = new String[] { Format(dateTime, new String(format, 1), dtfi) };
break;
default:
throw new FormatException(SR.Format_InvalidString);
}
return (results);
}
internal static String[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi)
{
List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE);
for (int i = 0; i < allStandardFormats.Length; i++)
{
String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi);
for (int j = 0; j < strings.Length; j++)
{
results.Add(strings[j]);
}
}
String[] value = new String[results.Count];
results.CopyTo(0, value, 0, results.Count);
return (value);
}
// This is a placeholder for an MDA to detect when the user is using a
// local DateTime with a format that will be interpreted as UTC.
internal static void InvalidFormatForLocal(ReadOnlySpan<char> format, DateTime dateTime)
{
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
using NSubstitute;
using Ploeh.AutoFixture.Xunit2;
using Xunit;
namespace MicroServiceFabric.Bootstrap.StatefulServices.Data.Tests
{
public sealed class LazyReliableQueueTests
{
[Fact]
public void ctor_WrappedInstanceRequired()
{
Assert.Throws<ArgumentNullException>(
"wrappedInstance",
() => new LazyReliableQueue<object>(null));
}
[Theory]
[AutoData]
public void Name_ReturnsWrappedInstanceName(Uri expectedName)
{
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.Name
.Returns(expectedName);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
lazyReliableQueue.Name
.Should()
.Be(wrappedInstance.Name);
}
[Theory]
[AutoData]
public async Task GetCountAsync_ReturnsWrappedInstanceGetCount(long expectedCount)
{
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.GetCountAsync(transaction)
.Returns(expectedCount);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var count = await lazyReliableQueue.GetCountAsync(transaction).ConfigureAwait(false);
count
.Should()
.Be(count);
}
[Fact]
public async Task ClearAsync_ClearsWrappedInstance()
{
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
await lazyReliableQueue.ClearAsync().ConfigureAwait(false);
await wrappedInstance
.Received()
.ClearAsync().ConfigureAwait(false);
}
[Fact]
public async Task EnqueueAsync_Transaction_Item_EnqueuesOnWrappedInstance()
{
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var item = Substitute.For<object>();
await lazyReliableQueue.EnqueueAsync(transaction, item).ConfigureAwait(false);
await wrappedInstance
.Received()
.EnqueueAsync(transaction, item).ConfigureAwait(false);
}
[Theory]
[AutoData]
public async Task EnqueueAsync_Transaction_Item_Timeout_CancellationToken_EnqueuesOnWrappedInstance(
TimeSpan timeout, CancellationToken cancellationToken)
{
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var item = Substitute.For<object>();
await lazyReliableQueue.EnqueueAsync(transaction, item, timeout, cancellationToken).ConfigureAwait(false);
await wrappedInstance
.Received()
.EnqueueAsync(transaction, item, timeout, cancellationToken).ConfigureAwait(false);
}
[Fact]
public async Task TryDequeueAsync_Transaction_TriesDequeuesFromWrappedInstance()
{
var expectedValue = Substitute.For<object>();
var expectedResponse = new ConditionalValue<object>(true, expectedValue);
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.TryDequeueAsync(transaction)
.Returns(expectedResponse);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var response = await lazyReliableQueue.TryDequeueAsync(transaction).ConfigureAwait(false);
response.Value
.Should()
.Be(expectedValue);
}
[Theory]
[AutoData]
public async Task TryDequeueAsync_Transaction_Timeout_CancellationToken_TriesDequeueFromWrappedInstance(
TimeSpan timeout, CancellationToken cancellationToken)
{
var expectedValue = Substitute.For<object>();
var expectedResponse = new ConditionalValue<object>(true, expectedValue);
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.TryDequeueAsync(transaction, timeout, cancellationToken)
.Returns(expectedResponse);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var response =
await lazyReliableQueue.TryDequeueAsync(transaction, timeout, cancellationToken).ConfigureAwait(false);
response.Value
.Should()
.Be(expectedValue);
}
[Fact]
public async Task TryPeekAsync_Transaction_TriesPeekOnWrappedInstance()
{
var expectedValue = Substitute.For<object>();
var expectedResponse = new ConditionalValue<object>(true, expectedValue);
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.TryPeekAsync(transaction)
.Returns(expectedResponse);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var response = await lazyReliableQueue.TryPeekAsync(transaction).ConfigureAwait(false);
response.Value
.Should()
.Be(expectedValue);
}
[Theory]
[AutoData]
public async Task TryPeekAsync_Transaction_Timeout_CancellationToken_TriesPeekOnWrappedInstance(
TimeSpan timeout, CancellationToken cancellationToken)
{
var expectedValue = Substitute.For<object>();
var expectedResponse = new ConditionalValue<object>(true, expectedValue);
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.TryPeekAsync(transaction, timeout, cancellationToken)
.Returns(expectedResponse);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var response =
await lazyReliableQueue.TryPeekAsync(transaction, timeout, cancellationToken).ConfigureAwait(false);
response.Value
.Should()
.Be(expectedValue);
}
[Theory]
[InlineData(LockMode.Default)]
[InlineData(LockMode.Update)]
public async Task TryPeekAsync_Transaction_LockMode_TriesPeekOnWrappedInstance(LockMode lockMode)
{
var expectedValue = Substitute.For<object>();
var expectedResponse = new ConditionalValue<object>(true, expectedValue);
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.TryPeekAsync(transaction, lockMode)
.Returns(expectedResponse);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var response = await lazyReliableQueue.TryPeekAsync(transaction, lockMode).ConfigureAwait(false);
response.Value
.Should()
.Be(expectedValue);
}
[Theory]
[AutoData]
public async Task TryPeekAsync_Transaction_LockMode_Timeout_CancellationToken_TriesPeekOnWrappedInstance(
LockMode lockMode, TimeSpan timeout, CancellationToken cancellationToken)
{
var expectedValue = Substitute.For<object>();
var expectedResponse = new ConditionalValue<object>(true, expectedValue);
var transaction = Substitute.For<ITransaction>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.TryPeekAsync(transaction, lockMode, timeout, cancellationToken)
.Returns(expectedResponse);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var response =
await
lazyReliableQueue.TryPeekAsync(transaction, lockMode, timeout, cancellationToken)
.ConfigureAwait(false);
response.Value
.Should()
.Be(expectedValue);
}
[Fact]
public async Task CreateEnumerableAsync_ReturnsCreateEnumerableOnWrappedInstance()
{
var transaction = Substitute.For<ITransaction>();
var expectedEnumerable = Substitute.For<IAsyncEnumerable<object>>();
var wrappedInstance = Substitute.For<IReliableQueue<object>>();
wrappedInstance
.CreateEnumerableAsync(transaction)
.Returns(expectedEnumerable);
var lazyReliableQueue = CreateLazyReliableQueue(wrappedInstance);
var enumerable = await lazyReliableQueue.CreateEnumerableAsync(transaction).ConfigureAwait(false);
enumerable
.Should()
.Be(expectedEnumerable);
}
private static IReliableQueue<T> CreateLazyReliableQueue<T>(IReliableQueue<T> wrappedInstance)
{
return new LazyReliableQueue<T>(() => wrappedInstance);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.IO;
using System.Threading;
/**
* Class that converts BitmapData into a valid JPEG
*/
public class JPGEncoder
{
/**
* This is an AS3 class--just emulated the parts the encoder uses
*/
private class ByteArray
{
private MemoryStream stream;
private BinaryWriter writer;
public ByteArray()
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
}
/**
* Function from AS3--add a byte to our stream
*/
public void WriteByte( byte value )
{
writer.Write(value);
}
/**
* Spit back all bytes--to either pass via WWW or save to disk
*/
public byte[] GetAllBytes()
{
byte[] buffer = new byte[stream.Length];
stream.Position = 0;
stream.Read(buffer, 0, buffer.Length);
return buffer;
}
}
private struct BitString
{
public int length;
public int value;
}
/**
* Another flash class--emulating the stuff the encoder uses
*/
private class BitmapData
{
public int height;
public int width;
private Color32[] pixels;
/**
* Pull all of our pixels off the texture (Unity stuff isn't thread safe, and this is faster)
*/
public BitmapData ( Texture2D texture )
{
this.height = texture.height;
this.width = texture.width;
pixels = texture.GetPixels32();
}
/**
* Mimic the flash function
*/
public Color32 GetPixelColor( int x, int y )
{
x = Mathf.Clamp(x, 0, width - 1);
y = Mathf.Clamp(y, 0, height - 1);
return pixels[y * width + x];
}
}
// Static table initialization
private int[] ZigZag = new int[]{
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
};
private int[] YTable = new int[64];
private int[] UVTable = new int[64];
private float[] fdtbl_Y = new float[64];
private float[] fdtbl_UV = new float[64];
private void InitQuantTables ( int sf ){
int i;
float t;
int[] YQT = new int[]{
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
};
for (i = 0; i < 64; i++)
{
t = Mathf.Floor((YQT[i]*sf+50)/100);
t = Mathf.Clamp(t, 1, 255);
YTable[ZigZag[i]] = Mathf.RoundToInt( t );
}
int[] UVQT = new int[]{
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
};
for (i = 0; i < 64; i++)
{
t = Mathf.Floor((UVQT[i] * sf + 50) / 100);
t = Mathf.Clamp(t, 1, 255);
UVTable[ZigZag[i]] = (int) t;
}
float[] aasf = new float[]
{
1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
1.0f, 0.785694958f, 0.541196100f, 0.275899379f
};
i = 0;
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++)
{
fdtbl_Y[i] = (1.0f / (YTable [ZigZag[i]] * aasf[row] * aasf[col] * 8.0f));
fdtbl_UV[i] = (1.0f / (UVTable[ZigZag[i]] * aasf[row] * aasf[col] * 8.0f));
i++;
}
}
}
private BitString[] YDC_HT;
private BitString[] UVDC_HT;
private BitString[] YAC_HT;
private BitString[] UVAC_HT;
private BitString[] ComputeHuffmanTbl ( byte[] nrcodes , byte[] std_table )
{
int codevalue = 0;
int pos_in_table = 0;
BitString[] HT = new BitString[16 * 16];
for (int k=1; k<=16; k++)
{
for (int j=1; j<=nrcodes[k]; j++)
{
HT[std_table[pos_in_table]] = new BitString();
HT[std_table[pos_in_table]].value = codevalue;
HT[std_table[pos_in_table]].length = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
private byte[] std_dc_luminance_nrcodes = new byte[]{0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0};
private byte[] std_dc_luminance_values = new byte[]{0,1,2,3,4,5,6,7,8,9,10,11};
private byte[] std_ac_luminance_nrcodes = new byte[]{0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d};
private byte[] std_ac_luminance_values = new byte[]{
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
};
private byte[] std_dc_chrominance_nrcodes = new byte[]{0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0};
private byte[] std_dc_chrominance_values = new byte[]{0,1,2,3,4,5,6,7,8,9,10,11};
private byte[] std_ac_chrominance_nrcodes = new byte[]{0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77};
private byte[] std_ac_chrominance_values = new byte[]{
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
};
private void InitHuffmanTbl ()
{
YDC_HT = ComputeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = ComputeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = ComputeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = ComputeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
private BitString[] bitcode = new BitString[65535];
private int[] category = new int[65535];
private void InitCategoryfloat ()
{
int nrlower = 1;
int nrupper = 2;
int nr;
BitString bs;
for (int cat=1; cat<=15; cat++)
{
//Positive numbers
for (nr=nrlower; nr<nrupper; nr++)
{
category[32767+nr] = cat;
bs = new BitString();
bs.length = cat;
bs.value = nr;
bitcode[32767+nr] = bs;
}
//Negative numbers
for (nr=-(nrupper-1); nr<=-nrlower; nr++)
{
category[32767+nr] = cat;
bs = new BitString();
bs.length = cat;
bs.value = nrupper-1+nr;
bitcode[32767+nr] = bs;
}
nrlower <<= 1;
nrupper <<= 1;
}
}
// IO functions
private uint bytenew = 0;
private int bytepos = 7;
private ByteArray byteout = new ByteArray();
/**
* Get the result
*/
public byte[] GetBytes (){
if(!isDone)
{
Debug.LogError("JPEGEncoder not complete, cannot get bytes!");
return null;
}
return byteout.GetAllBytes();
}
private void WriteBits ( BitString bs ){
int value = bs.value;
int posval = bs.length-1;
while ( posval >= 0 )
{
if ( (value & System.Convert.ToUInt32(1 << posval)) != 0 )
{
bytenew |= System.Convert.ToUInt32(1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0)
{
if (bytenew == 0xFF)
{
WriteByte(0xFF);
WriteByte(0);
}
else
{
WriteByte((byte)bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
private void WriteByte ( byte value )
{
byteout.WriteByte(value);
}
private void WriteWord ( int value )
{
WriteByte((byte) (( value >> 8) &0xFF) );
WriteByte((byte) (( value ) &0xFF) );
}
// DCT & quantization core
private float[] FDCTQuant ( float[] data , float[] fdtbl )
{
float tmp0; float tmp1; float tmp2; float tmp3; float tmp4;
float tmp5; float tmp6; float tmp7;
float tmp10; float tmp11; float tmp12; float tmp13;
float z1; float z2; float z3; float z4; float z5; float z11; float z13;
int i;
/* Pass 1: process rows. */
int dataOff=0;
for (i=0; i<8; i++) {
tmp0 = data[dataOff+0] + data[dataOff+7];
tmp7 = data[dataOff+0] - data[dataOff+7];
tmp1 = data[dataOff+1] + data[dataOff+6];
tmp6 = data[dataOff+1] - data[dataOff+6];
tmp2 = data[dataOff+2] + data[dataOff+5];
tmp5 = data[dataOff+2] - data[dataOff+5];
tmp3 = data[dataOff+3] + data[dataOff+4];
tmp4 = data[dataOff+3] - data[dataOff+4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
data[dataOff+0] = tmp10 + tmp11; /* phase 3 */
data[dataOff+4] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * 0.707106781f; /* c4 */
data[dataOff+2] = tmp13 + z1; /* phase 5 */
data[dataOff+6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * 0.382683433f; /* c6 */
z2 = 0.541196100f * tmp10 + z5; /* c2-c6 */
z4 = 1.306562965f * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * 0.707106781f; /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
data[dataOff+5] = z13 + z2; /* phase 6 */
data[dataOff+3] = z13 - z2;
data[dataOff+1] = z11 + z4;
data[dataOff+7] = z11 - z4;
dataOff += 8; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataOff = 0;
for (i=0; i<8; i++) {
tmp0 = data[dataOff+ 0] + data[dataOff+56];
tmp7 = data[dataOff+ 0] - data[dataOff+56];
tmp1 = data[dataOff+ 8] + data[dataOff+48];
tmp6 = data[dataOff+ 8] - data[dataOff+48];
tmp2 = data[dataOff+16] + data[dataOff+40];
tmp5 = data[dataOff+16] - data[dataOff+40];
tmp3 = data[dataOff+24] + data[dataOff+32];
tmp4 = data[dataOff+24] - data[dataOff+32];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
data[dataOff+ 0] = tmp10 + tmp11; /* phase 3 */
data[dataOff+32] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * 0.707106781f; /* c4 */
data[dataOff+16] = tmp13 + z1; /* phase 5 */
data[dataOff+48] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * 0.382683433f; /* c6 */
z2 = 0.541196100f * tmp10 + z5; /* c2-c6 */
z4 = 1.306562965f * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * 0.707106781f; /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
data[dataOff+40] = z13 + z2; /* phase 6 */
data[dataOff+24] = z13 - z2;
data[dataOff+ 8] = z11 + z4;
data[dataOff+56] = z11 - z4;
dataOff++; /* advance pointer to next column */
}
// Quantize/descale the coefficients
for (i=0; i<64; i++) {
// Apply the quantization and scaling factor & Round to nearest integer
data[i] = Mathf.Round((data[i]*fdtbl[i]));
}
return data;
}
// Chunk writing
private void WriteAPP0 ()
{
WriteWord(0xFFE0); // marker
WriteWord(16); // length
WriteByte(0x4A); // J
WriteByte(0x46); // F
WriteByte(0x49); // I
WriteByte(0x46); // F
WriteByte(0); // = "JFIF",'\0'
WriteByte(1); // versionhi
WriteByte(1); // versionlo
WriteByte(0); // xyunits
WriteWord(1); // xdensity
WriteWord(1); // ydensity
WriteByte(0); // thumbnwidth
WriteByte(0); // thumbnheight
}
private void WriteSOF0( int width , int height )
{
WriteWord(0xFFC0); // marker
WriteWord(17); // length, truecolor YUV JPG
WriteByte(8); // precision
WriteWord(height);
WriteWord(width);
WriteByte(3); // nrofcomponents
WriteByte(1); // IdY
WriteByte(0x11); // HVY
WriteByte(0); // QTY
WriteByte(2); // IdU
WriteByte(0x11); // HVU
WriteByte(1); // QTU
WriteByte(3); // IdV
WriteByte(0x11); // HVV
WriteByte(1); // QTV
}
private void WriteDQT()
{
WriteWord(0xFFDB); // marker
WriteWord(132); // length
WriteByte(0);
int i;
for (i=0; i<64; i++) {
WriteByte((byte)YTable[i]);
}
WriteByte(1);
for (i=0; i<64; i++) {
WriteByte((byte)UVTable[i]);
}
}
private void WriteDHT()
{
WriteWord(0xFFC4); // marker
WriteWord(0x01A2); // length
int i;
WriteByte(0); // HTYDCinfo
for (i=0; i<16; i++) {
WriteByte(std_dc_luminance_nrcodes[i+1]);
}
for (i=0; i<=11; i++) {
WriteByte(std_dc_luminance_values[i]);
}
WriteByte(0x10); // HTYACinfo
for (i=0; i<16; i++) {
WriteByte(std_ac_luminance_nrcodes[i+1]);
}
for (i=0; i<=161; i++) {
WriteByte(std_ac_luminance_values[i]);
}
WriteByte(1); // HTUDCinfo
for (i=0; i<16; i++) {
WriteByte(std_dc_chrominance_nrcodes[i+1]);
}
for (i=0; i<=11; i++) {
WriteByte(std_dc_chrominance_values[i]);
}
WriteByte(0x11); // HTUACinfo
for (i=0; i<16; i++) {
WriteByte(std_ac_chrominance_nrcodes[i+1]);
}
for (i=0; i<=161; i++) {
WriteByte(std_ac_chrominance_values[i]);
}
}
private void writeSOS(){
WriteWord(0xFFDA); // marker
WriteWord(12); // length
WriteByte(3); // nrofcomponents
WriteByte(1); // IdY
WriteByte(0); // HTY
WriteByte(2); // IdU
WriteByte(0x11); // HTU
WriteByte(3); // IdV
WriteByte(0x11); // HTV
WriteByte(0); // Ss
WriteByte(0x3f); // Se
WriteByte(0); // Bf
}
// Core processing
private int[] DU = new int[64];
private float ProcessDU( float[] CDU , float[] fdtbl , float DC , BitString[] HTDC , BitString[] HTAC )
{
BitString EOB = HTAC[0x00];
BitString M16zeroes = HTAC[0xF0];
int i;
float[] DU_DCT = FDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (i=0;i<64;i++)
{
DU[ZigZag[i]]= (int) DU_DCT[i];
}
int Diff = (int) ( DU[0] - DC );
DC = DU[0];
//Encode DC
if (Diff==0)
{
WriteBits(HTDC[0]); // Diff might be 0
}
else
{
WriteBits(HTDC[category[32767+Diff]]);
WriteBits(bitcode[32767+Diff]);
}
//Encode ACs
int end0pos = 63;
for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) { };
//end0pos = first element in reverse order !=0
if ( end0pos == 0)
{
WriteBits(EOB);
return DC;
}
i = 1;
while ( i <= end0pos )
{
int startpos = i;
for (; (DU[i]==0) && (i<=end0pos); i++) {}
int nrzeroes = i-startpos;
if ( nrzeroes >= 16 )
{
for (int nrmarker=1; nrmarker <= nrzeroes/16; nrmarker++)
{
WriteBits(M16zeroes);
}
nrzeroes = (nrzeroes&0xF);
}
WriteBits(HTAC[nrzeroes*16+category[32767+DU[i]]]);
WriteBits(bitcode[32767+DU[i]]);
i++;
}
if ( end0pos != 63 )
{
WriteBits(EOB);
}
return DC;
}
private float[] YDU = new float[64];
private float[] UDU = new float[64];
private float[] VDU = new float[64];
private void RGB2YUV( BitmapData image, int xpos, int ypos)
{
int pos = 0;
for (int y = 0; y < 8; y++)
{
for (int x = 0; x < 8; x++)
{
Color32 C = image.GetPixelColor(xpos+x, image.height - (ypos+y));
YDU[pos]=((( 0.29900f)*C.r +( 0.58700f)*C.g+( 0.11400f)*C.b))-128;
UDU[pos]=(((-0.16874f)*C.r +(-0.33126f)*C.g+( 0.50000f)*C.b));
VDU[pos]=((( 0.50000f)*C.r +(-0.41869f)*C.g+(-0.08131f)*C.b));
pos++;
}
}
}
/**
* Constructor for JPEGEncoder class
*
* @param quality The quality level between 1 and 100 that detrmines the
* level of compression used in the generated JPEG
* @langversion ActionScript 3.0f
* @playerversion Flash 9.0f
* @tiptext
*/
// public flag--other scripts must watch this to know when they can safely get data out
public bool isDone = false;
private BitmapData image;
private int sf = 0;
private string path;
private int cores = 0;
//Contructor that doesn't save the data to disk
public JPGEncoder( Texture2D texture, float quality) : this(texture, quality, "", false){ }
public JPGEncoder( Texture2D texture, float quality, bool blocking) : this(texture, quality, "", blocking){ }
public JPGEncoder( Texture2D texture, float quality, string path) : this(texture, quality, path, false){ }
public JPGEncoder( Texture2D texture, float quality, string path, bool blocking )
{
this.path = path;
// save out texture data to our own data structure
image = new BitmapData(texture);
quality = Mathf.Clamp(quality, 1, 100);
sf = (quality < 50) ? (int)(5000 / quality) : (int)(200 - quality*2);
cores = SystemInfo.processorCount;
Thread thread = new Thread(DoEncoding);
thread.Start();
if( blocking )
thread.Join();
}
/**
* Handle initialization, encoding and writing to disk
*/
private void DoEncoding()
{
isDone = false;
// Create tables -- technically we could only do this once for multiple encodes
InitHuffmanTbl();
InitCategoryfloat();
InitQuantTables(sf);
// Do actual encoding
Encode();
if( !string.IsNullOrEmpty(path) )
File.WriteAllBytes(path, GetBytes());
// signal that our data is ok to use now
isDone = true;
}
/**
* Created a JPEG image from the specified BitmapData
*
* @param image The BitmapData that will be converted into the JPEG format.
* @return a ByteArray representing the JPEG encoded image data.
* @langversion ActionScript 3.0f
* @playerversion Flash 9.0f
* @tiptext
*/
private void Encode()
{
// Initialize bit writer
byteout = new ByteArray();
bytenew=0;
bytepos=7;
// Add JPEG headers
WriteWord(0xFFD8); // SOI
WriteAPP0();
WriteDQT();
WriteSOF0(image.width,image.height);
WriteDHT();
writeSOS();
// Encode 8x8 macroblocks
float DCY=0;
float DCU=0;
float DCV=0;
bytenew=0;
bytepos=7;
for (int ypos = 0; ypos < image.height; ypos += 8 )
{
for (int xpos = 0; xpos < image.width; xpos += 8)
{
RGB2YUV(image, xpos, ypos);
DCY = ProcessDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = ProcessDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = ProcessDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
//If running on a single core system, then give some time to do other stuff
if( cores == 1 )
Thread.Sleep(0);
}
}
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 )
{
BitString fillbits = new BitString();
fillbits.length = bytepos+1;
fillbits.value = (1<<(bytepos+1))-1;
WriteBits(fillbits);
}
WriteWord(0xFFD9); //EOI
//Signal we are done
isDone = true;
}
}
/*
* Ported to Unity C# by Andreas Broager
*/
/*
* Ported to UnityScript by Matthew Wegner, Flashbang Studios
*
* Original code is from as3corelib, found here:
* http://code.google.com/p/as3corelib/source/browse/trunk/src/com/adobe/images/JPGEncoder.as
*
* Original copyright notice is below:
*/
/*
Copyright (c) 2008, Adobe Systems Incorporated
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 Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| |
using System;
using System.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 MyHelp.Web.Areas.HelpPage.ModelDescriptions;
using MyHelp.Web.Areas.HelpPage.Models;
namespace MyHelp.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified 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.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Clauses.ResultOperators;
using Remotion.Linq.Parsing;
using Revenj.DatabasePersistence.Postgres.QueryGeneration.QueryComposition;
namespace Revenj.DatabasePersistence.Postgres.QueryGeneration.Visitors
{
public class SelectGeneratorExpressionTreeVisitor : ThrowingExpressionTreeVisitor
{
public static void ProcessExpression(Expression linqExpression, MainQueryParts query, QueryModel queryModel)
{
var visitor =
new SelectGeneratorExpressionTreeVisitor(
query,
queryModel.ResultOperators.Any(it => it is AllResultOperator));
visitor.VisitExpression(linqExpression);
}
private readonly MainQueryParts Query;
private readonly bool IsSimple;
private readonly List<Expression> DataSources = new List<Expression>();
private SelectGeneratorExpressionTreeVisitor(MainQueryParts query, bool simple)
{
this.Query = query;
this.IsSimple = simple;
}
protected override Expression VisitQuerySourceReferenceExpression(QuerySourceReferenceExpression expression)
{
if (IsSimple)
{
var qs = expression.ReferencedQuerySource;
Query.AddSelectPart(qs, qs.ItemName, qs.ItemName, typeof(bool), (_, __, dr) => dr.GetBoolean(0));
}
else
CreateSelector(expression.ReferencedQuerySource);
return expression;
}
private void CreateSelector(IQuerySource qs)
{
var index = Query.CurrentSelectIndex;
if (qs.ItemType.IsGrouping())
{
var factoryKey = QuerySourceConverterFactory.CreateResult("Key", qs.ItemType.GetGenericArguments()[0], qs, Query);
var factoryValue = QuerySourceConverterFactory.Create(qs, Query);
var genericType = qs.ItemType.CreateGrouping();
if (Query.AddSelectPart(
qs,
"\"{0}\".\"Key\" AS \"{0}.Key\", \"{0}\".\"Values\" AS \"{0}\"".With(factoryValue.Name),
factoryValue.Name,
qs.ItemType,
(_, reader, dr) =>
{
var keyInstance = factoryKey.Instancer(dr.GetValue(index), reader);
object[] array;
if (dr.IsDBNull(index + 1))
array = new string[0];
else
{
var obj = dr.GetValue(index + 1);
var tr = obj as TextReader;
if (tr != null)
array = PostgresRecordConverter.ParseArray(tr.ReadToEnd());
else
array = PostgresRecordConverter.ParseArray(obj as string);
};
var valueInstances = array.Select(it => factoryValue.Instancer(it, reader));
return Activator.CreateInstance(genericType, keyInstance, valueInstances);
}))
Query.CurrentSelectIndex++;
}
else
{
var factory = QuerySourceConverterFactory.Create(qs, Query);
Query.AddSelectPart(
factory.QuerySource,
"\"{0}\"".With(factory.Name),
factory.Name,
factory.Type,
(_, reader, dr) => dr.IsDBNull(index) ? null : factory.Instancer(dr.GetValue(index), reader));
}
}
protected override Expression VisitNewExpression(NewExpression expression)
{
if (expression.CanReduce)
return expression.Reduce();
foreach (var arg in expression.Arguments)
VisitExpression(arg);
return Expression.New(expression.Constructor, expression.Arguments);
}
protected override Expression VisitMemberInitExpression(MemberInitExpression expression)
{
var newExpression = expression.NewExpression;
var newBindings = VisitMemberBindingList(expression.Bindings);
if (newExpression != expression.NewExpression || newBindings != expression.Bindings)
return Expression.MemberInit(newExpression, newBindings);
return Expression.New(newExpression.Constructor, newExpression.Arguments);
}
protected override ReadOnlyCollection<MemberBinding> VisitMemberBindingList(ReadOnlyCollection<MemberBinding> expressions)
{
return base.VisitMemberBindingList(expressions);
}
protected override MemberBinding VisitMemberAssignment(MemberAssignment memberAssigment)
{
if (memberAssigment.Expression.NodeType == ExpressionType.Constant)
return Expression.Bind(memberAssigment.Member, memberAssigment.Expression);
var expression = VisitExpression(memberAssigment.Expression);
return Expression.Bind(memberAssigment.Member, expression);
}
protected override Expression VisitBinaryExpression(BinaryExpression expression)
{
VisitExpression(expression.Left);
VisitExpression(expression.Right);
return expression;
}
protected override Expression VisitConstantExpression(ConstantExpression expression)
{
return expression;
}
protected override Expression VisitUnaryExpression(UnaryExpression expression)
{
VisitExpression(expression.Operand);
return expression;
}
protected override Expression VisitMemberExpression(MemberExpression expression)
{
VisitExpression(expression.Expression);
return expression;
}
protected override Expression VisitMethodCallExpression(MethodCallExpression expression)
{
VisitExpression(expression.Object);
foreach (var arg in expression.Arguments)
VisitExpression(arg);
return expression;
}
protected override Expression VisitConditionalExpression(ConditionalExpression expression)
{
VisitExpression(expression.Test);
VisitExpression(expression.IfTrue);
VisitExpression(expression.IfFalse);
return expression;
}
private readonly List<Expression> ProcessedExpressions = new List<Expression>();
protected override Expression VisitSubQueryExpression(SubQueryExpression expression)
{
if (ProcessedExpressions.Contains(expression))
return expression;
if (DataSources.Count == 0)
{
DataSources.Add(Query.MainFrom.FromExpression);
DataSources.AddRange(Query.Joins.Select(it => it.InnerSequence));
DataSources.AddRange(Query.AdditionalJoins.Select(it => it.FromExpression));
}
var model = expression.QueryModel;
if (model.BodyClauses.Count == 0
&& DataSources.Contains(model.MainFromClause.FromExpression))
return expression;
ProcessedExpressions.Add(expression);
foreach (var candidate in Query.ProjectionMatchers)
if (candidate.TryMatch(expression, Query, exp => VisitExpression(exp)))
return expression;
var subquery = SubqueryGeneratorQueryModelVisitor.ParseSubquery(expression.QueryModel, Query, true);
var cnt = Query.CurrentSelectIndex;
//TODO true or false
var sql = subquery.BuildSqlString(true);
var selector = model.SelectClause.Selector;
var projector = (IExecuteFunc)Activator.CreateInstance(typeof(GenericProjection<>).MakeGenericType(selector.Type), model);
var ssd = SelectSubqueryData.Create(Query, subquery);
if (subquery.ResultOperators.Any(it => it is FirstResultOperator))
{
Query.AddSelectPart(
expression.QueryModel.MainFromClause,
@"(SELECT ""{1}"" FROM ({2}) ""{1}"" LIMIT 1) AS ""{0}""".With(
"_first_or_default_" + cnt,
expression.QueryModel.MainFromClause.ItemName,
sql),
"_first_or_default_" + cnt,
expression.QueryModel.ResultTypeOverride,
(rom, reader, dr) =>
{
if (dr.IsDBNull(cnt))
return null;
var tuple = new[] { dr.GetValue(cnt).ToString() };
var result = ssd.ProcessRow(rom, reader, tuple);
return projector.Eval(result);
});
}
else
{
Query.AddSelectPart(
expression.QueryModel.MainFromClause,
@"(SELECT ARRAY_AGG(""{1}"") FROM ({2}) ""{1}"") AS ""{0}""".With(
"_subquery_" + cnt,
expression.QueryModel.MainFromClause.ItemName,
sql),
"_subquery_" + cnt,
expression.QueryModel.ResultTypeOverride,
(rom, reader, dr) =>
{
object[] array;
if (dr.IsDBNull(cnt))
array = new string[0];
else
{
var value = dr.GetValue(cnt);
if (value is string[])
array = value as string[];
else
{
var obj = dr.GetValue(cnt);
//TODO fix dead code usage
var tr = obj as TextReader;
if (tr != null)
array = PostgresRecordConverter.ParseArray(tr.ReadToEnd());
else
array = PostgresRecordConverter.ParseArray(obj as string);
}
}
var resultItems = new ResultObjectMapping[array.Length];
for (int i = 0; i < array.Length; i++)
resultItems[i] = ssd.ProcessRow(rom, reader, array[i]);
return projector.Process(resultItems);
});
}
return expression;
}
class GenericProjection<TOut> : IExecuteFunc
{
private readonly Func<ResultObjectMapping, TOut> Func;
public GenericProjection(QueryModel model)
{
Func = ProjectorBuildingExpressionTreeVisitor<TOut>.BuildProjector(model);
}
public IQueryable Process(ResultObjectMapping[] items)
{
var result = new TOut[items.Length];
for (int i = 0; i < items.Length; i++)
result[i] = Func(items[i]);
return Queryable.AsQueryable(result);
}
public object Eval(ResultObjectMapping item)
{
return Func(item);
}
}
interface IExecuteFunc
{
IQueryable Process(ResultObjectMapping[] items);
object Eval(ResultObjectMapping item);
}
// Called when a LINQ expression type is not handled above.
protected override Exception CreateUnhandledItemException<T>(T unhandledItem, string visitMethod)
{
string itemText = FormatUnhandledItem(unhandledItem);
var message = "The expression '{0}' (type: {1}) is not supported by this LINQ provider.".With(itemText, typeof(T));
return new NotSupportedException(message);
}
private string FormatUnhandledItem<T>(T unhandledItem)
{
var itemAsExpression = unhandledItem as Expression;
return itemAsExpression != null ? FormattingExpressionTreeVisitor.Format(itemAsExpression) : unhandledItem.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using Nez.Textures;
namespace Nez.Sprites
{
/// <summary>
/// SpriteAnimator handles the display and animation of a sprite
/// </summary>
public class SpriteAnimator : SpriteRenderer, IUpdatable
{
public enum LoopMode
{
/// <summary>
/// Play the sequence in a loop forever [A][B][C][A][B][C][A][B][C]...
/// </summary>
Loop,
/// <summary>
/// Play the sequence once [A][B][C] then pause and set time to 0 [A]
/// </summary>
Once,
/// <summary>
/// Plays back the animation once, [A][B][C]. When it reaches the end, it will keep playing the last frame and never stop playing
/// </summary>
ClampForever,
/// <summary>
/// Play the sequence in a ping pong loop forever [A][B][C][B][A][B][C][B]...
/// </summary>
PingPong,
/// <summary>
/// Play the sequence once forward then back to the start [A][B][C][B][A] then pause and set time to 0
/// </summary>
PingPongOnce
}
public enum State
{
None,
Running,
Paused,
Completed
}
/// <summary>
/// fired when an animation completes, includes the animation name;
/// </summary>
public event Action<string> OnAnimationCompletedEvent;
/// <summary>
/// animation playback speed
/// </summary>
public float Speed = 1;
/// <summary>
/// the current state of the animation
/// </summary>
public State AnimationState { get; private set; } = State.None;
/// <summary>
/// the current animation
/// </summary>
public SpriteAnimation CurrentAnimation { get; private set; }
/// <summary>
/// the name of the current animation
/// </summary>
public string CurrentAnimationName { get; private set; }
/// <summary>
/// index of the current frame in sprite array of the current animation
/// </summary>
public int CurrentFrame { get; set; }
/// <summary>
/// checks to see if the CurrentAnimation is running
/// </summary>
public bool IsRunning => AnimationState == State.Running;
/// <summary>
/// Provides access to list of available animations
/// </summary>
public Dictionary<string, SpriteAnimation> Animations { get { return _animations; } }
readonly Dictionary<string, SpriteAnimation> _animations = new Dictionary<string, SpriteAnimation>();
float _elapsedTime;
LoopMode _loopMode;
public SpriteAnimator()
{ }
public SpriteAnimator(Sprite sprite) => SetSprite(sprite);
public virtual void Update()
{
if (AnimationState != State.Running || CurrentAnimation == null)
return;
var animation = CurrentAnimation;
var secondsPerFrame = 1 / (animation.FrameRate * Speed);
var iterationDuration = secondsPerFrame * animation.Sprites.Length;
var pingPongIterationDuration = animation.Sprites.Length < 3 ? iterationDuration : secondsPerFrame * (animation.Sprites.Length * 2 - 2);
_elapsedTime += Time.DeltaTime;
var time = Math.Abs(_elapsedTime);
// Once and PingPongOnce reset back to Time = 0 once they complete
if (_loopMode == LoopMode.Once && time > iterationDuration ||
_loopMode == LoopMode.PingPongOnce && time > pingPongIterationDuration)
{
AnimationState = State.Completed;
_elapsedTime = 0;
CurrentFrame = 0;
Sprite = animation.Sprites[0];
OnAnimationCompletedEvent?.Invoke(CurrentAnimationName);
return;
}
if (_loopMode == LoopMode.ClampForever && time > iterationDuration)
{
AnimationState = State.Completed;
CurrentFrame = animation.Sprites.Length - 1;
Sprite = animation.Sprites[CurrentFrame];
OnAnimationCompletedEvent?.Invoke(CurrentAnimationName);
return;
}
// figure out which frame we are on
int i = Mathf.FloorToInt(time / secondsPerFrame);
int n = animation.Sprites.Length;
if (n > 2 && (_loopMode == LoopMode.PingPong || _loopMode == LoopMode.PingPongOnce))
{
// create a pingpong frame
int maxIndex = n - 1;
CurrentFrame = maxIndex - Math.Abs(maxIndex - i % (maxIndex * 2));
}
else
// create a looping frame
CurrentFrame = i % n;
Sprite = animation.Sprites[CurrentFrame];
}
/// <summary>
/// adds all the animations from the SpriteAtlas
/// </summary>
public SpriteAnimator AddAnimationsFromAtlas(SpriteAtlas atlas)
{
for (var i = 0; i < atlas.AnimationNames.Length; i++)
_animations.Add(atlas.AnimationNames[i], atlas.SpriteAnimations[i]);
return this;
}
/// <summary>
/// Adds a SpriteAnimation
/// </summary>
public SpriteAnimator AddAnimation(string name, SpriteAnimation animation)
{
// if we have no sprite use the first frame we find
if (Sprite == null && animation.Sprites.Length > 0)
SetSprite(animation.Sprites[0]);
_animations[name] = animation;
return this;
}
public SpriteAnimator AddAnimation(string name, Sprite[] sprites, float fps = 10) => AddAnimation(name, fps, sprites);
public SpriteAnimator AddAnimation(string name, float fps, params Sprite[] sprites)
{
AddAnimation(name, new SpriteAnimation(sprites, fps));
return this;
}
#region Playback
/// <summary>
/// plays the animation with the given name. If no loopMode is specified it is defaults to Loop
/// </summary>
public void Play(string name, LoopMode? loopMode = null)
{
CurrentAnimation = _animations[name];
CurrentAnimationName = name;
CurrentFrame = 0;
AnimationState = State.Running;
Sprite = CurrentAnimation.Sprites[0];
_elapsedTime = 0;
_loopMode = loopMode ?? LoopMode.Loop;
}
/// <summary>
/// checks to see if the animation is playing (i.e. the animation is active. it may still be in the paused state)
/// </summary>
public bool IsAnimationActive(string name) => CurrentAnimation != null && CurrentAnimationName.Equals(name);
/// <summary>
/// pauses the animator
/// </summary>
public void Pause() => AnimationState = State.Paused;
/// <summary>
/// unpauses the animator
/// </summary>
public void UnPause() => AnimationState = State.Running;
/// <summary>
/// stops the current animation and nulls it out
/// </summary>
public void Stop()
{
CurrentAnimation = null;
CurrentAnimationName = null;
CurrentFrame = 0;
AnimationState = State.None;
}
#endregion
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics
{
public class ValueTupleTests : CompilingTestBase
{
[Fact]
public void TestWellKnownMembersForValueTuple()
{
var source = @"
namespace System
{
struct ValueTuple<T1>
{
public T1 Item1;
}
struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
}
struct ValueTuple<T1, T2, T3>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
}
struct ValueTuple<T1, T2, T3, T4>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
}
struct ValueTuple<T1, T2, T3, T4, T5>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
}
struct ValueTuple<T1, T2, T3, T4, T5, T6>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public T6 Item6;
}
struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public T6 Item6;
public T7 Item7;
}
struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
{
public T1 Item1;
public T2 Item2;
public T3 Item3;
public T4 Item4;
public T5 Item5;
public T6 Item6;
public T7 Item7;
public TRest Rest;
}
}";
var comp = CreateCompilationWithMscorlib(source);
Assert.Equal("T1 System.ValueTuple<T1>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__Item1).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item2).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2, T3>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2, T3>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item2).ToTestDisplayString());
Assert.Equal("T3 System.ValueTuple<T1, T2, T3>.Item3",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item3).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item2).ToTestDisplayString());
Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4>.Item3",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item3).ToTestDisplayString());
Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4>.Item4",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item4).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item2).ToTestDisplayString());
Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5>.Item3",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item3).ToTestDisplayString());
Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5>.Item4",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item4).ToTestDisplayString());
Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5>.Item5",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item5).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item2).ToTestDisplayString());
Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item3",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item3).ToTestDisplayString());
Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item4",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item4).ToTestDisplayString());
Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item5",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item5).ToTestDisplayString());
Assert.Equal("T6 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item6",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item6).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item2).ToTestDisplayString());
Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item3",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item3).ToTestDisplayString());
Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item4",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item4).ToTestDisplayString());
Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item5",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item5).ToTestDisplayString());
Assert.Equal("T6 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item6",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item6).ToTestDisplayString());
Assert.Equal("T7 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item7",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item7).ToTestDisplayString());
Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item1",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item1).ToTestDisplayString());
Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item2",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item2).ToTestDisplayString());
Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item3",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item3).ToTestDisplayString());
Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item4",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item4).ToTestDisplayString());
Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item5",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item5).ToTestDisplayString());
Assert.Equal("T6 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item6",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item6).ToTestDisplayString());
Assert.Equal("T7 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item7",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item7).ToTestDisplayString());
Assert.Equal("TRest System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Rest",
comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Rest).ToTestDisplayString());
}
[Fact]
public void TestMissingWellKnownMembersForValueTuple()
{
var comp = CreateCompilationWithMscorlib("");
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__Item1));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item2));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item2));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item3));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T4).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item2));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item3));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item4));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T5).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item2));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item3));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item4));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item5));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T6).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item2));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item3));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item4));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item6));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T7).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item2));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item3));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item4));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item6));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item7));
Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).IsErrorType());
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item1));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item2));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item3));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item4));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item6));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item7));
Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Rest));
}
}
}
| |
/* New BSD License
-------------------------------------------------------------------------------
Copyright (c) 2006-2012, EntitySpaces, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using Tiraggo.DynamicQuery;
using Tiraggo.Interfaces;
namespace Tiraggo.OracleClientProvider
{
class QueryBuilder
{
public static OracleCommand PrepareCommand(tgDataRequest request)
{
StandardProviderParameters std = new StandardProviderParameters();
std.cmd = new OracleCommand();
std.pindex = NextParamIndex(std.cmd);
std.request = request;
string sql = BuildQuery(std, request.DynamicQuery);
std.cmd.CommandText = sql;
return (OracleCommand)std.cmd;
}
protected static string BuildQuery(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
bool selectAll = (iQuery.InternalSelectColumns == null && !query.tg.CountAll);
bool paging = false;
if (query.tg.PageNumber.HasValue && query.tg.PageSize.HasValue)
paging = true;
string select = GetSelectStatement(std, query);
string from = GetFromStatement(std, query);
string join = GetJoinStatement(std, query);
string where = GetComparisonStatement(std, query, iQuery.InternalWhereItems, " WHERE ");
string groupBy = GetGroupByStatement(std, query);
string having = GetComparisonStatement(std, query, iQuery.InternalHavingItems, " HAVING ");
string orderBy = GetOrderByStatement(std, query);
string setOperation = GetSetOperationStatement(std, query);
string sql = String.Empty;
if (paging)
{
int begRow = ((query.tg.PageNumber.Value - 1) * query.tg.PageSize.Value) + 1;
int endRow = begRow + (query.tg.PageSize.Value - 1);
// The WITH statement
sql += "WITH \"withStatement\" AS (";
if (selectAll)
{
sql += "SELECT " +
Delimiters.TableOpen + query.tg.QuerySource + Delimiters.TableClose
+ ".*, ROW_NUMBER() OVER(" + orderBy + ") AS ESRN ";
}
else
{
sql += "SELECT " + select + ", ROW_NUMBER() OVER(" + orderBy + ") AS ESRN ";
}
sql += "FROM " + from + join + where + groupBy + ") ";
// The actual select
if (selectAll || join.Length > 0 || groupBy.Length > 0 || query.tg.Distinct)
{
sql += "SELECT " +
Delimiters.TableOpen + "withStatement" + Delimiters.TableClose
+ ".* FROM \"withStatement\" ";
}
else
{
sql += "SELECT " + select + " FROM \"withStatement\" ";
}
sql += "WHERE ESRN BETWEEN " + begRow + " AND " + endRow;
sql += " ORDER BY ESRN ASC";
}
else
{
sql += "SELECT " + select + " FROM " + from + join + where + setOperation + groupBy + having + orderBy;
}
return sql;
}
protected static string GetFromStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
string sql = String.Empty;
if (iQuery.InternalFromQuery == null)
{
sql = Shared.CreateFullName(std.request, query);
if (iQuery.JoinAlias != " ")
{
sql += " " + iQuery.JoinAlias;
}
}
else
{
IDynamicQuerySerializableInternal iSubQuery = iQuery.InternalFromQuery as IDynamicQuerySerializableInternal;
iSubQuery.IsInSubQuery = true;
sql += "(";
sql += BuildQuery(std, iQuery.InternalFromQuery);
sql += ")";
if (iSubQuery.SubQueryAlias != " ")
{
sql += " " + iSubQuery.SubQueryAlias;
}
iSubQuery.IsInSubQuery = false;
}
return sql;
}
protected static string GetSelectStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
string comma = String.Empty;
bool selectAll = true;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (query.tg.Distinct) sql += " DISTINCT ";
if (iQuery.InternalSelectColumns != null)
{
selectAll = false;
foreach (tgExpression expressionItem in iQuery.InternalSelectColumns)
{
if (expressionItem.Query != null)
{
IDynamicQuerySerializableInternal iSubQuery = expressionItem.Query as IDynamicQuerySerializableInternal;
sql += comma;
if (iSubQuery.SubQueryAlias == string.Empty)
{
sql += iSubQuery.JoinAlias + ".*";
}
else
{
iSubQuery.IsInSubQuery = true;
sql += " (" + BuildQuery(std, expressionItem.Query as tgDynamicQuerySerializable) + ") AS " + Delimiters.StringOpen + iSubQuery.SubQueryAlias + Delimiters.StringClose;
iSubQuery.IsInSubQuery = false;
}
comma = ",";
}
else
{
sql += comma;
string columnName = expressionItem.Column.Name;
if (columnName != null && columnName[0] == '<')
sql += columnName.Substring(1, columnName.Length - 2);
else
sql += GetExpressionColumn(std, query, expressionItem, false, true);
comma = ",";
}
}
sql += " ";
}
if (query.tg.CountAll)
{
selectAll = false;
sql += comma;
sql += "COUNT(*)";
if (query.tg.CountAllAlias != null)
{
// Need DBMS string delimiter here
sql += " AS " + Delimiters.StringOpen + query.tg.CountAllAlias + Delimiters.StringClose;
}
}
if (selectAll)
{
sql += "*";
}
return sql;
}
protected static string GetJoinStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalJoinItems != null)
{
foreach (tgJoinItem joinItem in iQuery.InternalJoinItems)
{
tgJoinItem.tgJoinItemData joinData = (tgJoinItem.tgJoinItemData)joinItem;
switch (joinData.JoinType)
{
case tgJoinType.InnerJoin:
sql += " INNER JOIN ";
break;
case tgJoinType.LeftJoin:
sql += " LEFT JOIN ";
break;
case tgJoinType.RightJoin:
sql += " RIGHT JOIN ";
break;
case tgJoinType.FullJoin:
sql += " FULL JOIN ";
break;
}
IDynamicQuerySerializableInternal iSubQuery = joinData.Query as IDynamicQuerySerializableInternal;
sql += Shared.CreateFullName(std.request, joinData.Query);
sql += " " + iSubQuery.JoinAlias + " ON ";
sql += GetComparisonStatement(std, query, joinData.WhereItems, String.Empty);
}
}
return sql;
}
protected static string GetComparisonStatement(StandardProviderParameters std, tgDynamicQuerySerializable query, List<tgComparison> items, string prefix)
{
string sql = String.Empty;
string comma = String.Empty;
bool first = true;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
//=======================================
// WHERE
//=======================================
if (items != null)
{
sql += prefix;
string compareTo = String.Empty;
foreach (tgComparison comparisonItem in items)
{
tgComparison.tgComparisonData comparisonData = (tgComparison.tgComparisonData)comparisonItem;
tgDynamicQuerySerializable subQuery = null;
bool requiresParam = true;
bool needsStringParameter = false;
std.needsStringParameter = false;
if (comparisonData.IsParenthesis)
{
if (comparisonData.Parenthesis == tgParenthesis.Open)
sql += "(";
else
sql += ")";
continue;
}
if (comparisonData.IsConjunction)
{
switch (comparisonData.Conjunction)
{
case tgConjunction.And: sql += " AND "; break;
case tgConjunction.Or: sql += " OR "; break;
case tgConjunction.AndNot: sql += " AND NOT "; break;
case tgConjunction.OrNot: sql += " OR NOT "; break;
}
continue;
}
Dictionary<string, OracleParameter> types = null;
if (comparisonData.Column.Query != null)
{
IDynamicQuerySerializableInternal iLocalQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
types = Cache.GetParameters(iLocalQuery.DataID, (tgProviderSpecificMetadata)iLocalQuery.ProviderMetadata, (tgColumnMetadataCollection)iLocalQuery.Columns);
}
if (comparisonData.IsLiteral)
{
if (comparisonData.Column.Name[0] == '<')
{
sql += comparisonData.Column.Name.Substring(1, comparisonData.Column.Name.Length - 2);
}
else
{
sql += comparisonData.Column.Name;
}
continue;
}
if (comparisonData.ComparisonColumn.Name == null)
{
subQuery = comparisonData.Value as tgDynamicQuerySerializable;
if (subQuery == null)
{
if (comparisonData.Column.Name != null)
{
IDynamicQuerySerializableInternal iColQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
tgColumnMetadataCollection columns = (tgColumnMetadataCollection)iColQuery.Columns;
compareTo = Delimiters.Param + columns[comparisonData.Column.Name].PropertyName + (++std.pindex).ToString();
}
else
{
compareTo = Delimiters.Param + "Expr" + (++std.pindex).ToString();
}
}
else
{
// It's a sub query
compareTo = GetSubquerySearchCondition(subQuery) + " (" + BuildQuery(std, subQuery) + ") ";
requiresParam = false;
}
}
else
{
compareTo = GetColumnName(comparisonData.ComparisonColumn);
requiresParam = false;
}
switch (comparisonData.Operand)
{
case tgComparisonOperand.Exists:
sql += " EXISTS" + compareTo;
break;
case tgComparisonOperand.NotExists:
sql += " NOT EXISTS" + compareTo;
break;
//-----------------------------------------------------------
// Comparison operators, left side vs right side
//-----------------------------------------------------------
case tgComparisonOperand.Equal:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " = " + compareTo;
else
sql += compareTo + " = " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.NotEqual:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " <> " + compareTo;
else
sql += compareTo + " <> " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.GreaterThan:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " > " + compareTo;
else
sql += compareTo + " > " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.LessThan:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " < " + compareTo;
else
sql += compareTo + " < " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.LessThanOrEqual:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " <= " + compareTo;
else
sql += compareTo + " <= " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.GreaterThanOrEqual:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " >= " + compareTo;
else
sql += compareTo + " >= " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.Like:
string esc = comparisonData.LikeEscape.ToString();
if (String.IsNullOrEmpty(esc) || esc == "\0")
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " LIKE " + compareTo;
needsStringParameter = true;
}
else
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " LIKE " + compareTo;
sql += " ESCAPE '" + esc + "'";
needsStringParameter = true;
}
break;
case tgComparisonOperand.NotLike:
esc = comparisonData.LikeEscape.ToString();
if (String.IsNullOrEmpty(esc) || esc == "\0")
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT LIKE " + compareTo;
needsStringParameter = true;
}
else
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT LIKE " + compareTo;
sql += " ESCAPE '" + esc + "'";
needsStringParameter = true;
}
break;
case tgComparisonOperand.Contains:
sql += " CONTAINS(" + GetColumnName(comparisonData.Column) +
", " + compareTo + ")";
needsStringParameter = true;
break;
case tgComparisonOperand.IsNull:
sql += ApplyWhereSubOperations(std, query, comparisonData) + " IS NULL";
requiresParam = false;
break;
case tgComparisonOperand.IsNotNull:
sql += ApplyWhereSubOperations(std, query, comparisonData) + " IS NOT NULL";
requiresParam = false;
break;
case tgComparisonOperand.In:
case tgComparisonOperand.NotIn:
{
if (subQuery != null)
{
// They used a subquery for In or Not
sql += ApplyWhereSubOperations(std, query, comparisonData);
sql += (comparisonData.Operand == tgComparisonOperand.In) ? " IN" : " NOT IN";
sql += compareTo;
}
else
{
comma = String.Empty;
if (comparisonData.Operand == tgComparisonOperand.In)
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " IN (";
}
else
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT IN (";
}
foreach (object oin in comparisonData.Values)
{
string str = oin as string;
if (str != null)
{
// STRING
sql += comma + "'" + str + "'";
comma = ",";
}
else if (null != oin as System.Collections.IEnumerable)
{
// LIST OR COLLECTION OF SOME SORT
System.Collections.IEnumerable enumer = oin as System.Collections.IEnumerable;
if (enumer != null)
{
System.Collections.IEnumerator iter = enumer.GetEnumerator();
while (iter.MoveNext())
{
object o = iter.Current;
string soin = o as string;
if (soin != null)
sql += comma + "'" + soin + "'";
else
sql += comma + Convert.ToString(o);
comma = ",";
}
}
}
else
{
// NON STRING OR LIST
sql += comma + Convert.ToString(oin);
comma = ",";
}
}
sql += ") ";
requiresParam = false;
}
}
break;
case tgComparisonOperand.Between:
OracleCommand sqlCommand = std.cmd as OracleCommand;
sql += ApplyWhereSubOperations(std, query, comparisonData) + " BETWEEN ";
sql += compareTo;
if (comparisonData.ComparisonColumn.Name == null)
{
OracleParameter p = new OracleParameter(compareTo, comparisonData.BetweenBegin);
sqlCommand.Parameters.Add(p);
}
if (comparisonData.ComparisonColumn2.Name == null)
{
IDynamicQuerySerializableInternal iColQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
tgColumnMetadataCollection columns = (tgColumnMetadataCollection)iColQuery.Columns;
compareTo = Delimiters.Param + columns[comparisonData.Column.Name].PropertyName + (++std.pindex).ToString();
sql += " AND " + compareTo;
OracleParameter p = new OracleParameter(compareTo, comparisonData.BetweenEnd);
sqlCommand.Parameters.Add(p);
}
else
{
sql += " AND " + Delimiters.ColumnOpen + comparisonData.ComparisonColumn2 + Delimiters.ColumnClose;
}
requiresParam = false;
break;
}
if (requiresParam)
{
OracleParameter p;
if (comparisonData.Column.Name != null)
{
p = types[comparisonData.Column.Name];
p = Cache.CloneParameter(p);
p.ParameterName = compareTo;
p.Value = comparisonData.Value;
if (needsStringParameter)
{
p.DbType = DbType.String;
}
else if (std.needsIntegerParameter)
{
p.DbType = DbType.Int32;
}
}
else
{
p = new OracleParameter(compareTo, comparisonData.Value);
}
std.cmd.Parameters.Add(p);
}
first = false;
}
}
// Kind of a hack here, I should probably pull this out and put it in build query ... and do it only for the WHERE
if (query.tg.Top >= 0 && prefix == " WHERE ")
{
if (!first)
{
sql += " AND ";
}
else
{
sql += " WHERE ";
}
sql += "ROWNUM <= " + query.tg.Top.ToString();
}
return sql;
}
protected static string GetOrderByStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
string comma = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalOrderByItems != null)
{
sql += " ORDER BY ";
foreach (tgOrderByItem orderByItem in iQuery.InternalOrderByItems)
{
bool literal = false;
sql += comma;
string columnName = orderByItem.Expression.Column.Name;
if (columnName != null && columnName[0] == '<')
{
sql += columnName.Substring(1, columnName.Length - 2);
if (orderByItem.Direction == tgOrderByDirection.Unassigned)
{
literal = true; // They must provide the DESC/ASC in the literal string
}
}
else
{
// Is in Set Operation (kind of a tricky workaround)
if (iQuery.HasSetOperation)
{
string joinAlias = iQuery.JoinAlias;
iQuery.JoinAlias = " ";
sql += GetExpressionColumn(std, query, orderByItem.Expression, false, false);
iQuery.JoinAlias = joinAlias;
}
else
{
sql += GetExpressionColumn(std, query, orderByItem.Expression, false, false);
}
}
if (!literal)
{
if (orderByItem.Direction == tgOrderByDirection.Ascending)
sql += " ASC";
else
sql += " DESC";
}
comma = ",";
}
}
return sql;
}
protected static string GetGroupByStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
string comma = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalGroupByItems != null)
{
sql += " GROUP BY ";
if (query.tg.WithRollup)
{
sql += " ROLLUP(";
}
foreach (tgGroupByItem groupBy in iQuery.InternalGroupByItems)
{
sql += comma;
string columnName = groupBy.Expression.Column.Name;
if (columnName != null && columnName[0] == '<')
sql += columnName.Substring(1, columnName.Length - 2);
else
sql += GetExpressionColumn(std, query, groupBy.Expression, false, false);
comma = ",";
}
if (query.tg.WithRollup)
{
sql += ")";
}
}
return sql;
}
protected static string GetSetOperationStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalSetOperations != null)
{
foreach (tgSetOperation setOperation in iQuery.InternalSetOperations)
{
switch (setOperation.SetOperationType)
{
case tgSetOperationType.Union: sql += " UNION "; break;
case tgSetOperationType.UnionAll: sql += " UNION ALL "; break;
case tgSetOperationType.Intersect: sql += " INTERSECT "; break;
case tgSetOperationType.Except: sql += " MINUS "; break;
}
sql += BuildQuery(std, setOperation.Query);
}
}
return sql;
}
protected static string GetExpressionColumn(StandardProviderParameters std, tgDynamicQuerySerializable query, tgExpression expression, bool inExpression, bool useAlias)
{
string sql = String.Empty;
if (expression.CaseWhen != null)
{
return GetCaseWhenThenEnd(std, query, expression.CaseWhen);
}
if (expression.HasMathmaticalExpression)
{
sql += GetMathmaticalExpressionColumn(std, query, expression.MathmaticalExpression);
}
else
{
sql += GetColumnName(expression.Column);
}
if (expression.SubOperators != null)
{
if (expression.Column.Distinct)
{
sql = BuildSubOperationsSql(std, "DISTINCT " + sql, expression.SubOperators);
}
else
{
sql = BuildSubOperationsSql(std, sql, expression.SubOperators);
}
}
if (!inExpression && useAlias)
{
if (expression.SubOperators != null || expression.Column.HasAlias)
{
sql += " AS " + Delimiters.ColumnOpen + expression.Column.Alias + Delimiters.ColumnClose;
}
}
return sql;
}
protected static string GetCaseWhenThenEnd(StandardProviderParameters std, tgDynamicQuerySerializable query, tgCase caseWhenThen)
{
string sql = string.Empty;
Tiraggo.DynamicQuery.tgCase.tgSimpleCaseData caseStatement = caseWhenThen;
tgColumnItem column = caseStatement.QueryItem;
sql += "CASE ";
List<tgComparison> list = new List<tgComparison>();
foreach (Tiraggo.DynamicQuery.tgCase.tgSimpleCaseData.tgCaseClause caseClause in caseStatement.Cases)
{
sql += " WHEN ";
if (!caseClause.When.IsExpression)
{
sql += GetComparisonStatement(std, query, caseClause.When.Comparisons, string.Empty);
}
else
{
if (!caseClause.When.Expression.IsLiteralValue)
{
sql += GetExpressionColumn(std, query, caseClause.When.Expression, false, true);
}
else
{
if (caseClause.When.Expression.LiteralValue is string)
{
sql += Delimiters.StringOpen + caseClause.When.Expression.LiteralValue + Delimiters.StringClose;
}
else
{
sql += Convert.ToString(caseClause.When.Expression.LiteralValue);
}
}
}
sql += " THEN ";
if (!caseClause.Then.IsLiteralValue)
{
sql += GetExpressionColumn(std, query, caseClause.Then, false, true);
}
else
{
if (caseClause.Then.LiteralValue is string)
{
sql += Delimiters.AliasOpen + caseClause.Then.LiteralValue + Delimiters.AliasClose;
}
else
{
sql += Convert.ToString(caseClause.Then.LiteralValue);
}
}
}
if (caseStatement.Else != null)
{
sql += " ELSE ";
if (!caseStatement.Else.IsLiteralValue)
{
sql += GetExpressionColumn(std, query, caseStatement.Else, false, true);
}
else
{
if (caseStatement.Else.LiteralValue is string)
{
sql += Delimiters.AliasOpen + caseStatement.Else.LiteralValue + Delimiters.AliasClose;
}
else
{
sql += Convert.ToString(caseStatement.Else.LiteralValue);
}
}
}
sql += " END ";
sql += " AS " + Delimiters.ColumnOpen + column.Alias + Delimiters.ColumnClose;
return sql;
}
protected static string GetMathmaticalExpressionColumn(StandardProviderParameters std, tgDynamicQuerySerializable query, tgMathmaticalExpression mathmaticalExpression)
{
bool isMod = false;
bool needsRounding = false;
string sql = "(";
if (mathmaticalExpression.ItemFirst)
{
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem1, true, false);
sql += esArithmeticOperatorToString(mathmaticalExpression, out isMod, out needsRounding);
if (mathmaticalExpression.SelectItem2 != null)
{
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem2, true, false);
}
else
{
sql += GetMathmaticalExpressionLiteralType(std, mathmaticalExpression);
}
}
else
{
if (mathmaticalExpression.SelectItem2 != null)
{
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem2, true, true);
}
else
{
sql += GetMathmaticalExpressionLiteralType(std, mathmaticalExpression);
}
sql += esArithmeticOperatorToString(mathmaticalExpression, out isMod, out needsRounding);
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem1, true, false);
}
sql += ")";
if (isMod)
{
sql = "MOD(" + sql.Replace("(", String.Empty).Replace(")", String.Empty) + ")";
}
if (needsRounding)
{
sql = "ROUND(" + sql + ", 10)";
}
return sql;
}
protected static string esArithmeticOperatorToString(tgMathmaticalExpression mathmaticalExpression, out bool isMod, out bool needsRounding)
{
isMod = false;
needsRounding = false;
switch (mathmaticalExpression.Operator)
{
case tgArithmeticOperator.Add:
// MEG - 4/26/08, I'm not thrilled with this check here, will revist on future release
if (mathmaticalExpression.SelectItem1.Column.Datatype == tgSystemType.String ||
(mathmaticalExpression.SelectItem1.HasMathmaticalExpression && mathmaticalExpression.SelectItem1.MathmaticalExpression.LiteralType == tgSystemType.String) ||
(mathmaticalExpression.SelectItem1.HasMathmaticalExpression && mathmaticalExpression.SelectItem1.MathmaticalExpression.SelectItem1.Column.Datatype == tgSystemType.String) ||
(mathmaticalExpression.LiteralType == tgSystemType.String))
return " || ";
else
return " + ";
case tgArithmeticOperator.Subtract: return " - ";
case tgArithmeticOperator.Multiply: return " * ";
case tgArithmeticOperator.Divide:
needsRounding = true;
return "/";
case tgArithmeticOperator.Modulo:
isMod = true;
return ",";
default: return "";
}
}
protected static string GetMathmaticalExpressionLiteralType(StandardProviderParameters std, tgMathmaticalExpression mathmaticalExpression)
{
switch (mathmaticalExpression.LiteralType)
{
case tgSystemType.String:
return "'" + (string)mathmaticalExpression.Literal + "'";
case tgSystemType.DateTime:
return Delimiters.StringOpen + ((DateTime)(mathmaticalExpression.Literal)).ToShortDateString() + Delimiters.StringClose;
default:
return Convert.ToString(mathmaticalExpression.Literal);
}
}
protected static string ApplyWhereSubOperations(StandardProviderParameters std, tgDynamicQuerySerializable query, tgComparison.tgComparisonData comparisonData)
{
string sql = string.Empty;
if (comparisonData.HasExpression)
{
sql += GetMathmaticalExpressionColumn(std, query, comparisonData.Expression);
if (comparisonData.SubOperators != null && comparisonData.SubOperators.Count > 0)
{
sql = BuildSubOperationsSql(std, sql, comparisonData.SubOperators);
}
return sql;
}
string delimitedColumnName = GetColumnName(comparisonData.Column);
if (comparisonData.SubOperators != null)
{
sql = BuildSubOperationsSql(std, delimitedColumnName, comparisonData.SubOperators);
}
else
{
sql = delimitedColumnName;
}
return sql;
}
protected static string BuildSubOperationsSql(StandardProviderParameters std, string columnName, List<tgQuerySubOperator> subOperators)
{
string sql = string.Empty;
subOperators.Reverse();
Stack<object> stack = new Stack<object>();
if (subOperators != null)
{
foreach (tgQuerySubOperator op in subOperators)
{
switch (op.SubOperator)
{
case tgQuerySubOperatorType.ToLower:
sql += "LOWER(";
stack.Push(")");
break;
case tgQuerySubOperatorType.ToUpper:
sql += "UPPER(";
stack.Push(")");
break;
case tgQuerySubOperatorType.LTrim:
sql += "LTRIM(";
stack.Push(")");
break;
case tgQuerySubOperatorType.RTrim:
sql += "RTRIM(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Trim:
sql += "LTRIM(RTRIM(";
stack.Push("))");
break;
case tgQuerySubOperatorType.SubString:
sql += "SUBSTR(";
stack.Push(")");
stack.Push(op.Parameters["length"]);
stack.Push(",");
if (op.Parameters.ContainsKey("start"))
{
stack.Push(op.Parameters["start"]);
stack.Push(",");
}
else
{
// They didn't pass in start so we start
// at the beginning
stack.Push(1);
stack.Push(",");
}
break;
case tgQuerySubOperatorType.Coalesce:
sql += "COALESCE(";
stack.Push(")");
stack.Push(op.Parameters["expressions"]);
stack.Push(",");
break;
case tgQuerySubOperatorType.Date:
sql += "TRUNC(";
stack.Push(")");
stack.Push("'DD'");
stack.Push(",");
break;
case tgQuerySubOperatorType.Length:
sql += "LENGTH(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Round:
sql += "ROUND(";
stack.Push(")");
stack.Push(op.Parameters["SignificantDigits"]);
stack.Push(",");
break;
case tgQuerySubOperatorType.DatePart:
std.needsStringParameter = true;
sql += "EXTRACT(";
sql += op.Parameters["DatePart"];
sql += " FROM ";
stack.Push(")");
break;
case tgQuerySubOperatorType.Avg:
sql += "ROUND(AVG(";
stack.Push("), 10)");
break;
case tgQuerySubOperatorType.Count:
sql += "COUNT(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Max:
sql += "MAX(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Min:
sql += "MIN(";
stack.Push(")");
break;
case tgQuerySubOperatorType.StdDev:
sql += "ROUND(STDDEV(";
stack.Push("), 10)");
break;
case tgQuerySubOperatorType.Sum:
sql += "SUM(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Var:
sql += "ROUND(VARIANCE(";
stack.Push("), 10)");
break;
case tgQuerySubOperatorType.Cast:
sql += "CAST(";
stack.Push(")");
if (op.Parameters.Count > 1)
{
stack.Push(")");
if (op.Parameters.Count == 2)
{
stack.Push(op.Parameters["length"].ToString());
}
else
{
stack.Push(op.Parameters["scale"].ToString());
stack.Push(",");
stack.Push(op.Parameters["precision"].ToString());
}
stack.Push("(");
}
stack.Push(GetCastSql((tgCastType)op.Parameters["tgCastType"]));
stack.Push(" AS ");
break;
}
}
sql += columnName;
while (stack.Count > 0)
{
sql += stack.Pop().ToString();
}
}
return sql;
}
protected static string GetCastSql(tgCastType castType)
{
switch (castType)
{
case tgCastType.Boolean: return "NUMBER";
case tgCastType.Byte: return "RAW";
case tgCastType.Char: return "CHAR";
case tgCastType.DateTime: return "TIMESTAMP";
case tgCastType.Double: return "NUMBER";
case tgCastType.Decimal: return "NUMBER";
case tgCastType.Guid: return "RAW";
case tgCastType.Int16: return "INTEGER";
case tgCastType.Int32: return "INTEGER";
case tgCastType.Int64: return "INTEGER";
case tgCastType.Single: return "NUMBER";
case tgCastType.String: return "VARCHAR2";
default: return "error";
}
}
protected static string GetColumnName(tgColumnItem column)
{
if (column.Query == null || column.Query.tg.JoinAlias == " ")
{
return Delimiters.ColumnOpen + column.Name + Delimiters.ColumnClose;
}
else
{
IDynamicQuerySerializableInternal iQuery = column.Query as IDynamicQuerySerializableInternal;
if (iQuery.IsInSubQuery)
{
return column.Query.tg.JoinAlias + "." + Delimiters.ColumnOpen + column.Name + Delimiters.ColumnClose;
}
else
{
string alias = iQuery.SubQueryAlias == string.Empty ? iQuery.JoinAlias : iQuery.SubQueryAlias;
return alias + "." + Delimiters.ColumnOpen + column.Name + Delimiters.ColumnClose;
}
}
}
private static int NextParamIndex(IDbCommand cmd)
{
return cmd.Parameters.Count;
}
private static string GetSubquerySearchCondition(tgDynamicQuerySerializable query)
{
string searchCondition = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
switch (iQuery.SubquerySearchCondition)
{
case tgSubquerySearchCondition.All: searchCondition = "ALL"; break;
case tgSubquerySearchCondition.Any: searchCondition = "ANY"; break;
case tgSubquerySearchCondition.Some: searchCondition = "SOME"; break;
}
return searchCondition;
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using BulletSharp.Math;
namespace BulletSharp
{
public class MultiBodySolverConstraint : IDisposable
{
internal IntPtr _native;
protected MultiBody _multiBodyA;
protected MultiBody _multiBodyB;
internal MultiBodySolverConstraint(IntPtr native)
{
_native = native;
}
public MultiBodySolverConstraint()
{
_native = btMultiBodySolverConstraint_new();
}
public Vector3 AngularComponentA
{
get
{
Vector3 value;
btMultiBodySolverConstraint_getAngularComponentA(_native, out value);
return value;
}
set { btMultiBodySolverConstraint_setAngularComponentA(_native, ref value); }
}
public Vector3 AngularComponentB
{
get
{
Vector3 value;
btMultiBodySolverConstraint_getAngularComponentB(_native, out value);
return value;
}
set { btMultiBodySolverConstraint_setAngularComponentB(_native, ref value); }
}
public float AppliedImpulse
{
get { return btMultiBodySolverConstraint_getAppliedImpulse(_native); }
set { btMultiBodySolverConstraint_setAppliedImpulse(_native, value); }
}
public float AppliedPushImpulse
{
get { return btMultiBodySolverConstraint_getAppliedPushImpulse(_native); }
set { btMultiBodySolverConstraint_setAppliedPushImpulse(_native, value); }
}
public float Cfm
{
get { return btMultiBodySolverConstraint_getCfm(_native); }
set { btMultiBodySolverConstraint_setCfm(_native, value); }
}
public Vector3 ContactNormal1
{
get
{
Vector3 value;
btMultiBodySolverConstraint_getContactNormal1(_native, out value);
return value;
}
set { btMultiBodySolverConstraint_setContactNormal1(_native, ref value); }
}
public Vector3 ContactNormal2
{
get
{
Vector3 value;
btMultiBodySolverConstraint_getContactNormal2(_native, out value);
return value;
}
set { btMultiBodySolverConstraint_setContactNormal2(_native, ref value); }
}
public int DeltaVelAindex
{
get { return btMultiBodySolverConstraint_getDeltaVelAindex(_native); }
set { btMultiBodySolverConstraint_setDeltaVelAindex(_native, value); }
}
public int DeltaVelBindex
{
get { return btMultiBodySolverConstraint_getDeltaVelBindex(_native); }
set { btMultiBodySolverConstraint_setDeltaVelBindex(_native, value); }
}
public float Friction
{
get { return btMultiBodySolverConstraint_getFriction(_native); }
set { btMultiBodySolverConstraint_setFriction(_native, value); }
}
public int FrictionIndex
{
get { return btMultiBodySolverConstraint_getFrictionIndex(_native); }
set { btMultiBodySolverConstraint_setFrictionIndex(_native, value); }
}
public int JacAindex
{
get { return btMultiBodySolverConstraint_getJacAindex(_native); }
set { btMultiBodySolverConstraint_setJacAindex(_native, value); }
}
public int JacBindex
{
get { return btMultiBodySolverConstraint_getJacBindex(_native); }
set { btMultiBodySolverConstraint_setJacBindex(_native, value); }
}
public float JacDiagABInv
{
get { return btMultiBodySolverConstraint_getJacDiagABInv(_native); }
set { btMultiBodySolverConstraint_setJacDiagABInv(_native, value); }
}
public int LinkA
{
get { return btMultiBodySolverConstraint_getLinkA(_native); }
set { btMultiBodySolverConstraint_setLinkA(_native, value); }
}
public int LinkB
{
get { return btMultiBodySolverConstraint_getLinkB(_native); }
set { btMultiBodySolverConstraint_setLinkB(_native, value); }
}
public float LowerLimit
{
get { return btMultiBodySolverConstraint_getLowerLimit(_native); }
set { btMultiBodySolverConstraint_setLowerLimit(_native, value); }
}
public MultiBody MultiBodyA
{
get
{
if (_multiBodyA == null)
{
_multiBodyA = new MultiBody(btMultiBodySolverConstraint_getMultiBodyA(_native));
}
return _multiBodyA;
}
set
{
btMultiBodySolverConstraint_setMultiBodyA(_native, value._native);
_multiBodyA = value;
}
}
public MultiBody MultiBodyB
{
get
{
if (_multiBodyB == null)
{
_multiBodyB = new MultiBody(btMultiBodySolverConstraint_getMultiBodyB(_native));
}
return _multiBodyB;
}
set
{
btMultiBodySolverConstraint_setMultiBodyB(_native, value._native);
_multiBodyB = value;
}
}
/*
public MultiBodyConstraint OrgConstraint
{
get { return btMultiBodySolverConstraint_getOrgConstraint(_native); }
set { btMultiBodySolverConstraint_setOrgConstraint(_native, value._native); }
}
*/
public int OrgDofIndex
{
get { return btMultiBodySolverConstraint_getOrgDofIndex(_native); }
set { btMultiBodySolverConstraint_setOrgDofIndex(_native, value); }
}
public IntPtr OriginalContactPoint
{
get { return btMultiBodySolverConstraint_getOriginalContactPoint(_native); }
set { btMultiBodySolverConstraint_setOriginalContactPoint(_native, value); }
}
public int OverrideNumSolverIterations
{
get { return btMultiBodySolverConstraint_getOverrideNumSolverIterations(_native); }
set { btMultiBodySolverConstraint_setOverrideNumSolverIterations(_native, value); }
}
public Vector3 Relpos1CrossNormal
{
get
{
Vector3 value;
btMultiBodySolverConstraint_getRelpos1CrossNormal(_native, out value);
return value;
}
set { btMultiBodySolverConstraint_setRelpos1CrossNormal(_native, ref value); }
}
public Vector3 Relpos2CrossNormal
{
get
{
Vector3 value;
btMultiBodySolverConstraint_getRelpos2CrossNormal(_native, out value);
return value;
}
set { btMultiBodySolverConstraint_setRelpos2CrossNormal(_native, ref value); }
}
public float Rhs
{
get { return btMultiBodySolverConstraint_getRhs(_native); }
set { btMultiBodySolverConstraint_setRhs(_native, value); }
}
public float RhsPenetration
{
get { return btMultiBodySolverConstraint_getRhsPenetration(_native); }
set { btMultiBodySolverConstraint_setRhsPenetration(_native, value); }
}
public int SolverBodyIdA
{
get { return btMultiBodySolverConstraint_getSolverBodyIdA(_native); }
set { btMultiBodySolverConstraint_setSolverBodyIdA(_native, value); }
}
public int SolverBodyIdB
{
get { return btMultiBodySolverConstraint_getSolverBodyIdB(_native); }
set { btMultiBodySolverConstraint_setSolverBodyIdB(_native, value); }
}
public float UnusedPadding4
{
get { return btMultiBodySolverConstraint_getUnusedPadding4(_native); }
set { btMultiBodySolverConstraint_setUnusedPadding4(_native, value); }
}
public float UpperLimit
{
get { return btMultiBodySolverConstraint_getUpperLimit(_native); }
set { btMultiBodySolverConstraint_setUpperLimit(_native, value); }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_native != IntPtr.Zero)
{
btMultiBodySolverConstraint_delete(_native);
_native = IntPtr.Zero;
}
}
~MultiBodySolverConstraint()
{
Dispose(false);
}
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBodySolverConstraint_new();
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_getAngularComponentA(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_getAngularComponentB(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getAppliedImpulse(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getAppliedPushImpulse(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getCfm(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_getContactNormal1(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_getContactNormal2(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getDeltaVelAindex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getDeltaVelBindex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getFriction(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getFrictionIndex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getJacAindex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getJacBindex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getJacDiagABInv(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getLinkA(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getLinkB(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getLowerLimit(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBodySolverConstraint_getMultiBodyA(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBodySolverConstraint_getMultiBodyB(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBodySolverConstraint_getOrgConstraint(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getOrgDofIndex(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern IntPtr btMultiBodySolverConstraint_getOriginalContactPoint(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getOverrideNumSolverIterations(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_getRelpos1CrossNormal(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_getRelpos2CrossNormal(IntPtr obj, [Out] out Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getRhs(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getRhsPenetration(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getSolverBodyIdA(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern int btMultiBodySolverConstraint_getSolverBodyIdB(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getUnusedPadding4(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern float btMultiBodySolverConstraint_getUpperLimit(IntPtr obj);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setAngularComponentA(IntPtr obj, [In] ref Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setAngularComponentB(IntPtr obj, [In] ref Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setAppliedImpulse(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setAppliedPushImpulse(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setCfm(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setContactNormal1(IntPtr obj, [In] ref Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setContactNormal2(IntPtr obj, [In] ref Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setDeltaVelAindex(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setDeltaVelBindex(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setFriction(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setFrictionIndex(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setJacAindex(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setJacBindex(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setJacDiagABInv(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setLinkA(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setLinkB(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setLowerLimit(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setMultiBodyA(IntPtr obj, IntPtr value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setMultiBodyB(IntPtr obj, IntPtr value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setOrgConstraint(IntPtr obj, IntPtr value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setOrgDofIndex(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setOriginalContactPoint(IntPtr obj, IntPtr value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setOverrideNumSolverIterations(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setRelpos1CrossNormal(IntPtr obj, [In] ref Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setRelpos2CrossNormal(IntPtr obj, [In] ref Vector3 value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setRhs(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setRhsPenetration(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setSolverBodyIdA(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setSolverBodyIdB(IntPtr obj, int value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setUnusedPadding4(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_setUpperLimit(IntPtr obj, float value);
[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity]
static extern void btMultiBodySolverConstraint_delete(IntPtr obj);
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace Dataphoria.Web.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Cloud.ServiceControl.V1
{
/// <summary>Settings for <see cref="QuotaControllerClient"/> instances.</summary>
public sealed partial class QuotaControllerSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="QuotaControllerSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="QuotaControllerSettings"/>.</returns>
public static QuotaControllerSettings GetDefault() => new QuotaControllerSettings();
/// <summary>Constructs a new <see cref="QuotaControllerSettings"/> object with default settings.</summary>
public QuotaControllerSettings()
{
}
private QuotaControllerSettings(QuotaControllerSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
AllocateQuotaSettings = existing.AllocateQuotaSettings;
OnCopy(existing);
}
partial void OnCopy(QuotaControllerSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>QuotaControllerClient.AllocateQuota</c> and <c>QuotaControllerClient.AllocateQuotaAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings AllocateQuotaSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="QuotaControllerSettings"/> object.</returns>
public QuotaControllerSettings Clone() => new QuotaControllerSettings(this);
}
/// <summary>
/// Builder class for <see cref="QuotaControllerClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
public sealed partial class QuotaControllerClientBuilder : gaxgrpc::ClientBuilderBase<QuotaControllerClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public QuotaControllerSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public QuotaControllerClientBuilder()
{
UseJwtAccessWithScopes = QuotaControllerClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref QuotaControllerClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<QuotaControllerClient> task);
/// <summary>Builds the resulting client.</summary>
public override QuotaControllerClient Build()
{
QuotaControllerClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<QuotaControllerClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<QuotaControllerClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private QuotaControllerClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return QuotaControllerClient.Create(callInvoker, Settings);
}
private async stt::Task<QuotaControllerClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return QuotaControllerClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => QuotaControllerClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => QuotaControllerClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => QuotaControllerClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>QuotaController client wrapper, for convenient use.</summary>
/// <remarks>
/// [Google Quota Control API](/service-control/overview)
///
/// Allows clients to allocate and release quota against a [managed
/// service](https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService).
/// </remarks>
public abstract partial class QuotaControllerClient
{
/// <summary>
/// The default endpoint for the QuotaController service, which is a host of "servicecontrol.googleapis.com" and
/// a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "servicecontrol.googleapis.com:443";
/// <summary>The default QuotaController scopes.</summary>
/// <remarks>
/// The default QuotaController scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// <item><description>https://www.googleapis.com/auth/servicecontrol</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/servicecontrol",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="QuotaControllerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="QuotaControllerClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="QuotaControllerClient"/>.</returns>
public static stt::Task<QuotaControllerClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new QuotaControllerClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="QuotaControllerClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="QuotaControllerClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="QuotaControllerClient"/>.</returns>
public static QuotaControllerClient Create() => new QuotaControllerClientBuilder().Build();
/// <summary>
/// Creates a <see cref="QuotaControllerClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="QuotaControllerSettings"/>.</param>
/// <returns>The created <see cref="QuotaControllerClient"/>.</returns>
internal static QuotaControllerClient Create(grpccore::CallInvoker callInvoker, QuotaControllerSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
QuotaController.QuotaControllerClient grpcClient = new QuotaController.QuotaControllerClient(callInvoker);
return new QuotaControllerClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC QuotaController client</summary>
public virtual QuotaController.QuotaControllerClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual AllocateQuotaResponse AllocateQuota(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AllocateQuotaResponse> AllocateQuotaAsync(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<AllocateQuotaResponse> AllocateQuotaAsync(AllocateQuotaRequest request, st::CancellationToken cancellationToken) =>
AllocateQuotaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>QuotaController client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// [Google Quota Control API](/service-control/overview)
///
/// Allows clients to allocate and release quota against a [managed
/// service](https://cloud.google.com/service-management/reference/rpc/google.api/servicemanagement.v1#google.api.servicemanagement.v1.ManagedService).
/// </remarks>
public sealed partial class QuotaControllerClientImpl : QuotaControllerClient
{
private readonly gaxgrpc::ApiCall<AllocateQuotaRequest, AllocateQuotaResponse> _callAllocateQuota;
/// <summary>
/// Constructs a client wrapper for the QuotaController service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="QuotaControllerSettings"/> used within this client.</param>
public QuotaControllerClientImpl(QuotaController.QuotaControllerClient grpcClient, QuotaControllerSettings settings)
{
GrpcClient = grpcClient;
QuotaControllerSettings effectiveSettings = settings ?? QuotaControllerSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callAllocateQuota = clientHelper.BuildApiCall<AllocateQuotaRequest, AllocateQuotaResponse>(grpcClient.AllocateQuotaAsync, grpcClient.AllocateQuota, effectiveSettings.AllocateQuotaSettings).WithGoogleRequestParam("service_name", request => request.ServiceName);
Modify_ApiCall(ref _callAllocateQuota);
Modify_AllocateQuotaApiCall(ref _callAllocateQuota);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_AllocateQuotaApiCall(ref gaxgrpc::ApiCall<AllocateQuotaRequest, AllocateQuotaResponse> call);
partial void OnConstruction(QuotaController.QuotaControllerClient grpcClient, QuotaControllerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC QuotaController client</summary>
public override QuotaController.QuotaControllerClient GrpcClient { get; }
partial void Modify_AllocateQuotaRequest(ref AllocateQuotaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override AllocateQuotaResponse AllocateQuota(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AllocateQuotaRequest(ref request, ref callSettings);
return _callAllocateQuota.Sync(request, callSettings);
}
/// <summary>
/// Attempts to allocate quota for the specified consumer. It should be called
/// before the operation is executed.
///
/// This method requires the `servicemanagement.services.quota`
/// permission on the specified service. For more information, see
/// [Cloud IAM](https://cloud.google.com/iam).
///
/// **NOTE:** The client **must** fail-open on server errors `INTERNAL`,
/// `UNKNOWN`, `DEADLINE_EXCEEDED`, and `UNAVAILABLE`. To ensure system
/// reliability, the server may inject these errors to prohibit any hard
/// dependency on the quota functionality.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<AllocateQuotaResponse> AllocateQuotaAsync(AllocateQuotaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_AllocateQuotaRequest(ref request, ref callSettings);
return _callAllocateQuota.Async(request, callSettings);
}
}
}
| |
/*
* 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 QuantConnect.Data.Market;
using QuantConnect.Securities;
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Logging;
namespace QuantConnect.ToolBox.RandomDataGenerator
{
/// <summary>
/// Generates random tick data according to the settings provided
/// </summary>
public class TickGenerator : ITickGenerator
{
private readonly IPriceGenerator _priceGenerator;
private Symbol Symbol => Security.Symbol;
private readonly IRandomValueGenerator _random;
private readonly RandomDataGeneratorSettings _settings;
private readonly TickType[] _tickTypes;
private MarketHoursDatabase MarketHoursDatabase { get; }
private SymbolPropertiesDatabase SymbolPropertiesDatabase { get; }
private Security Security { get; }
public TickGenerator(RandomDataGeneratorSettings settings, TickType[] tickTypes, Security security, IRandomValueGenerator random)
{
_random = random;
_settings = settings;
_tickTypes = tickTypes;
Security = security;
SymbolPropertiesDatabase = SymbolPropertiesDatabase.FromDataFolder();
MarketHoursDatabase = MarketHoursDatabase.FromDataFolder();
if (Symbol.SecurityType.IsOption())
{
_priceGenerator = new OptionPriceModelPriceGenerator(security);
}
else
{
_priceGenerator = new RandomPriceGenerator(security, random);
}
}
public IEnumerable<Tick> GenerateTicks()
{
var current = _settings.Start;
// There is a possibility that even though this succeeds, the DateTime
// generated may be the same as the starting DateTime, although the probability
// of this happening diminishes the longer the period we're generating data for is
if (_random.NextBool(_settings.HasIpoPercentage))
{
current = _random.NextDate(_settings.Start, _settings.End, null);
Log.Trace($"\tSymbol: {Symbol} has delayed IPO at date {current:yyyy MMMM dd}");
}
// creates a max deviation that scales parabolically as resolution decreases (lower frequency)
var deviation = GetMaximumDeviation(_settings.Resolution);
while (current <= _settings.End)
{
var next = NextTickTime(current, _settings.Resolution, _settings.DataDensity);
if (_tickTypes.Contains(TickType.OpenInterest))
{
if (next.Date != current.Date)
{
// 5% deviation in daily OI
var openInterest = NextTick(next.Date, TickType.OpenInterest, 5m);
yield return openInterest;
}
}
Tick nextTick = null;
// keeps quotes close to the trades for consistency
if (_tickTypes.Contains(TickType.Trade) &&
_tickTypes.Contains(TickType.Quote))
{
// %odds of getting a trade tick, for example, a quote:trade ratio of 2 means twice as likely
// to get a quote, which means you have a 33% chance of getting a trade => 1/3
var tradeChancePercent = 100 / (1 + _settings.QuoteTradeRatio);
nextTick = NextTick(
next,
_random.NextBool(tradeChancePercent)
? TickType.Trade
: TickType.Quote,
deviation);
}
else if (_tickTypes.Contains(TickType.Trade))
{
nextTick = NextTick(next, TickType.Trade, deviation);
}
else if (_tickTypes.Contains(TickType.Quote))
{
nextTick = NextTick(next, TickType.Quote, deviation);
}
if (nextTick != null && _priceGenerator.WarmedUp)
{
yield return nextTick;
}
// advance to the next time step
current = next;
}
}
/// <summary>
/// Generates a random <see cref="Tick"/> that is at most the specified <paramref name="maximumPercentDeviation"/> away from the
/// previous price and is of the requested <paramref name="tickType"/>
/// </summary>
/// <param name="dateTime">The time of the generated tick</param>
/// <param name="tickType">The type of <see cref="Tick"/> to be generated</param>
/// <param name="maximumPercentDeviation">The maximum percentage to deviate from the
/// previous price for example, 1 would indicate a maximum of 1% deviation from the
/// previous price. For a previous price of 100, this would yield a price between 99 and 101 inclusive</param>
/// <returns>A random <see cref="Tick"/> value that is within the specified <paramref name="maximumPercentDeviation"/>
/// from the previous price</returns>
public virtual Tick NextTick(DateTime dateTime, TickType tickType, decimal maximumPercentDeviation)
{
var next = _priceGenerator.NextValue(maximumPercentDeviation, dateTime);
var tick = new Tick
{
Time = dateTime,
Symbol = Symbol,
TickType = tickType,
Value = next
};
switch (tickType)
{
case TickType.OpenInterest:
return NextOpenInterest(dateTime, Security.OpenInterest, maximumPercentDeviation);
case TickType.Trade:
tick.Quantity = _random.NextInt(1, 1500);
return tick;
case TickType.Quote:
var bid = _random.NextPrice(Symbol.SecurityType, Symbol.ID.Market, tick.Value, maximumPercentDeviation);
if (bid > tick.Value)
{
bid = tick.Value - (bid - tick.Value);
}
var ask = _random.NextPrice(Symbol.SecurityType, Symbol.ID.Market, tick.Value, maximumPercentDeviation);
if (ask < tick.Value)
{
ask = tick.Value + (tick.Value - ask);
}
tick.BidPrice = bid;
tick.BidSize = _random.NextInt(1, 1500);
tick.AskPrice = ask;
tick.AskSize = _random.NextInt(1, 1500);
return tick;
default:
throw new ArgumentOutOfRangeException(nameof(tickType), tickType, null);
}
}
/// <summary>
/// Generates a random <see cref="Tick"/> that is at most the specified <paramref name="maximumPercentDeviation"/> away from the
/// <paramref name="previousValue"/> and is of the Open Interest
/// </summary>
/// <param name="dateTime">The time of the generated tick</param>
/// <param name="previousValue">The previous price, used as a reference for generating
/// new random prices for the next time step</param>
/// <param name="maximumPercentDeviation">The maximum percentage to deviate from the
/// <paramref name="previousValue"/>, for example, 1 would indicate a maximum of 1% deviation from the
/// <paramref name="previousValue"/>. For a previous price of 100, this would yield a price between 99 and 101 inclusive</param>
/// <returns>A random <see cref="Tick"/> value that is within the specified <paramref name="maximumPercentDeviation"/>
/// from the <paramref name="previousValue"/></returns>
public Tick NextOpenInterest(DateTime dateTime, decimal previousValue, decimal maximumPercentDeviation)
{
var next = (long)_random.NextPrice(Symbol.SecurityType, Symbol.ID.Market, previousValue, maximumPercentDeviation);
return new Tick
{
Time = dateTime,
Symbol = Symbol,
TickType = TickType.OpenInterest,
Value = next,
Quantity = next
};
}
/// <summary>
/// Generates a random <see cref="DateTime"/> suitable for use as a tick's emit time.
/// If the density provided is <see cref="DataDensity.Dense"/>, then at least one tick will be generated per <paramref name="resolution"/> step.
/// If the density provided is <see cref="DataDensity.Sparse"/>, then at least one tick will be generated every 5 <paramref name="resolution"/> steps.
/// if the density provided is <see cref="DataDensity.VerySparse"/>, then at least one tick will be generated every 50 <paramref name="resolution"/> steps.
/// Times returned are guaranteed to be within market hours for the specified Symbol
/// </summary>
/// <param name="previous">The previous tick time</param>
/// <param name="resolution">The requested resolution of data</param>
/// <param name="density">The requested data density</param>
/// <returns>A new <see cref="DateTime"/> that is after <paramref name="previous"/> according to the specified <paramref name="resolution"/>
/// and <paramref name="density"/> specified</returns>
public virtual DateTime NextTickTime(DateTime previous, Resolution resolution, DataDensity density)
{
var increment = resolution.ToTimeSpan();
if (increment == TimeSpan.Zero)
{
increment = TimeSpan.FromMilliseconds(500);
}
double steps;
switch (density)
{
case DataDensity.Dense:
steps = 0.5 * _random.NextDouble();
break;
case DataDensity.Sparse:
steps = 5 * _random.NextDouble();
break;
case DataDensity.VerySparse:
steps = 50 * _random.NextDouble();
break;
default:
throw new ArgumentOutOfRangeException(nameof(density), density, null);
}
var delta = TimeSpan.FromTicks((long)(steps * increment.Ticks));
var tickTime = previous.Add(delta);
if (tickTime == previous)
{
tickTime = tickTime.Add(increment);
}
var barStart = tickTime.Subtract(increment);
var marketHours = MarketHoursDatabase.GetExchangeHours(Symbol.ID.Market, Symbol, Symbol.SecurityType);
if (!marketHours.IsDateOpen(tickTime) || !marketHours.IsOpen(barStart, tickTime, false))
{
// we ended up outside of market hours, emit a new tick at market open
var nextMarketOpen = marketHours.GetNextMarketOpen(tickTime, false);
if (resolution == Resolution.Tick)
{
resolution = Resolution.Second;
}
// emit a new tick somewhere in the next trading day at a step higher resolution to guarantee a hit
return NextTickTime(nextMarketOpen, resolution - 1, density);
}
return tickTime;
}
private static decimal GetMaximumDeviation(Resolution resolution)
{
var incr = ((int)resolution) + 0.15m;
var deviation = incr * incr * 0.1m;
return deviation;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using gcwcv = Google.Cloud.Workflows.Common.V1Beta;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Workflows.V1Beta.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedWorkflowsClientTest
{
[xunit::FactAttribute]
public void GetWorkflowRequestObject()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow response = client.GetWorkflow(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowRequestObjectAsync()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow responseCallSettings = await client.GetWorkflowAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workflow responseCancellationToken = await client.GetWorkflowAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflow()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow response = client.GetWorkflow(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowAsync()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow responseCallSettings = await client.GetWorkflowAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workflow responseCancellationToken = await client.GetWorkflowAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetWorkflowResourceNames()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflow(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow response = client.GetWorkflow(request.WorkflowName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetWorkflowResourceNamesAsync()
{
moq::Mock<Workflows.WorkflowsClient> mockGrpcClient = new moq::Mock<Workflows.WorkflowsClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
Workflow expectedResponse = new Workflow
{
WorkflowName = gcwcv::WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
Description = "description2cf9da67",
State = Workflow.Types.State.Unspecified,
RevisionId = "revision_id8d9ae05d",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RevisionCreateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ServiceAccount = "service_accounta3c1b923",
SourceContents = "source_contentscf4464d3",
};
mockGrpcClient.Setup(x => x.GetWorkflowAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Workflow>(stt::Task.FromResult(expectedResponse), null, null, null, null));
WorkflowsClient client = new WorkflowsClientImpl(mockGrpcClient.Object, null);
Workflow responseCallSettings = await client.GetWorkflowAsync(request.WorkflowName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Workflow responseCancellationToken = await client.GetWorkflowAsync(request.WorkflowName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using Lw.ApplicationMessages;
using Lw.Collections.Generic;
using Lw.Resources;
namespace Lw
{
/// <summary>
/// Provides messages for the Lw.Core assembly.
/// </summary>
/// <remarks>
/// <para>
/// Application messages are usually created by defining an AMDL file in a project and adding the
/// (ProjectName)Messages.CS.tt and (ProjectName)Messages.RESX.tt T4 templates to the project. Project
/// developers us the <c>CreateMessage</c> methods to create instances of <see cref="ApplicationMessage"/> that
/// correspond to the message needed. The developer passes the desired <see cref="ApplicationMessage"/> code
/// defined as a static field and passes the appropriate arguments in the specified order with the specified
/// types, as defined in the AMDL file. These messages can be logged directly by the
/// <see cref="Lw.Diagnostics.ILogWriter"/> using the priority information within the
/// <see cref="ApplicationMessage"/>.
/// <para></para>
/// Every <see cref="ApplicationMessage"/> seven properties:
/// <list type="table">
/// <listheader>
/// <term>Property</term>
/// <description>Comments</description>
/// </listheader>
/// <item>
/// <term>Schema</term>
/// <description>
/// The layout identifier for the messages code. Only codes that begin with the Schema Code
/// can be interpreted as an Application Message. Value is 0x00001.
/// </description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>The message severity.</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>
/// The message prioirty, used for logging thresholds. A value of Default (0) indicates that
/// the priority is derived from the severity.
/// </description>
/// </item>
/// <item>
/// <term>Authority</term>
/// <description>Code indicating the responsible party for defining Domain and Library.</description>
/// </item>
/// <item>
/// <term>Domain</term>
/// <description>
/// For system code, represents the area of application functionality that the libraries pertain.
/// For business or application code, represents the registerd Business Domain of the library or
/// application.
/// </description>
/// </item>
/// <item>
/// <term>Library</term>
/// <description>A C# project or interrelated group of projects.</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>The message base code. Unique within an individual library and severity.</description>
/// </item>
/// </list>
/// </para><para>
/// Layout of the message code is described below.
/// <code>
/// /-------------- Schema: Constant. Only these are Application Messages.
/// | 00001
/// |/------------- Severity Code: Message severity.
/// || 0 - F
/// || 0 - A Inverse of custom severities 5 - 16. 0 = 16, etc.
/// || B Verbose. Used for logging purposes.
/// || C Information
/// || D Warning.
/// || E Error. Application or system error.
/// || F Critical. Application or system failure or data
/// || corruption. Application or system must be stopped.
/// ||/------------ Priority Code: Message priority. Used for logging thresholds.
/// ||| 0 - F
/// ||| 0 Default. Prority is inferred by Severity.
/// ||| Severity Priority
/// ||| -------- --------
/// ||| Critical Mandatory
/// ||| Error High
/// ||| Warning Medium
/// ||| Information Low
/// ||| Verbose Very Low
/// ||| 1 Mandatory. Always logged.
/// ||| 2 High
/// ||| 3 Medium
/// ||| 4 Low
/// ||| 5 Very Low
/// ||| 6 - F. Numeric custom priorities.
/// |||
/// |||
/// |||
/// [ ]||
/// 0000 1F01 0101 F001
/// | [][] |[ ]
/// | | | | |
/// | | | | \- Base Code: Raw code value. Unique within Library/Severity.
/// | | | | 000 - FFF
/// | | | | 0000 - FFFF if not using local severity codes. (Rare)
/// | | | |
/// | | | \---- Local Severity Code: Same format as Severity Code below.
/// | | |
/// | | \------ Library Code: Libraries in Domain. Identifes an application or shared library.
/// | | 00 - FF Code defined by Authority.
/// | |
/// | \-------- Domain Code: Domains of Authority. Identifies a business domain or shared
/// | or application feature shared library implements.
/// | 00 - FF Code defined by Authority
/// |
/// \----------- Authority Code: Authority. Owner of Domain and Library codes.
/// 0 - F Statically defined. Only two are defined:
/// 0 Enterprise. For Core and System Libraries.
/// 1 Corporate. For Business Domains and Applications.
/// 2 - F Not defined.
/// </code>
/// </para>
/// </remarks>
/// <seealso cref="ApplicationMessage"/>
public class LwCoreMessages
{
#region Public Methods
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long)"/>
public static ApplicationMessage CreateMessage(
long messageCode, params object[] args)
{
return CreateMessage(null, Guid.Empty, null, messageCode, (CultureInfo)null, args);
}
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="obj">
/// The object that this message applies to.
/// </param>
/// <param name="memberNames">
/// Names of the properties that pertain to the message or <see langword="null"/> if none pertain.
/// </param>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="culture">
/// The <see cref="CultureInfo"/> object that represents the culture
/// for which the resource is localized. Note that if the resource is not localized
/// for this culture, the lookup will fall back using the culture's
/// <see cref="CultureInfo.Parent"/> property, stopping after
/// looking in the neutral culture. If this value is <see langword="null"/>, the
/// <see cref="CultureInfo"/> is obtained using the culture's
/// <see cref="CultureInfo.CurrentUICulture"/> property.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long, CultureInfo)"/>
public static ApplicationMessage CreateMessage(
object obj, IEnumerable<string> memberNames, long messageCode, params object[] args)
{
return CreateMessage(obj, null, memberNames, messageCode, (CultureInfo)null, args);
}
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="objectUid">
/// Uniquely defines the object that this message applies to.
/// </param>
/// <param name="memberNames">
/// Names of the properties that pertain to the message or <see langword="null"/> if none pertain.
/// </param>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long)"/>
public static ApplicationMessage CreateMessage(
Guid? objectUid, IEnumerable<string> memberNames, long messageCode, params object[] args)
{
return CreateMessage(null, objectUid, memberNames, messageCode, (CultureInfo)null, args);
}
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="culture">
/// The <see cref="CultureInfo"/> object that represents the culture
/// for which the resource is localized. Note that if the resource is not localized
/// for this culture, the lookup will fall back using the culture's
/// <see cref="CultureInfo.Parent"/> property, stopping after
/// looking in the neutral culture. If this value is <see langword="null"/>, the
/// <see cref="CultureInfo"/> is obtained using the culture's
/// <see cref="CultureInfo.CurrentUICulture"/> property.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long, CultureInfo)"/>
public static ApplicationMessage CreateMessage(
long messageCode, CultureInfo culture, params object[] args)
{
return CreateMessage(null, null, null, messageCode, culture, args);
}
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="obj">
/// The object that this message applies to.
/// </param>
/// <param name="memberNames">
/// Names of the properties that pertain to the message or <see langword="null"/> if none pertain.
/// </param>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="culture">
/// The <see cref="CultureInfo"/> object that represents the culture
/// for which the resource is localized. Note that if the resource is not localized
/// for this culture, the lookup will fall back using the culture's
/// <see cref="CultureInfo.Parent"/> property, stopping after
/// looking in the neutral culture. If this value is <see langword="null"/>, the
/// <see cref="CultureInfo"/> is obtained using the culture's
/// <see cref="CultureInfo.CurrentUICulture"/> property.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long, CultureInfo)"/>
public static ApplicationMessage CreateMessage(
object obj,
IEnumerable<string> memberNames,
long messageCode,
CultureInfo culture,
params object[] args)
{
return CreateMessage(obj, null, memberNames, messageCode, culture, args);
}
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="objectUid">
/// Uniquely defines the object that this message applies to.
/// </param>
/// <param name="memberNames">
/// Names of the properties that pertain to the message or <see langword="null"/> if none pertain.
/// </param>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="culture">
/// The <see cref="CultureInfo"/> object that represents the culture
/// for which the resource is localized. Note that if the resource is not localized
/// for this culture, the lookup will fall back using the culture's
/// <see cref="CultureInfo.Parent"/> property, stopping after
/// looking in the neutral culture. If this value is <see langword="null"/>, the
/// <see cref="CultureInfo"/> is obtained using the culture's
/// <see cref="CultureInfo.CurrentUICulture"/> property.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long, CultureInfo)"/>
public static ApplicationMessage CreateMessage(
Guid? objectUid,
IEnumerable<string> memberNames,
long messageCode,
CultureInfo culture,
params object[] args)
{
return CreateMessage(null, objectUid, memberNames, messageCode, culture, args);
}
/// <summary>
/// Creates an application message.
/// </summary>
/// <param name="obj">
/// The object that this message applies to.
/// </param>
/// <param name="objectUid">
/// Uniquely defines the object that this message applies to or <see langword="null"> if taken from
/// <paramref name="obj"/> or cannot be specified.
/// </param>
/// <param name="memberNames">
/// Names of the properties that pertain to the message or <see langword="null"/> if none pertain.
/// </param>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="culture">
/// The <see cref="CultureInfo"/> object that represents the culture
/// for which the resource is localized. Note that if the resource is not localized
/// for this culture, the lookup will fall back using the culture's
/// <see cref="CultureInfo.Parent"/> property, stopping after
/// looking in the neutral culture. If this value is <see langword="null"/>, the
/// <see cref="CultureInfo"/> is obtained using the culture's
/// <see cref="CultureInfo.CurrentUICulture"/> property.
/// </param>
/// <param name="args">
/// The message arguements. Must match the message format string.
/// </param>
/// <returns>
/// An <see cref="ApplicationMessage"/>
/// </returns>
/// <seealso cref="GetFormatString(long, CultureInfo)"/>
public static ApplicationMessage CreateMessage(
object obj,
Guid? objectUid,
IEnumerable<string> memberNames,
long messageCode,
CultureInfo culture,
params object[] args)
{
string format = GetFormatString(messageCode, culture);
return new ApplicationMessage(obj, objectUid, memberNames, messageCode, format, args);
}
/// <summary>
/// Returns the format string associated with the specified message code.
/// </summary>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <returns>
/// A format string localized to <see cref="CultureInfo.CurrentUICulture"/>.
/// </returns>
public static string GetFormatString(long messageCode)
{
return GetFormatString(messageCode, null);
}
/// <summary>
/// Returns the format string associated with the specified message code.
/// </summary>
/// <param name="messageCode">
/// A message code defined by <see cref="LwCoreMessages"/>.
/// </param>
/// <param name="culture">
/// The <see cref="CultureInfo"/> object that represents the culture
/// for which the resource is localized. Note that if the resource is not localized
/// for this culture, the lookup will fall back using the culture's
/// <see cref="CultureInfo.Parent"/> property, stopping after
/// looking in the neutral culture. If this value is <see langword="null"/>, the
/// <see cref="CultureInfo"/> is obtained using the culture's
/// <see cref="CultureInfo.CurrentUICulture"/> property.
/// </param>
/// <returns>
/// A format string localized to the specified culture.
/// </returns>
public static string GetFormatString(long messageCode, CultureInfo culture)
{
string resourceName = LwCoreMessages.messageFormatResourceNames.GetValue(
messageCode,
() => { throw new ArgumentOutOfRangeException("messageCode"); });
return LwCoreMessagesResources.ResourceManager.GetString(resourceName, culture);
}
#endregion Public Methods
#region Public Fields
/// <summary>
/// Common prefix for all message codes defined by <see cref="LwCoreMessages"/>.
/// </summary>
/// <value>
/// 0x100101010000
/// </value>
/// <remarks>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Schema</term>
/// <description>Enterprise</description>
/// </item>
/// <item>
/// <term>Authority</term>
/// <description>Enterprise</description>
/// </item>
/// <item>
/// <term>Domain</term>
/// <description>Core</description>
/// </item>
/// <item>
/// <term>Library</term>
/// <description>Core</description>
/// </item>
/// </list>
/// </remarks>
public const long MessageCodePrefix =
(long)ApplicationMessageSchemaCode.Enterprise |
(long)ApplicationMessageAuthorityCode.Enterprise |
(long)Lw.ApplicationMessages.EnterpriseMessageDomainCode.Core |
(long)Lw.ApplicationMessages.CoreMessageLibraryCode.Core;
#region Critical Messages
/// <summary>
/// An internal application error has occured. The application cannot continue. Description: '{0}'.
/// </summary>
/// <value>
/// 0x1F010101F001
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Critical</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x001</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>description</c>: String
/// </para><para>
/// The conditions under which the internal error occured.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"description",
typeof(String),
"The conditions under which the internal error occured.")]
[ResourceName("CriticalMessageInternalError")]
public const long CriticalMessageCodeInternalError =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Critical |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Critical |
0x001L;
#endregion Critical Messages
#region Error Messages
/// <summary>
/// The request is in error. Description: '{0}'.
/// </summary>
/// <value>
/// 0x1E010101E011
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Error</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x011</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>description</c>: String
/// </para><para>
/// Explanation of error.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"description",
typeof(String),
"Explanation of error.")]
[ResourceName("ErrorMessageRequestError")]
public const long ErrorMessageCodeRequestError =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Error |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Error |
0x011L;
/// <summary>
/// The request at offset '{0}' is null.
/// </summary>
/// <value>
/// 0x1E010101E012
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Error</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x012</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>requestIndex</c>: Int32
/// </para><para>
/// The zero-offset index of the request in the request list.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"requestIndex",
typeof(Int32),
"The zero-offset index of the request in the request list.")]
[ResourceName("ErrorMessageRequestNullError")]
public const long ErrorMessageCodeRequestNullError =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Error |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Error |
0x012L;
/// <summary>
/// The request at offset '{0}' has an invalid property '{1}'. Message: '{2}'.
/// </summary>
/// <value>
/// 0x1E010101E013
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Error</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x013</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>requestIndex</c>: Int32
/// </para><para>
/// The zero-offset index of the request in the request list.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>
/// <para>
/// <c>propertyName</c>: String
/// </para><para>
/// The name of the request property with the error.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>2</term>
/// <description>
/// <para>
/// <c>errorMessage</c>: String
/// </para><para>
/// A message describing the error.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"requestIndex",
typeof(Int32),
"The zero-offset index of the request in the request list.")]
[ApplicationMessageArgument(
"propertyName",
typeof(String),
"The name of the request property with the error.")]
[ApplicationMessageArgument(
"errorMessage",
typeof(String),
"A message describing the error.")]
[ResourceName("ErrorMessageRequestParameterError")]
public const long ErrorMessageCodeRequestParameterError =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Error |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Error |
0x013L;
/// <summary>
/// The request at offset '{0}' has a null property '{1}'.
/// </summary>
/// <value>
/// 0x1E010101E014
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Error</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x014</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>requestIndex</c>: Int32
/// </para><para>
/// The zero-offset index of the request in the request list.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>
/// <para>
/// <c>propertyName</c>: String
/// </para><para>
/// The name of the request property with the error.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"requestIndex",
typeof(Int32),
"The zero-offset index of the request in the request list.")]
[ApplicationMessageArgument(
"propertyName",
typeof(String),
"The name of the request property with the error.")]
[ResourceName("ErrorMessageRequestParameterNullError")]
public const long ErrorMessageCodeRequestParameterNullError =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Error |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Error |
0x014L;
/// <summary>
/// The request at offset '{0}' has a property '{1}' whose value is out the range of valid values.
/// </summary>
/// <value>
/// 0x1E010101E015
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Error</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x015</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>requestIndex</c>: Int32
/// </para><para>
/// The zero-offset index of the request in the request list.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>
/// <para>
/// <c>propertyName</c>: String
/// </para><para>
/// The name of the request property with the error.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"requestIndex",
typeof(Int32),
"The zero-offset index of the request in the request list.")]
[ApplicationMessageArgument(
"propertyName",
typeof(String),
"The name of the request property with the error.")]
[ResourceName("ErrorMessageRequestParameterOutOfRangeError")]
public const long ErrorMessageCodeRequestParameterOutOfRangeError =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Error |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Error |
0x015L;
#endregion Error Messages
#region Warning Messages
/// <summary>
/// An ApplicationMessageCodeAttribute was placed on type member incorrectly. The member must be an Int64 field or property. Member '{1}' of Type '{0}'.
/// </summary>
/// <value>
/// 0x1D010101D001
/// </value>
/// <remarks>
/// <para>
/// Properties:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Property</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>Prefix</term>
/// <description>0x100101010000</description>
/// </item>
/// <item>
/// <term>Severity</term>
/// <description>Warning</description>
/// </item>
/// <item>
/// <term>Priority</term>
/// <description>Default</description>
/// </item>
/// <item>
/// <term>Base Code</term>
/// <description>0x001</description>
/// </item>
/// </list>
/// </para><para>
/// Arguments:
/// </para><para>
/// <list>
/// <listheader>
/// <term>Argument</term>
/// <description>Value</description>
/// </listheader>
/// <item>
/// <term>0</term>
/// <description>
/// <para>
/// <c>type</c>: String
/// </para><para>
/// Type that has the invalid attributet.
/// </para>
/// </description>
/// </item>
/// <item>
/// <term>1</term>
/// <description>
/// <para>
/// <c>name</c>: String
/// </para><para>
/// Name of member with the invalid attribute.
/// </para>
/// </description>
/// </item>
/// </list>
/// </para>
/// </remarks>
[ApplicationMessageCode]
[ApplicationMessageArgument(
"type",
typeof(String),
"Type that has the invalid attributet.")]
[ApplicationMessageArgument(
"name",
typeof(String),
"Name of member with the invalid attribute.")]
[ResourceName("WarningMessageInvalidMessageCodeAttributeMember")]
public const long WarningMessageCodeInvalidMessageCodeAttributeMember =
LwCoreMessages.MessageCodePrefix |
(long)ApplicationMessageSeverityCode.Warning |
(long)ApplicationMessagePriorityCode.Default |
(long)ApplicationMessageLocalSeverityCode.Warning |
0x001L;
#endregion Warning Messages
#endregion Public Fields
#region Private Constructors
static LwCoreMessages()
{
LwCoreMessages.messageFormatResourceNames = ApplicationMessage.CreateMessageCodeResourceNameMap(
typeof(LwCoreMessages));
}
#endregion Private Constructors
#region Private Fields
private static readonly IDictionary<long, string> messageFormatResourceNames;
#endregion Private Fields
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Agent.Sdk;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
using Newtonsoft.Json.Linq;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using System.IO;
namespace Agent.Plugins.Repository
{
public interface ISourceProvider
{
Task GetSourceAsync(AgentTaskPluginExecutionContext executionContext, Pipelines.RepositoryResource repository, CancellationToken cancellationToken);
Task PostJobCleanupAsync(AgentTaskPluginExecutionContext executionContext, Pipelines.RepositoryResource repository);
}
public abstract class RepositoryTask : IAgentTaskPlugin
{
private static readonly HashSet<String> _checkoutOptions = new HashSet<String>(StringComparer.OrdinalIgnoreCase)
{
Pipelines.PipelineConstants.CheckoutTaskInputs.Clean,
Pipelines.PipelineConstants.CheckoutTaskInputs.FetchDepth,
Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs,
Pipelines.PipelineConstants.CheckoutTaskInputs.PersistCredentials,
Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules,
};
protected RepositoryTask()
: this(new SourceProviderFactory())
{
}
protected RepositoryTask(ISourceProviderFactory sourceProviderFactory)
{
SourceProviderFactory = sourceProviderFactory;
}
public Guid Id => Pipelines.PipelineConstants.CheckoutTask.Id;
public ISourceProviderFactory SourceProviderFactory { get; }
public abstract string Stage { get; }
public abstract Task RunAsync(AgentTaskPluginExecutionContext executionContext, CancellationToken token);
protected void MergeCheckoutOptions(AgentTaskPluginExecutionContext executionContext, Pipelines.RepositoryResource repository)
{
// Merge the repository checkout options
if ((!executionContext.Variables.TryGetValue("MERGE_CHECKOUT_OPTIONS", out VariableValue mergeCheckoutOptions) || !String.Equals(mergeCheckoutOptions.Value, "false", StringComparison.OrdinalIgnoreCase)) &&
repository.Properties.Get<JToken>(Pipelines.RepositoryPropertyNames.CheckoutOptions) is JObject checkoutOptions)
{
foreach (var pair in checkoutOptions)
{
var inputName = pair.Key;
// Skip if unexpected checkout option
if (!_checkoutOptions.Contains(inputName))
{
executionContext.Debug($"Unexpected checkout option '{inputName}'");
continue;
}
// Skip if input defined
if (executionContext.Inputs.TryGetValue(inputName, out string inputValue) && !string.IsNullOrEmpty(inputValue))
{
continue;
}
try
{
executionContext.Inputs[inputName] = pair.Value.ToObject<String>();
}
catch (Exception ex)
{
executionContext.Debug($"Error setting the checkout option '{inputName}': {ex.Message}");
}
}
}
}
protected bool HasMultipleCheckouts(AgentTaskPluginExecutionContext executionContext)
{
return executionContext != null && RepositoryUtil.HasMultipleCheckouts(executionContext.JobSettings);
}
}
public class CheckoutTask : RepositoryTask
{
public CheckoutTask()
{
}
public CheckoutTask(ISourceProviderFactory sourceProviderFactory)
: base(sourceProviderFactory)
{
}
public override string Stage => "main";
public override async Task RunAsync(AgentTaskPluginExecutionContext executionContext, CancellationToken token)
{
var sourceSkipVar = StringUtil.ConvertToBoolean(executionContext.Variables.GetValueOrDefault("agent.source.skip")?.Value) ||
!StringUtil.ConvertToBoolean(executionContext.Variables.GetValueOrDefault("build.syncSources")?.Value ?? bool.TrueString);
if (sourceSkipVar)
{
executionContext.Output($"Skip sync source for repository.");
return;
}
var repoAlias = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository, true);
var repo = executionContext.Repositories.Single(x => string.Equals(x.Alias, repoAlias, StringComparison.OrdinalIgnoreCase));
MergeCheckoutOptions(executionContext, repo);
var currentRepoPath = repo.Properties.Get<string>(Pipelines.RepositoryPropertyNames.Path);
var buildDirectory = executionContext.Variables.GetValueOrDefault("agent.builddirectory")?.Value;
var tempDirectory = executionContext.Variables.GetValueOrDefault("agent.tempdirectory")?.Value;
ArgUtil.NotNullOrEmpty(currentRepoPath, nameof(currentRepoPath));
ArgUtil.NotNullOrEmpty(buildDirectory, nameof(buildDirectory));
ArgUtil.NotNullOrEmpty(tempDirectory, nameof(tempDirectory));
// Determine the path that we should clone/move the repository into
const string sourcesDirectory = "s"; //Constants.Build.Path.SourcesDirectory
string expectRepoPath;
var path = executionContext.GetInput("path");
if (!string.IsNullOrEmpty(path))
{
// When the checkout task provides a path, always use that one
expectRepoPath = IOUtil.ResolvePath(buildDirectory, path);
if (!expectRepoPath.StartsWith(buildDirectory.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
{
throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{buildDirectory}', current resolved path '{expectRepoPath}'.");
}
}
else if (HasMultipleCheckouts(executionContext))
{
// When there are multiple checkout tasks (and this one didn't set the path), default to directory 1/s/<repoName>
expectRepoPath = Path.Combine(buildDirectory, sourcesDirectory, RepositoryUtil.GetCloneDirectory(repo));
}
else
{
// When there's a single checkout task that doesn't have path set, default to sources directory 1/s
expectRepoPath = Path.Combine(buildDirectory, sourcesDirectory);
}
// Update the repository path in the worker process
executionContext.UpdateRepositoryPath(repoAlias, expectRepoPath);
executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{currentRepoPath}'");
if (!string.Equals(currentRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
{
executionContext.Output($"Repository is current at '{currentRepoPath}', move to '{expectRepoPath}'.");
var count = 1;
var staging = Path.Combine(tempDirectory, $"_{count}");
while (Directory.Exists(staging))
{
count++;
staging = Path.Combine(tempDirectory, $"_{count}");
}
try
{
executionContext.Debug($"Move existing repository '{currentRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
IOUtil.MoveDirectory(currentRepoPath, expectRepoPath, staging, CancellationToken.None);
}
catch (Exception ex)
{
executionContext.Debug("Catch exception during repository move.");
executionContext.Debug(ex.ToString());
executionContext.Warning("Unable move and reuse existing repository to required location.");
IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
}
executionContext.Output($"Repository will be located at '{expectRepoPath}'.");
repo.Properties.Set<string>(Pipelines.RepositoryPropertyNames.Path, expectRepoPath);
}
ISourceProvider sourceProvider = SourceProviderFactory.GetSourceProvider(repo.Type);
await sourceProvider.GetSourceAsync(executionContext, repo, token);
}
}
public class CleanupTask : RepositoryTask
{
public override string Stage => "post";
public override async Task RunAsync(AgentTaskPluginExecutionContext executionContext, CancellationToken token)
{
var repoAlias = executionContext.TaskVariables.GetValueOrDefault("repository")?.Value;
if (!string.IsNullOrEmpty(repoAlias))
{
var repo = executionContext.Repositories.Single(x => string.Equals(x.Alias, repoAlias, StringComparison.OrdinalIgnoreCase));
ArgUtil.NotNull(repo, nameof(repo));
MergeCheckoutOptions(executionContext, repo);
ISourceProvider sourceProvider = SourceProviderFactory.GetSourceProvider(repo.Type);
await sourceProvider.PostJobCleanupAsync(executionContext, repo);
}
}
}
public interface ISourceProviderFactory
{
ISourceProvider GetSourceProvider(string repositoryType);
}
public class SourceProviderFactory : ISourceProviderFactory
{
public virtual ISourceProvider GetSourceProvider(string repositoryType)
{
ISourceProvider sourceProvider = null;
if (string.Equals(repositoryType, Pipelines.RepositoryTypes.GitHub, StringComparison.OrdinalIgnoreCase) ||
string.Equals(repositoryType, Pipelines.RepositoryTypes.GitHubEnterprise, StringComparison.OrdinalIgnoreCase))
{
sourceProvider = new GitHubSourceProvider();
}
else if (string.Equals(repositoryType, Pipelines.RepositoryTypes.Bitbucket, StringComparison.OrdinalIgnoreCase))
{
sourceProvider = new BitbucketGitSourceProvider();
}
else if (string.Equals(repositoryType, Pipelines.RepositoryTypes.ExternalGit, StringComparison.OrdinalIgnoreCase))
{
sourceProvider = new ExternalGitSourceProvider();
}
else if (string.Equals(repositoryType, Pipelines.RepositoryTypes.Git, StringComparison.OrdinalIgnoreCase))
{
sourceProvider = new TfsGitSourceProvider();
}
else if (string.Equals(repositoryType, Pipelines.RepositoryTypes.Tfvc, StringComparison.OrdinalIgnoreCase))
{
sourceProvider = new TfsVCSourceProvider();
}
else if (string.Equals(repositoryType, Pipelines.RepositoryTypes.Svn, StringComparison.OrdinalIgnoreCase))
{
sourceProvider = new SvnSourceProvider();
}
else
{
throw new NotSupportedException(repositoryType);
}
return sourceProvider;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
////////////////////////////////////////////////////////////////////////////
//
//
// Purpose: This class implements a set of methods for retrieving
// character type information. Character type information is
// independent of culture and region.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
//This class has only static members and therefore doesn't need to be serialized.
using System;
using System.Threading;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Reflection;
using System.Security;
using System.Diagnostics;
using System.Diagnostics.Contracts;
public static class CharUnicodeInfo
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Native methods to access the Unicode category data tables in charinfo.nlp.
//
internal const char HIGH_SURROGATE_START = '\ud800';
internal const char HIGH_SURROGATE_END = '\udbff';
internal const char LOW_SURROGATE_START = '\udc00';
internal const char LOW_SURROGATE_END = '\udfff';
internal const int UNICODE_CATEGORY_OFFSET = 0;
internal const int BIDI_CATEGORY_OFFSET = 1;
static bool s_initialized = InitTable();
// The native pointer to the 12:4:4 index table of the Unicode cateogry data.
unsafe static ushort* s_pCategoryLevel1Index;
unsafe static byte* s_pCategoriesValue;
// The native pointer to the 12:4:4 index table of the Unicode numeric data.
// The value of this index table is an index into the real value table stored in s_pNumericValues.
unsafe static ushort* s_pNumericLevel1Index;
// The numeric value table, which is indexed by s_pNumericLevel1Index.
// Every item contains the value for numeric value.
// unsafe static double* s_pNumericValues;
// To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting
// at 4-byte boundary. This cause a alignment issue since double is 8-byte.
unsafe static byte* s_pNumericValues;
// The digit value table, which is indexed by s_pNumericLevel1Index. It shares the same indice as s_pNumericValues.
// Every item contains the value for decimal digit/digit value.
unsafe static DigitValues* s_pDigitValues;
internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp";
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
//
// This is the header for the native data table that we load from UNICODE_INFO_FILE_NAME.
//
// Excplicit layout is used here since a syntax like char[16] can not be used in sequential layout.
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct UnicodeDataHeader {
[FieldOffset(0)]
internal char TableName; // WCHAR[16]
[FieldOffset(0x20)]
internal ushort version; // WORD[4]
[FieldOffset(0x28)]
internal uint OffsetToCategoriesIndex; // DWORD
[FieldOffset(0x2c)]
internal uint OffsetToCategoriesValue; // DWORD
[FieldOffset(0x30)]
internal uint OffsetToNumbericIndex; // DWORD
[FieldOffset(0x34)]
internal uint OffsetToDigitValue; // DWORD
[FieldOffset(0x38)]
internal uint OffsetToNumbericValue; // DWORD
}
// NOTE: It's important to specify pack size here, since the size of the structure is 2 bytes. Otherwise,
// the default pack size will be 4.
[StructLayout(LayoutKind.Sequential, Pack=2)]
internal struct DigitValues {
internal sbyte decimalDigit;
internal sbyte digit;
}
//We need to allocate the underlying table that provides us with the information that we
//use. We allocate this once in the class initializer and then we don't need to worry
//about it again.
//
unsafe static bool InitTable() {
// Go to native side and get pointer to the native table
byte * pDataTable = GlobalizationAssembly.GetGlobalizationResourceBytePtr(typeof(CharUnicodeInfo).Assembly, UNICODE_INFO_FILE_NAME);
UnicodeDataHeader* mainHeader = (UnicodeDataHeader*)pDataTable;
// Set up the native pointer to different part of the tables.
s_pCategoryLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToCategoriesIndex);
s_pCategoriesValue = (byte*) (pDataTable + mainHeader->OffsetToCategoriesValue);
s_pNumericLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToNumbericIndex);
s_pNumericValues = (byte*) (pDataTable + mainHeader->OffsetToNumbericValue);
s_pDigitValues = (DigitValues*) (pDataTable + mainHeader->OffsetToDigitValue);
return true;
}
////////////////////////////////////////////////////////////////////////
//
// Actions:
// Convert the BMP character or surrogate pointed by index to a UTF32 value.
// This is similar to Char.ConvertToUTF32, but the difference is that
// it does not throw exceptions when invalid surrogate characters are passed in.
//
// WARNING: since it doesn't throw an exception it CAN return a value
// in the surrogate range D800-DFFF, which are not legal unicode values.
//
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index) {
Debug.Assert(s != null, "s != null");
Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
if (index < s.Length - 1) {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff) {
int temp2 = (int)s[index+1] - LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff) {
// Convert the surrogate to UTF32 and get the result.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
}
}
return ((int)s[index]);
}
////////////////////////////////////////////////////////////////////////
//
// Convert a character or a surrogate pair starting at index of string s
// to UTF32 value.
//
// Parameters:
// s The string
// index The starting index. It can point to a BMP character or
// a surrogate pair.
// len The length of the string.
// charLength [out] If the index points to a BMP char, charLength
// will be 1. If the index points to a surrogate pair,
// charLength will be 2.
//
// WARNING: since it doesn't throw an exception it CAN return a value
// in the surrogate range D800-DFFF, which are not legal unicode values.
//
// Returns:
// The UTF32 value
//
////////////////////////////////////////////////////////////////////////
internal static int InternalConvertToUtf32(String s, int index, out int charLength) {
Debug.Assert(s != null, "s != null");
Debug.Assert(s.Length > 0, "s.Length > 0");
Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
if (index < s.Length - 1) {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
if (temp1 >= 0 && temp1 <= 0x3ff) {
int temp2 = (int)s[index+1] - LOW_SURROGATE_START;
if (temp2 >= 0 && temp2 <= 0x3ff) {
// Convert the surrogate to UTF32 and get the result.
charLength++;
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
}
}
return ((int)s[index]);
}
////////////////////////////////////////////////////////////////////////
//
// IsWhiteSpace
//
// Determines if the given character is a white space character.
//
////////////////////////////////////////////////////////////////////////
internal static bool IsWhiteSpace(String s, int index)
{
Debug.Assert(s != null, "s!=null");
Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc) {
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
internal static bool IsWhiteSpace(char c)
{
UnicodeCategory uc = GetUnicodeCategory(c);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc) {
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
//
// This is called by the public char and string, index versions
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
internal unsafe static double InternalGetNumericValue(int ch) {
Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// The offset is referred to an float item in m_pNumericFloatData.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)];
byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]);
// Get the result from the 0 -3 bit of ch.
#if BIT64
// To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting
// at 4-byte boundary. This cause a alignment issue since double is 8-byte.
byte* pSourcePtr = &(s_pNumericValues[pBytePtr[(ch & 0x000f)] * sizeof(double)]);
if (((long)pSourcePtr % 8) != 0) {
// We are not aligned in 8-byte boundary. Do a copy.
double ret;
byte* retPtr = (byte*)&ret;
Buffer.Memcpy(retPtr, pSourcePtr, sizeof(double));
return (ret);
}
return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]);
#else
return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]);
#endif
}
//
// This is called by the public char and string, index versions
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
internal unsafe static DigitValues* InternalGetDigitValues(int ch) {
Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// The offset is referred to an float item in m_pNumericFloatData.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)];
byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]);
// Get the result from the 0 -3 bit of ch.
return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]);
}
internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) {
return (InternalGetDigitValues(ch)->decimalDigit);
}
internal unsafe static sbyte InternalGetDigitValue(int ch) {
return (InternalGetDigitValues(ch)->digit);
}
////////////////////////////////////////////////////////////////////////
//
//Returns the numeric value associated with the character c. If the character is a fraction,
// the return value will not be an integer. If the character does not have a numeric value, the return value is -1.
//
//Returns:
// the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1.
//Arguments:
// ch a Unicode character
//Exceptions:
// ArgumentNullException
// ArgumentOutOfRangeException
//
////////////////////////////////////////////////////////////////////////
public static double GetNumericValue(char ch) {
return (InternalGetNumericValue(ch));
}
public static double GetNumericValue(String s, int index) {
if (s == null) {
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
}
////////////////////////////////////////////////////////////////////////
//
//Returns the decimal digit value associated with the character c.
//
// The value should be from 0 ~ 9.
// If the character does not have a numeric value, the return value is -1.
// From Unicode.org: Decimal Digits. Digits that can be used to form decimal-radix numbers.
//Returns:
// the decimal digit value for the specified Unicode character. If the character does not have a decimal digit value, the return value is -1.
//Arguments:
// ch a Unicode character
//Exceptions:
// ArgumentNullException
// ArgumentOutOfRangeException
//
////////////////////////////////////////////////////////////////////////
public static int GetDecimalDigitValue(char ch) {
return (InternalGetDecimalDigitValue(ch));
}
public static int GetDecimalDigitValue(String s, int index) {
if (s == null) {
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (InternalGetDecimalDigitValue(InternalConvertToUtf32(s, index)));
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the digit value associated with the character c.
// If the character does not have a numeric value, the return value is -1.
// From Unicode.org: If the character represents a digit, not necessarily a decimal digit,
// the value is here. This covers digits which do not form decimal radix forms, such as the compatibility superscript digits.
//
// An example is: U+2460 IRCLED DIGIT ONE. This character has digit value 1, but does not have associcated decimal digit value.
//
//Returns:
// the digit value for the specified Unicode character. If the character does not have a digit value, the return value is -1.
//Arguments:
// ch a Unicode character
//Exceptions:
// ArgumentNullException
// ArgumentOutOfRangeException
//
////////////////////////////////////////////////////////////////////////
public static int GetDigitValue(char ch) {
return (InternalGetDigitValue(ch));
}
public static int GetDigitValue(String s, int index) {
if (s == null) {
throw new ArgumentNullException(nameof(s));
}
if (index < 0 || index >= s.Length) {
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
Contract.EndContractBlock();
return (InternalGetDigitValue(InternalConvertToUtf32(s, index)));
}
public static UnicodeCategory GetUnicodeCategory(char ch)
{
return (InternalGetUnicodeCategory(ch)) ;
}
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
if (s==null)
throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return InternalGetUnicodeCategory(s, index);
}
internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch) {
return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
//Returns:
// an value in UnicodeCategory enum
//Arguments:
// ch a Unicode character
//Exceptions:
// None
//
//Note that this API will return values for D800-DF00 surrogate halves.
//
////////////////////////////////////////////////////////////////////////
internal unsafe static byte InternalGetCategoryValue(int ch, int offset) {
Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)];
byte* pBytePtr = (byte*)&(s_pCategoryLevel1Index[index]);
// Get the result from the 0 -3 bit of ch.
byte valueIndex = pBytePtr[(ch & 0x000f)];
byte uc = s_pCategoriesValue[valueIndex * 2 + offset];
//
// Make sure that OtherNotAssigned is the last category in UnicodeCategory.
// If that changes, change the following assertion as well.
//
//Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
return (uc);
}
// internal static BidiCategory GetBidiCategory(char ch) {
// return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET));
// }
internal static BidiCategory GetBidiCategory(String s, int index) {
if (s==null)
throw new ArgumentNullException(nameof(s));
if (((uint)index)>=((uint)s.Length)) {
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return ((BidiCategory)InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET));
}
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
//Returns:
// an value in UnicodeCategory enum
//Arguments:
// value a Unicode String
// index Index for the specified string.
//Exceptions:
// None
//
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) {
Debug.Assert(value != null, "value can not be null");
Debug.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
////////////////////////////////////////////////////////////////////////
//
// Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1.
// If the character is a valid surrogate pair, charLength will return 2.
//
////////////////////////////////////////////////////////////////////////
internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) {
Debug.Assert(str != null, "str can not be null");
Debug.Assert(str.Length > 0, "str.Length > 0");;
Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
internal static bool IsCombiningCategory(UnicodeCategory uc) {
Debug.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
uc == UnicodeCategory.SpacingCombiningMark ||
uc == UnicodeCategory.EnclosingMark
);
}
}
}
| |
/*
* 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Provides a means of distributing output from enumerators from a dedicated separate thread
/// </summary>
public class BaseDataExchange
{
private int _sleepInterval = 1;
private volatile bool _isStopping = false;
private Func<Exception, bool> _isFatalError;
private readonly string _name;
private readonly ConcurrentDictionary<Symbol, DataHandler> _dataHandlers;
// using concurrent dictionary for fast/easy contains/remove, the int value is nothingness
private IReadOnlyList<EnumeratorHandler> _enumerators;
/// <summary>
/// Gets or sets how long this thread will sleep when no data is available
/// </summary>
public int SleepInterval
{
get { return _sleepInterval; }
set { if (value > -1) _sleepInterval = value; }
}
/// <summary>
/// Gets a name for this exchange
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseDataExchange"/>.
/// This constructor will exit the exchange when all enumerators are finished.
/// </summary>
/// <param name="enumerators">The enumerators to fanout</param>
public BaseDataExchange(params IEnumerator<BaseData>[] enumerators)
: this(string.Empty, enumerators)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BaseDataExchange"/>
/// </summary>
/// <param name="name">A name for this exchange</param>
/// <param name="enumerators">The enumerators to fanout</param>
public BaseDataExchange(string name, params IEnumerator<BaseData>[] enumerators)
{
_name = name;
_isFatalError = x => false;
_dataHandlers = new ConcurrentDictionary<Symbol, DataHandler>();
_enumerators = enumerators.Select(enumerator => new EnumeratorHandler(enumerator, () => true)).ToList();
}
/// <summary>
/// Adds the enumerator to this exchange. If it has already been added
/// then it will remain registered in the exchange only once
/// </summary>
/// <param name="handler">The handler to use when this symbol's data is encountered</param>
public void AddEnumerator(EnumeratorHandler handler)
{
var copy = _enumerators.ToList();
copy.Add(handler);
_enumerators = copy;
}
/// <summary>
/// Adds the enumerator to this exchange. If it has already been added
/// then it will remain registered in the exchange only once
/// </summary>
/// <param name="enumerator">The enumerator to be added</param>
/// <param name="shouldMoveNext">Function used to determine if move next should be called on this
/// enumerator, defaults to always returning true</param>
/// <param name="enumeratorFinished">Delegate called when the enumerator move next returns false</param>
public void AddEnumerator(IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<EnumeratorHandler> enumeratorFinished = null)
{
var enumeratorHandler = new EnumeratorHandler(enumerator, shouldMoveNext);
if (enumeratorFinished != null)
{
enumeratorHandler.EnumeratorFinished += (sender, args) => enumeratorFinished(args);
}
AddEnumerator(enumeratorHandler);
}
/// <summary>
/// Sets the specified function as the error handler. This function
/// returns true if it is a fatal error and queue consumption should
/// cease.
/// </summary>
/// <param name="isFatalError">The error handling function to use when an
/// error is encountered during queue consumption. Returns true if queue
/// consumption should be stopped, returns false if queue consumption should
/// continue</param>
public void SetErrorHandler(Func<Exception, bool> isFatalError)
{
// default to false;
_isFatalError = isFatalError ?? (x => false);
}
/// <summary>
/// Sets the specified hander function to handle data for the handler's symbol
/// </summary>
/// <param name="handler">The handler to use when this symbol's data is encountered</param>
/// <returns>An identifier that can be used to remove this handler</returns>
public void SetDataHandler(DataHandler handler)
{
_dataHandlers[handler.Symbol] = handler;
}
/// <summary>
/// Sets the specified hander function to handle data for the handler's symbol
/// </summary>
/// <param name="symbol">The symbol whose data is to be handled</param>
/// <param name="handler">The handler to use when this symbol's data is encountered</param>
/// <returns>An identifier that can be used to remove this handler</returns>
public void SetDataHandler(Symbol symbol, Action<BaseData> handler)
{
var dataHandler = new DataHandler(symbol);
dataHandler.DataEmitted += (sender, args) => handler(args);
SetDataHandler(dataHandler);
}
/// <summary>
/// Removes the handler with the specified identifier
/// </summary>
/// <param name="symbol">The symbol to remove handlers for</param>
public bool RemoveDataHandler(Symbol symbol)
{
DataHandler handler;
return _dataHandlers.TryRemove(symbol, out handler);
}
/// <summary>
/// Begins consumption of the wrapped <see cref="IDataQueueHandler"/> on
/// a separate thread
/// </summary>
/// <param name="token">A cancellation token used to signal to stop</param>
public void Start(CancellationToken? token = null)
{
_isStopping = false;
ConsumeEnumerators(token ?? CancellationToken.None);
}
/// <summary>
/// Ends consumption of the wrapped <see cref="IDataQueueHandler"/>
/// </summary>
public void Stop()
{
_isStopping = true;
}
/// <summary> Entry point for queue consumption </summary>
/// <param name="token">A cancellation token used to signal to stop</param>
/// <remarks> This function only returns after <see cref="Stop"/> is called or the token is cancelled</remarks>
private void ConsumeEnumerators(CancellationToken token)
{
while (true)
{
if (_isStopping || token.IsCancellationRequested)
{
_isStopping = true;
var request = token.IsCancellationRequested ? "Cancellation requested" : "Stop requested";
Log.Trace("BaseDataExchange({0}).ConsumeQueue(): {1}. Exiting...", Name, request);
return;
}
try
{
// call move next each enumerator and invoke the appropriate handlers
var handled = false;
foreach (var enumeratorHandler in _enumerators)
{
var enumerator = enumeratorHandler.Enumerator;
// check to see if we should advance this enumerator
if (!enumeratorHandler.ShouldMoveNext()) continue;
if (!enumerator.MoveNext())
{
enumeratorHandler.OnEnumeratorFinished();
// remove dead enumerators
var copy = _enumerators.ToList();
copy.Remove(enumeratorHandler);
_enumerators = copy;
continue;
}
if (enumerator.Current == null) continue;
// if the enumerator is configured to handle it, then do it, don't pass to data handlers
if (enumeratorHandler.HandlesData)
{
handled = true;
enumeratorHandler.HandleData(enumerator.Current);
continue;
}
// invoke the correct handler
DataHandler dataHandler;
if (_dataHandlers.TryGetValue(enumerator.Current.Symbol, out dataHandler))
{
handled = true;
dataHandler.OnDataEmitted(enumerator.Current);
}
}
// if we didn't handle anything on this past iteration, take a nap
if (!handled && _sleepInterval != 0)
{
Thread.Sleep(_sleepInterval);
}
}
catch (Exception err)
{
Log.Error(err);
if (_isFatalError(err))
{
Log.Trace("BaseDataExchange({0}).ConsumeQueue(): Fatal error encountered. Exiting...", Name);
return;
}
}
}
}
/// <summary>
/// Handler used to handle data emitted from enumerators
/// </summary>
public class DataHandler
{
/// <summary>
/// Event fired when MoveNext returns true and Current is non-null
/// </summary>
public event EventHandler<BaseData> DataEmitted;
/// <summary>
/// The symbol this handler handles
/// </summary>
public readonly Symbol Symbol;
/// <summary>
/// Initializes a new instance of the <see cref="DataHandler"/> class
/// </summary>
/// <param name="symbol">The symbol whose data is to be handled</param>
public DataHandler(Symbol symbol)
{
Symbol = symbol;
}
/// <summary>
/// Event invocator for the <see cref="DataEmitted"/> event
/// </summary>
/// <param name="data">The data being emitted</param>
public void OnDataEmitted(BaseData data)
{
var handler = DataEmitted;
if (handler != null) handler(this, data);
}
}
/// <summary>
/// Handler used to manage a single enumerator's move next/end of stream behavior
/// </summary>
public class EnumeratorHandler
{
private readonly Func<bool> _shouldMoveNext;
private readonly Action<BaseData> _handleData;
/// <summary>
/// Event fired when MoveNext returns false
/// </summary>
public event EventHandler<EnumeratorHandler> EnumeratorFinished;
/// <summary>
/// The enumerator this handler handles
/// </summary>
public readonly IEnumerator<BaseData> Enumerator;
/// <summary>
/// Determines whether or not this handler is to be used for handling the
/// data emitted. This is useful when enumerators are not for a single symbol,
/// such is the case with universe subscriptions
/// </summary>
public readonly bool HandlesData;
/// <summary>
/// Initializes a new instance of the <see cref="EnumeratorHandler"/> class
/// </summary>
/// <param name="enumerator">The enumeator this handler handles</param>
/// <param name="shouldMoveNext">Predicate function used to determine if we should call move next
/// on the symbol's enumerator</param>
/// <param name="handleData">Handler for data if HandlesData=true</param>
public EnumeratorHandler(IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<BaseData> handleData = null)
{
Enumerator = enumerator;
HandlesData = handleData != null;
_handleData = handleData ?? (data => { });
_shouldMoveNext = shouldMoveNext ?? (() => true);
}
/// <summary>
/// Initializes a new instance of the <see cref="EnumeratorHandler"/> class
/// </summary>
/// <param name="enumerator">The enumeator this handler handles</param>
/// <param name="handlesData">True if this handler will handle the data, false otherwise</param>
protected EnumeratorHandler(IEnumerator<BaseData> enumerator, bool handlesData)
{
HandlesData = handlesData;
Enumerator = enumerator;
_handleData = data => { };
_shouldMoveNext = () => true;
}
/// <summary>
/// Event invocator for the <see cref="EnumeratorFinished"/> event
/// </summary>
public virtual void OnEnumeratorFinished()
{
var handler = EnumeratorFinished;
if (handler != null) handler(this, this);
}
/// <summary>
/// Returns true if this enumerator should move next
/// </summary>
public virtual bool ShouldMoveNext()
{
return _shouldMoveNext();
}
/// <summary>
/// Handles the specified data.
/// </summary>
/// <param name="data">The data to be handled</param>
public virtual void HandleData(BaseData data)
{
_handleData(data);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DCalc.Communication;
namespace DCalc.UI
{
/// <summary>
/// Server edit dialog.
/// </summary>
public partial class EditServerForm : Form
{
#region Public Static Methods
/// <summary>
/// Creates a new entry server entry giving a UI dialog.
/// </summary>
/// <returns></returns>
public static IServer CreateServerEntry()
{
EditServerForm form = new EditServerForm();
form.cbbType.SelectedIndex = 0;
if (form.ShowDialog() == DialogResult.OK)
{
/* Gather the info form the form into the resulting object */
return new RemoteServer(form.edtServerName.Text, form.edtServerHost.Text,
Convert.ToInt32(form.edServerPort.Text), form.edtSecurityKey.Text, (ConnectionType)form.cbbType.SelectedIndex, form.cbIsEnabled.Checked);
}
else
return null;
}
/// <summary>
/// Edits a server entry using edit dialog.
/// </summary>
/// <param name="server">The server.</param>
/// <returns></returns>
public static IServer EditServerEntry(IServer server)
{
EditServerForm form = new EditServerForm();
if (!(server is RemoteServer))
{
/* Unsupported server type */
return null;
}
RemoteServer rServer = (RemoteServer)server;
form.edtServerName.Text = rServer.Name;
form.edtServerHost.Text = rServer.Host;
form.edServerPort.Text = rServer.Port.ToString();
form.cbIsEnabled.Checked = rServer.Enabled;
form.edtSecurityKey.Text = rServer.SecurityKey;
form.cbbType.SelectedIndex = (Int32)rServer.ConnectionType;
if (rServer.SecurityKey != null && rServer.SecurityKey.Length > 0)
form.cbSecure.Checked = true;
if (form.ShowDialog() == DialogResult.OK)
{
/* Gather the info form the form into the resulting object */
rServer.Name = form.edtServerName.Text;
rServer.Host = form.edtServerHost.Text;
rServer.Port = Convert.ToInt32(form.edServerPort.Text);
rServer.Enabled = form.cbIsEnabled.Checked;
rServer.ConnectionType = (ConnectionType)form.cbbType.SelectedIndex;
if (form.cbSecure.Checked)
rServer.SecurityKey = form.edtSecurityKey.Text;
else
rServer.SecurityKey = null;
return rServer;
}
else
return null;
}
#endregion
#region Private Methods
/// <summary>
/// Controls the UI changes.
/// </summary>
private void ControlUIChanges()
{
Boolean enable = true;
if (edtServerName.TextLength == 0 || edtServerHost.TextLength == 0 || edServerPort.TextLength == 0)
{
enable = false;
}
if (cbSecure.Checked && edtSecurityKey.TextLength == 0)
{
enable = false;
}
try
{
Convert.ToUInt32(edServerPort.Text);
}
catch
{
enable = false;
}
btAccept.Enabled = enable;
edtSecurityKey.Enabled = cbSecure.Checked;
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="EditServerForm"/> class.
/// </summary>
private EditServerForm()
{
InitializeComponent();
/* Fill in the cbb */
cbbType.Items.Add("HTTP (Hyper Text Transfer Protocol)");
cbbType.Items.Add("TCP (Transmission Control Protocol)");
/* Control */
ControlUIChanges();
}
#endregion
#region UI Events
/// <summary>
/// Handles the Click event of the btAccept control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btAccept_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
}
/// <summary>
/// Handles the Click event of the btCancel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void btCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
/// <summary>
/// Handles the TextChanged event of all text controls.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void text_TextChanged(object sender, EventArgs e)
{
ControlUIChanges();
}
/// <summary>
/// Handles the KeyPress event of all text control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.KeyPressEventArgs"/> instance containing the event data.</param>
private void control_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
btCancel_Click(btCancel, e);
if (e.KeyChar == '\r')
{
if (btAccept.Enabled)
btAccept_Click(btAccept, e);
}
}
/// <summary>
/// Handles the CheckedChanged event of the cbSecure control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void cbSecure_CheckedChanged(object sender, EventArgs e)
{
ControlUIChanges();
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.CloudFront.Model
{
/// <summary>
/// <para> A distribution. </para>
/// </summary>
public class Distribution
{
private string id;
private string status;
private DateTime? lastModifiedTime;
private int? inProgressInvalidationBatches;
private string domainName;
private ActiveTrustedSigners activeTrustedSigners;
private DistributionConfig distributionConfig;
/// <summary>
/// The identifier for the distribution. For example: EDFDVBD632BHDS5.
///
/// </summary>
public string Id
{
get { return this.id; }
set { this.id = value; }
}
/// <summary>
/// Sets the Id property
/// </summary>
/// <param name="id">The value to set for the Id property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithId(string id)
{
this.id = id;
return this;
}
// Check to see if Id property is set
internal bool IsSetId()
{
return this.id != null;
}
/// <summary>
/// This response element indicates the current status of the distribution. When the status is Deployed, the distribution's information is fully
/// propagated throughout the Amazon CloudFront system.
///
/// </summary>
public string Status
{
get { return this.status; }
set { this.status = value; }
}
/// <summary>
/// Sets the Status property
/// </summary>
/// <param name="status">The value to set for the Status property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithStatus(string status)
{
this.status = status;
return this;
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this.status != null;
}
/// <summary>
/// The date and time the distribution was last modified.
///
/// </summary>
public DateTime LastModifiedTime
{
get { return this.lastModifiedTime ?? default(DateTime); }
set { this.lastModifiedTime = value; }
}
/// <summary>
/// Sets the LastModifiedTime property
/// </summary>
/// <param name="lastModifiedTime">The value to set for the LastModifiedTime property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithLastModifiedTime(DateTime lastModifiedTime)
{
this.lastModifiedTime = lastModifiedTime;
return this;
}
// Check to see if LastModifiedTime property is set
internal bool IsSetLastModifiedTime()
{
return this.lastModifiedTime.HasValue;
}
/// <summary>
/// The number of invalidation batches currently in progress.
///
/// </summary>
public int InProgressInvalidationBatches
{
get { return this.inProgressInvalidationBatches ?? default(int); }
set { this.inProgressInvalidationBatches = value; }
}
/// <summary>
/// Sets the InProgressInvalidationBatches property
/// </summary>
/// <param name="inProgressInvalidationBatches">The value to set for the InProgressInvalidationBatches property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithInProgressInvalidationBatches(int inProgressInvalidationBatches)
{
this.inProgressInvalidationBatches = inProgressInvalidationBatches;
return this;
}
// Check to see if InProgressInvalidationBatches property is set
internal bool IsSetInProgressInvalidationBatches()
{
return this.inProgressInvalidationBatches.HasValue;
}
/// <summary>
/// The domain name corresponding to the distribution. For example: d604721fxaaqy9.cloudfront.net.
///
/// </summary>
public string DomainName
{
get { return this.domainName; }
set { this.domainName = value; }
}
/// <summary>
/// Sets the DomainName property
/// </summary>
/// <param name="domainName">The value to set for the DomainName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithDomainName(string domainName)
{
this.domainName = domainName;
return this;
}
// Check to see if DomainName property is set
internal bool IsSetDomainName()
{
return this.domainName != null;
}
/// <summary>
/// CloudFront automatically adds this element to the response only if you've set up the distribution to serve private content with signed URLs.
/// The element lists the key pair IDs that CloudFront is aware of for each trusted signer. The Signer child element lists the AWS account
/// number of the trusted signer (or an empty Self element if the signer is you). The Signer element also includes the IDs of any active key
/// pairs associated with the trusted signer's AWS account. If no KeyPairId element appears for a Signer, that signer can't create working
/// signed URLs.
///
/// </summary>
public ActiveTrustedSigners ActiveTrustedSigners
{
get { return this.activeTrustedSigners; }
set { this.activeTrustedSigners = value; }
}
/// <summary>
/// Sets the ActiveTrustedSigners property
/// </summary>
/// <param name="activeTrustedSigners">The value to set for the ActiveTrustedSigners property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithActiveTrustedSigners(ActiveTrustedSigners activeTrustedSigners)
{
this.activeTrustedSigners = activeTrustedSigners;
return this;
}
// Check to see if ActiveTrustedSigners property is set
internal bool IsSetActiveTrustedSigners()
{
return this.activeTrustedSigners != null;
}
/// <summary>
/// The current configuration information for the distribution.
///
/// </summary>
public DistributionConfig DistributionConfig
{
get { return this.distributionConfig; }
set { this.distributionConfig = value; }
}
/// <summary>
/// Sets the DistributionConfig property
/// </summary>
/// <param name="distributionConfig">The value to set for the DistributionConfig property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public Distribution WithDistributionConfig(DistributionConfig distributionConfig)
{
this.distributionConfig = distributionConfig;
return this;
}
// Check to see if DistributionConfig property is set
internal bool IsSetDistributionConfig()
{
return this.distributionConfig != null;
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol.Entities;
using Thrift.Protocol.Utilities;
using Thrift.Transport;
namespace Thrift.Protocol
{
/// <summary>
/// JSON protocol implementation for thrift.
/// This is a full-featured protocol supporting Write and Read.
/// Please see the C++ class header for a detailed description of the
/// protocol's wire format.
/// Adapted from the Java version.
/// </summary>
// ReSharper disable once InconsistentNaming
public class TJsonProtocol : TProtocol
{
private const long Version = 1;
// Temporary buffer used by several methods
private readonly byte[] _tempBuffer = new byte[4];
// Current context that we are in
protected JSONBaseContext Context;
// Stack of nested contexts that we may be in
protected Stack<JSONBaseContext> ContextStack = new Stack<JSONBaseContext>();
// Reader that manages a 1-byte buffer
protected LookaheadReader Reader;
// Default encoding
protected Encoding Utf8Encoding = Encoding.UTF8;
/// <summary>
/// TJsonProtocol Constructor
/// </summary>
public TJsonProtocol(TTransport trans)
: base(trans)
{
Context = new JSONBaseContext(this);
Reader = new LookaheadReader(this);
}
/// <summary>
/// Push a new JSON context onto the stack.
/// </summary>
protected void PushContext(JSONBaseContext c)
{
ContextStack.Push(Context);
Context = c;
}
/// <summary>
/// Pop the last JSON context off the stack
/// </summary>
protected void PopContext()
{
Context = ContextStack.Pop();
}
/// <summary>
/// Resets the context stack to pristine state. Allows for reusal of the protocol
/// even in cases where the protocol instance was in an undefined state due to
/// dangling/stale/obsolete contexts
/// </summary>
private void ResetContext()
{
ContextStack.Clear();
Context = new JSONBaseContext(this);
}
/// <summary>
/// Read a byte that must match b[0]; otherwise an exception is thrown.
/// Marked protected to avoid synthetic accessor in JSONListContext.Read
/// and JSONPairContext.Read
/// </summary>
protected async Task ReadJsonSyntaxCharAsync(byte[] bytes, CancellationToken cancellationToken)
{
var ch = await Reader.ReadAsync(cancellationToken);
if (ch != bytes[0])
{
throw new TProtocolException(TProtocolException.INVALID_DATA, $"Unexpected character: {(char) ch}");
}
}
/// <summary>
/// Write the bytes in array buf as a JSON characters, escaping as needed
/// </summary>
private async Task WriteJsonStringAsync(byte[] bytes, CancellationToken cancellationToken)
{
await Context.WriteConditionalDelimiterAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
var len = bytes.Length;
for (var i = 0; i < len; i++)
{
if ((bytes[i] & 0x00FF) >= 0x30)
{
if (bytes[i] == TJSONProtocolConstants.Backslash[0])
{
await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
}
else
{
await Trans.WriteAsync(bytes, i, 1, cancellationToken);
}
}
else
{
_tempBuffer[0] = TJSONProtocolConstants.JsonCharTable[bytes[i]];
if (_tempBuffer[0] == 1)
{
await Trans.WriteAsync(bytes, i, 1, cancellationToken);
}
else if (_tempBuffer[0] > 1)
{
await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken);
await Trans.WriteAsync(_tempBuffer, 0, 1, cancellationToken);
}
else
{
await Trans.WriteAsync(TJSONProtocolConstants.EscSequences, cancellationToken);
_tempBuffer[0] = TJSONProtocolHelper.ToHexChar((byte) (bytes[i] >> 4));
_tempBuffer[1] = TJSONProtocolHelper.ToHexChar(bytes[i]);
await Trans.WriteAsync(_tempBuffer, 0, 2, cancellationToken);
}
}
}
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
/// <summary>
/// Write out number as a JSON value. If the context dictates so, it will be
/// wrapped in quotes to output as a JSON string.
/// </summary>
private async Task WriteJsonIntegerAsync(long num, CancellationToken cancellationToken)
{
await Context.WriteConditionalDelimiterAsync(cancellationToken);
var str = num.ToString();
var escapeNum = Context.EscapeNumbers();
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
var bytes = Utf8Encoding.GetBytes(str);
await Trans.WriteAsync(bytes, cancellationToken);
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
}
/// <summary>
/// Write out a double as a JSON value. If it is NaN or infinity or if the
/// context dictates escaping, Write out as JSON string.
/// </summary>
private async Task WriteJsonDoubleAsync(double num, CancellationToken cancellationToken)
{
await Context.WriteConditionalDelimiterAsync(cancellationToken);
var str = num.ToString("G17", CultureInfo.InvariantCulture);
var special = false;
switch (str[0])
{
case 'N': // NaN
case 'I': // Infinity
special = true;
break;
case '-':
if (str[1] == 'I')
{
// -Infinity
special = true;
}
break;
}
var escapeNum = special || Context.EscapeNumbers();
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
await Trans.WriteAsync(Utf8Encoding.GetBytes(str), cancellationToken);
if (escapeNum)
{
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
}
/// <summary>
/// Write out contents of byte array b as a JSON string with base-64 encoded
/// data
/// </summary>
private async Task WriteJsonBase64Async(byte[] bytes, CancellationToken cancellationToken)
{
await Context.WriteConditionalDelimiterAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
var len = bytes.Length;
var off = 0;
while (len >= 3)
{
// Encode 3 bytes at a time
TBase64Utils.Encode(bytes, off, 3, _tempBuffer, 0);
await Trans.WriteAsync(_tempBuffer, 0, 4, cancellationToken);
off += 3;
len -= 3;
}
if (len > 0)
{
// Encode remainder
TBase64Utils.Encode(bytes, off, len, _tempBuffer, 0);
await Trans.WriteAsync(_tempBuffer, 0, len + 1, cancellationToken);
}
await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
private async Task WriteJsonObjectStartAsync(CancellationToken cancellationToken)
{
await Context.WriteConditionalDelimiterAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.LeftBrace, cancellationToken);
PushContext(new JSONPairContext(this));
}
private async Task WriteJsonObjectEndAsync(CancellationToken cancellationToken)
{
PopContext();
await Trans.WriteAsync(TJSONProtocolConstants.RightBrace, cancellationToken);
}
private async Task WriteJsonArrayStartAsync(CancellationToken cancellationToken)
{
await Context.WriteConditionalDelimiterAsync(cancellationToken);
await Trans.WriteAsync(TJSONProtocolConstants.LeftBracket, cancellationToken);
PushContext(new JSONListContext(this));
}
private async Task WriteJsonArrayEndAsync(CancellationToken cancellationToken)
{
PopContext();
await Trans.WriteAsync(TJSONProtocolConstants.RightBracket, cancellationToken);
}
public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken)
{
ResetContext();
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonIntegerAsync(Version, cancellationToken);
var b = Utf8Encoding.GetBytes(message.Name);
await WriteJsonStringAsync(b, cancellationToken);
await WriteJsonIntegerAsync((long) message.Type, cancellationToken);
await WriteJsonIntegerAsync(message.SeqID, cancellationToken);
}
public override async Task WriteMessageEndAsync(CancellationToken cancellationToken)
{
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken)
{
await WriteJsonObjectStartAsync(cancellationToken);
}
public override async Task WriteStructEndAsync(CancellationToken cancellationToken)
{
await WriteJsonObjectEndAsync(cancellationToken);
}
public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(field.ID, cancellationToken);
await WriteJsonObjectStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(field.Type), cancellationToken);
}
public override async Task WriteFieldEndAsync(CancellationToken cancellationToken)
{
await WriteJsonObjectEndAsync(cancellationToken);
}
public override Task WriteFieldStopAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.KeyType), cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.ValueType), cancellationToken);
await WriteJsonIntegerAsync(map.Count, cancellationToken);
await WriteJsonObjectStartAsync(cancellationToken);
}
public override async Task WriteMapEndAsync(CancellationToken cancellationToken)
{
await WriteJsonObjectEndAsync(cancellationToken);
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(list.ElementType), cancellationToken);
await WriteJsonIntegerAsync(list.Count, cancellationToken);
}
public override async Task WriteListEndAsync(CancellationToken cancellationToken)
{
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken)
{
await WriteJsonArrayStartAsync(cancellationToken);
await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(set.ElementType), cancellationToken);
await WriteJsonIntegerAsync(set.Count, cancellationToken);
}
public override async Task WriteSetEndAsync(CancellationToken cancellationToken)
{
await WriteJsonArrayEndAsync(cancellationToken);
}
public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(b ? 1 : 0, cancellationToken);
}
public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(b, cancellationToken);
}
public override async Task WriteI16Async(short i16, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(i16, cancellationToken);
}
public override async Task WriteI32Async(int i32, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(i32, cancellationToken);
}
public override async Task WriteI64Async(long i64, CancellationToken cancellationToken)
{
await WriteJsonIntegerAsync(i64, cancellationToken);
}
public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken)
{
await WriteJsonDoubleAsync(d, cancellationToken);
}
public override async Task WriteStringAsync(string s, CancellationToken cancellationToken)
{
var b = Utf8Encoding.GetBytes(s);
await WriteJsonStringAsync(b, cancellationToken);
}
public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken)
{
await WriteJsonBase64Async(bytes, cancellationToken);
}
/// <summary>
/// Read in a JSON string, unescaping as appropriate.. Skip Reading from the
/// context if skipContext is true.
/// </summary>
private async ValueTask<byte[]> ReadJsonStringAsync(bool skipContext, CancellationToken cancellationToken)
{
using (var buffer = new MemoryStream())
{
var codeunits = new List<char>();
if (!skipContext)
{
await Context.ReadConditionalDelimiterAsync(cancellationToken);
}
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
while (true)
{
var ch = await Reader.ReadAsync(cancellationToken);
if (ch == TJSONProtocolConstants.Quote[0])
{
break;
}
// escaped?
if (ch != TJSONProtocolConstants.EscSequences[0])
{
#if NETSTANDARD2_0
await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken);
#else
var wbuf = new[] { ch };
await buffer.WriteAsync(wbuf.AsMemory(0, 1), cancellationToken);
#endif
continue;
}
// distinguish between \uXXXX and \?
ch = await Reader.ReadAsync(cancellationToken);
if (ch != TJSONProtocolConstants.EscSequences[1]) // control chars like \n
{
var off = Array.IndexOf(TJSONProtocolConstants.EscapeChars, (char) ch);
if (off == -1)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char");
}
ch = TJSONProtocolConstants.EscapeCharValues[off];
#if NETSTANDARD2_0
await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken);
#else
var wbuf = new[] { ch };
await buffer.WriteAsync( wbuf.AsMemory(0, 1), cancellationToken);
#endif
continue;
}
// it's \uXXXX
await Trans.ReadAllAsync(_tempBuffer, 0, 4, cancellationToken);
var wch = (short) ((TJSONProtocolHelper.ToHexVal(_tempBuffer[0]) << 12) +
(TJSONProtocolHelper.ToHexVal(_tempBuffer[1]) << 8) +
(TJSONProtocolHelper.ToHexVal(_tempBuffer[2]) << 4) +
TJSONProtocolHelper.ToHexVal(_tempBuffer[3]));
if (char.IsHighSurrogate((char) wch))
{
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char");
}
codeunits.Add((char) wch);
}
else if (char.IsLowSurrogate((char) wch))
{
if (codeunits.Count == 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected high surrogate char");
}
codeunits.Add((char) wch);
var tmp = Utf8Encoding.GetBytes(codeunits.ToArray());
#if NETSTANDARD2_0
await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken);
#else
await buffer.WriteAsync(tmp.AsMemory(0, tmp.Length), cancellationToken);
#endif
codeunits.Clear();
}
else
{
var tmp = Utf8Encoding.GetBytes(new[] { (char)wch });
#if NETSTANDARD2_0
await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken);
#else
await buffer.WriteAsync(tmp.AsMemory( 0, tmp.Length), cancellationToken);
#endif
}
}
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char");
}
return buffer.ToArray();
}
}
/// <summary>
/// Read in a sequence of characters that are all valid in JSON numbers. Does
/// not do a complete regex check to validate that this is actually a number.
/// </summary>
private async ValueTask<string> ReadJsonNumericCharsAsync(CancellationToken cancellationToken)
{
var strbld = new StringBuilder();
while (true)
{
//TODO: workaround for primitive types with TJsonProtocol, think - how to rewrite into more easy form without exceptions
try
{
var ch = await Reader.PeekAsync(cancellationToken);
if (!TJSONProtocolHelper.IsJsonNumeric(ch))
{
break;
}
var c = (char)await Reader.ReadAsync(cancellationToken);
strbld.Append(c);
}
catch (TTransportException)
{
break;
}
}
return strbld.ToString();
}
/// <summary>
/// Read in a JSON number. If the context dictates, Read in enclosing quotes.
/// </summary>
private async ValueTask<long> ReadJsonIntegerAsync(CancellationToken cancellationToken)
{
await Context.ReadConditionalDelimiterAsync(cancellationToken);
if (Context.EscapeNumbers())
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
var str = await ReadJsonNumericCharsAsync(cancellationToken);
if (Context.EscapeNumbers())
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
try
{
return long.Parse(str);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data");
}
}
/// <summary>
/// Read in a JSON double value. Throw if the value is not wrapped in quotes
/// when expected or if wrapped in quotes when not expected.
/// </summary>
private async ValueTask<double> ReadJsonDoubleAsync(CancellationToken cancellationToken)
{
await Context.ReadConditionalDelimiterAsync(cancellationToken);
if (await Reader.PeekAsync(cancellationToken) == TJSONProtocolConstants.Quote[0])
{
var arr = await ReadJsonStringAsync(true, cancellationToken);
var dub = double.Parse(Utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture);
if (!Context.EscapeNumbers() && !double.IsNaN(dub) && !double.IsInfinity(dub))
{
// Throw exception -- we should not be in a string in this case
throw new TProtocolException(TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted");
}
return dub;
}
if (Context.EscapeNumbers())
{
// This will throw - we should have had a quote if escapeNum == true
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken);
}
try
{
return double.Parse(await ReadJsonNumericCharsAsync(cancellationToken), CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data");
}
}
/// <summary>
/// Read in a JSON string containing base-64 encoded data and decode it.
/// </summary>
private async ValueTask<byte[]> ReadJsonBase64Async(CancellationToken cancellationToken)
{
var b = await ReadJsonStringAsync(false, cancellationToken);
var len = b.Length;
var off = 0;
var size = 0;
// reduce len to ignore fill bytes
while ((len > 0) && (b[len - 1] == '='))
{
--len;
}
// read & decode full byte triplets = 4 source bytes
while (len > 4)
{
// Decode 4 bytes at a time
TBase64Utils.Decode(b, off, 4, b, size); // NB: decoded in place
off += 4;
len -= 4;
size += 3;
}
// Don't decode if we hit the end or got a single leftover byte (invalid
// base64 but legal for skip of regular string exType)
if (len > 1)
{
// Decode remainder
TBase64Utils.Decode(b, off, len, b, size); // NB: decoded in place
size += len - 1;
}
// Sadly we must copy the byte[] (any way around this?)
var result = new byte[size];
Array.Copy(b, 0, result, 0, size);
return result;
}
private async Task ReadJsonObjectStartAsync(CancellationToken cancellationToken)
{
await Context.ReadConditionalDelimiterAsync(cancellationToken);
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBrace, cancellationToken);
PushContext(new JSONPairContext(this));
}
private async Task ReadJsonObjectEndAsync(CancellationToken cancellationToken)
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBrace, cancellationToken);
PopContext();
}
private async Task ReadJsonArrayStartAsync(CancellationToken cancellationToken)
{
await Context.ReadConditionalDelimiterAsync(cancellationToken);
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBracket, cancellationToken);
PushContext(new JSONListContext(this));
}
private async Task ReadJsonArrayEndAsync(CancellationToken cancellationToken)
{
await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBracket, cancellationToken);
PopContext();
}
public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken)
{
var message = new TMessage();
ResetContext();
await ReadJsonArrayStartAsync(cancellationToken);
if (await ReadJsonIntegerAsync(cancellationToken) != Version)
{
throw new TProtocolException(TProtocolException.BAD_VERSION, "Message contained bad version.");
}
var buf = await ReadJsonStringAsync(false, cancellationToken);
message.Name = Utf8Encoding.GetString(buf, 0, buf.Length);
message.Type = (TMessageType) await ReadJsonIntegerAsync(cancellationToken);
message.SeqID = (int) await ReadJsonIntegerAsync(cancellationToken);
return message;
}
public override async Task ReadMessageEndAsync(CancellationToken cancellationToken)
{
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectStartAsync(cancellationToken);
return AnonymousStruct;
}
public override async Task ReadStructEndAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectEndAsync(cancellationToken);
}
public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken)
{
var ch = await Reader.PeekAsync(cancellationToken);
if (ch == TJSONProtocolConstants.RightBrace[0])
{
return StopField;
}
var field = new TField()
{
ID = (short)await ReadJsonIntegerAsync(cancellationToken)
};
await ReadJsonObjectStartAsync(cancellationToken);
field.Type = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
return field;
}
public override async Task ReadFieldEndAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectEndAsync(cancellationToken);
}
public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken)
{
var map = new TMap();
await ReadJsonArrayStartAsync(cancellationToken);
map.KeyType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
map.ValueType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
map.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
CheckReadBytesAvailable(map);
await ReadJsonObjectStartAsync(cancellationToken);
return map;
}
public override async Task ReadMapEndAsync(CancellationToken cancellationToken)
{
await ReadJsonObjectEndAsync(cancellationToken);
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken)
{
var list = new TList();
await ReadJsonArrayStartAsync(cancellationToken);
list.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
list.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
CheckReadBytesAvailable(list);
return list;
}
public override async Task ReadListEndAsync(CancellationToken cancellationToken)
{
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken)
{
var set = new TSet();
await ReadJsonArrayStartAsync(cancellationToken);
set.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken));
set.Count = (int) await ReadJsonIntegerAsync(cancellationToken);
CheckReadBytesAvailable(set);
return set;
}
public override async Task ReadSetEndAsync(CancellationToken cancellationToken)
{
await ReadJsonArrayEndAsync(cancellationToken);
}
public override async ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken)
{
return await ReadJsonIntegerAsync(cancellationToken) != 0;
}
public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken)
{
return (sbyte) await ReadJsonIntegerAsync(cancellationToken);
}
public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken)
{
return (short) await ReadJsonIntegerAsync(cancellationToken);
}
public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken)
{
return (int) await ReadJsonIntegerAsync(cancellationToken);
}
public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken)
{
return await ReadJsonIntegerAsync(cancellationToken);
}
public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken)
{
return await ReadJsonDoubleAsync(cancellationToken);
}
public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken)
{
var buf = await ReadJsonStringAsync(false, cancellationToken);
return Utf8Encoding.GetString(buf, 0, buf.Length);
}
public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken)
{
return await ReadJsonBase64Async(cancellationToken);
}
// Return the minimum number of bytes a type will consume on the wire
public override int GetMinSerializedSize(TType type)
{
switch (type)
{
case TType.Stop: return 0;
case TType.Void: return 0;
case TType.Bool: return 1; // written as int
case TType.Byte: return 1;
case TType.Double: return 1;
case TType.I16: return 1;
case TType.I32: return 1;
case TType.I64: return 1;
case TType.String: return 2; // empty string
case TType.Struct: return 2; // empty struct
case TType.Map: return 2; // empty map
case TType.Set: return 2; // empty set
case TType.List: return 2; // empty list
default: throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED, "unrecognized type code");
}
}
/// <summary>
/// Factory for JSON protocol objects
/// </summary>
public class Factory : TProtocolFactory
{
public override TProtocol GetProtocol(TTransport trans)
{
return new TJsonProtocol(trans);
}
}
/// <summary>
/// Base class for tracking JSON contexts that may require
/// inserting/Reading additional JSON syntax characters
/// This base context does nothing.
/// </summary>
protected class JSONBaseContext
{
protected TJsonProtocol Proto;
public JSONBaseContext(TJsonProtocol proto)
{
Proto = proto;
}
public virtual Task WriteConditionalDelimiterAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public virtual Task ReadConditionalDelimiterAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
public virtual bool EscapeNumbers()
{
return false;
}
}
/// <summary>
/// Context for JSON lists. Will insert/Read commas before each item except
/// for the first one
/// </summary>
protected class JSONListContext : JSONBaseContext
{
private bool _first = true;
public JSONListContext(TJsonProtocol protocol)
: base(protocol)
{
}
public override async Task WriteConditionalDelimiterAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
}
else
{
await Proto.Trans.WriteAsync(TJSONProtocolConstants.Comma, cancellationToken);
}
}
public override async Task ReadConditionalDelimiterAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
}
else
{
await Proto.ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Comma, cancellationToken);
}
}
}
/// <summary>
/// Context for JSON records. Will insert/Read colons before the value portion
/// of each record pair, and commas before each key except the first. In
/// addition, will indicate that numbers in the key position need to be
/// escaped in quotes (since JSON keys must be strings).
/// </summary>
// ReSharper disable once InconsistentNaming
protected class JSONPairContext : JSONBaseContext
{
private bool _colon = true;
private bool _first = true;
public JSONPairContext(TJsonProtocol proto)
: base(proto)
{
}
public override async Task WriteConditionalDelimiterAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
_colon = true;
}
else
{
await Proto.Trans.WriteAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken);
_colon = !_colon;
}
}
public override async Task ReadConditionalDelimiterAsync(CancellationToken cancellationToken)
{
if (_first)
{
_first = false;
_colon = true;
}
else
{
await Proto.ReadJsonSyntaxCharAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken);
_colon = !_colon;
}
}
public override bool EscapeNumbers()
{
return _colon;
}
}
/// <summary>
/// Holds up to one byte from the transport
/// </summary>
protected class LookaheadReader
{
private readonly byte[] _data = new byte[1];
private bool _hasData;
protected TJsonProtocol Proto;
public LookaheadReader(TJsonProtocol proto)
{
Proto = proto;
}
/// <summary>
/// Return and consume the next byte to be Read, either taking it from the
/// data buffer if present or getting it from the transport otherwise.
/// </summary>
public async ValueTask<byte> ReadAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (_hasData)
{
_hasData = false;
}
else
{
// find more easy way to avoid exception on reading primitive types
await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken);
}
return _data[0];
}
/// <summary>
/// Return the next byte to be Read without consuming, filling the data
/// buffer if it has not been filled alReady.
/// </summary>
public async ValueTask<byte> PeekAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (!_hasData)
{
// find more easy way to avoid exception on reading primitive types
await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken);
_hasData = true;
}
return _data[0];
}
}
}
}
| |
// 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.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Logging;
using osu.Game;
using osu.Game.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.Notifications;
using osuTK;
using osuTK.Graphics;
using Squirrel;
using LogLevel = Splat.LogLevel;
namespace osu.Desktop.Updater
{
public class SquirrelUpdateManager : osu.Game.Updater.UpdateManager
{
private UpdateManager updateManager;
private NotificationOverlay notificationOverlay;
public Task PrepareUpdateAsync() => UpdateManager.RestartAppWhenExited();
private static readonly Logger logger = Logger.GetLogger("updater");
/// <summary>
/// Whether an update has been downloaded but not yet applied.
/// </summary>
private bool updatePending;
[BackgroundDependencyLoader]
private void load(NotificationOverlay notification)
{
notificationOverlay = notification;
Splat.Locator.CurrentMutable.Register(() => new SquirrelLogger(), typeof(Splat.ILogger));
}
protected override async Task<bool> PerformUpdateCheck() => await checkForUpdateAsync().ConfigureAwait(false);
private async Task<bool> checkForUpdateAsync(bool useDeltaPatching = true, UpdateProgressNotification notification = null)
{
// should we schedule a retry on completion of this check?
bool scheduleRecheck = true;
try
{
updateManager ??= await UpdateManager.GitHubUpdateManager(@"https://github.com/ppy/osu", @"osulazer", null, null, true).ConfigureAwait(false);
var info = await updateManager.CheckForUpdate(!useDeltaPatching).ConfigureAwait(false);
if (info.ReleasesToApply.Count == 0)
{
if (updatePending)
{
// the user may have dismissed the completion notice, so show it again.
notificationOverlay.Post(new UpdateCompleteNotification(this));
return true;
}
// no updates available. bail and retry later.
return false;
}
scheduleRecheck = false;
if (notification == null)
{
notification = new UpdateProgressNotification(this) { State = ProgressNotificationState.Active };
Schedule(() => notificationOverlay.Post(notification));
}
notification.Progress = 0;
notification.Text = @"Downloading update...";
try
{
await updateManager.DownloadReleases(info.ReleasesToApply, p => notification.Progress = p / 100f).ConfigureAwait(false);
notification.Progress = 0;
notification.Text = @"Installing update...";
await updateManager.ApplyReleases(info, p => notification.Progress = p / 100f).ConfigureAwait(false);
notification.State = ProgressNotificationState.Completed;
updatePending = true;
}
catch (Exception e)
{
if (useDeltaPatching)
{
logger.Add(@"delta patching failed; will attempt full download!");
// could fail if deltas are unavailable for full update path (https://github.com/Squirrel/Squirrel.Windows/issues/959)
// try again without deltas.
await checkForUpdateAsync(false, notification).ConfigureAwait(false);
}
else
{
// In the case of an error, a separate notification will be displayed.
notification.State = ProgressNotificationState.Cancelled;
notification.Close();
Logger.Error(e, @"update failed!");
}
}
}
catch (Exception)
{
// we'll ignore this and retry later. can be triggered by no internet connection or thread abortion.
scheduleRecheck = true;
}
finally
{
if (scheduleRecheck)
{
// check again in 30 minutes.
Scheduler.AddDelayed(() => Task.Run(async () => await checkForUpdateAsync().ConfigureAwait(false)), 60000 * 30);
}
}
return true;
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
updateManager?.Dispose();
}
private class UpdateCompleteNotification : ProgressCompletionNotification
{
[Resolved]
private OsuGame game { get; set; }
public UpdateCompleteNotification(SquirrelUpdateManager updateManager)
{
Text = @"Update ready to install. Click to restart!";
Activated = () =>
{
updateManager.PrepareUpdateAsync()
.ContinueWith(_ => updateManager.Schedule(() => game?.GracefullyExit()));
return true;
};
}
}
private class UpdateProgressNotification : ProgressNotification
{
private readonly SquirrelUpdateManager updateManager;
public UpdateProgressNotification(SquirrelUpdateManager updateManager)
{
this.updateManager = updateManager;
}
protected override Notification CreateCompletionNotification()
{
return new UpdateCompleteNotification(updateManager);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
IconContent.AddRange(new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientVertical(colours.YellowDark, colours.Yellow)
},
new SpriteIcon
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Icon = FontAwesome.Solid.Upload,
Colour = Color4.White,
Size = new Vector2(20),
}
});
}
public override void Close()
{
// cancelling updates is not currently supported by the underlying updater.
// only allow dismissing for now.
switch (State)
{
case ProgressNotificationState.Cancelled:
base.Close();
break;
}
}
}
private class SquirrelLogger : Splat.ILogger, IDisposable
{
public LogLevel Level { get; set; } = LogLevel.Info;
public void Write(string message, LogLevel logLevel)
{
if (logLevel < Level)
return;
logger.Add(message);
}
public void Dispose()
{
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DataAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.Common {
using System;
using System.ComponentModel;
using System.Data;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
public class DataAdapter : Component, IDataAdapter { // V1.0.3300
static private readonly object EventFillError = new object();
private bool _acceptChangesDuringUpdate = true;
private bool _acceptChangesDuringUpdateAfterInsert = true;
private bool _continueUpdateOnError = false;
private bool _hasFillErrorHandler = false;
private bool _returnProviderSpecificTypes = false;
private bool _acceptChangesDuringFill = true;
private LoadOption _fillLoadOption;
private MissingMappingAction _missingMappingAction = System.Data.MissingMappingAction.Passthrough;
private MissingSchemaAction _missingSchemaAction = System.Data.MissingSchemaAction.Add;
private DataTableMappingCollection _tableMappings;
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
#if DEBUG
// if true, we are asserting that the caller has provided a select command
// which should not return an empty result set
private bool _debugHookNonEmptySelectCommand = false;
#endif
[Conditional("DEBUG")]
void AssertReaderHandleFieldCount(DataReaderContainer readerHandler) {
#if DEBUG
Debug.Assert(!_debugHookNonEmptySelectCommand || readerHandler.FieldCount > 0, "Scenario expects non-empty results but no fields reported by reader");
#endif
}
[Conditional("DEBUG")]
void AssertSchemaMapping(SchemaMapping mapping) {
#if DEBUG
if (_debugHookNonEmptySelectCommand) {
Debug.Assert(mapping != null && mapping.DataValues != null && mapping.DataTable != null, "Debug hook specifies that non-empty results are not expected");
}
#endif
}
protected DataAdapter() : base() { // V1.0.3300
GC.SuppressFinalize(this);
}
protected DataAdapter(DataAdapter from) : base() { // V1.1.3300
CloneFrom(from);
}
[
DefaultValue(true),
ResCategoryAttribute(Res.DataCategory_Fill),
ResDescriptionAttribute(Res.DataAdapter_AcceptChangesDuringFill),
]
public bool AcceptChangesDuringFill { // V1.0.3300
get {
//Bid.Trace("<comm.DataAdapter.get_AcceptChangesDuringFill|API> %d#\n", ObjectID);
return _acceptChangesDuringFill;
}
set {
_acceptChangesDuringFill = value;
//Bid.Trace("<comm.DataAdapter.set_AcceptChangesDuringFill|API> %d#, %d\n", ObjectID, value);
}
}
[
EditorBrowsableAttribute(EditorBrowsableState.Never)
]
virtual public bool ShouldSerializeAcceptChangesDuringFill() {
return (0 == _fillLoadOption);
}
[
DefaultValue(true),
ResCategoryAttribute(Res.DataCategory_Update),
ResDescriptionAttribute(Res.DataAdapter_AcceptChangesDuringUpdate),
]
public bool AcceptChangesDuringUpdate { // V1.2.3300, MDAC 74988
get {
//Bid.Trace("<comm.DataAdapter.get_AcceptChangesDuringUpdate|API> %d#\n", ObjectID);
return _acceptChangesDuringUpdate;
}
set {
_acceptChangesDuringUpdate = value;
//Bid.Trace("<comm.DataAdapter.set_AcceptChangesDuringUpdate|API> %d#, %d\n", ObjectID, value);
}
}
[
DefaultValue(false),
ResCategoryAttribute(Res.DataCategory_Update),
ResDescriptionAttribute(Res.DataAdapter_ContinueUpdateOnError),
]
public bool ContinueUpdateOnError { // V1.0.3300, MDAC 66900
get {
//Bid.Trace("<comm.DataAdapter.get_ContinueUpdateOnError|API> %d#\n", ObjectID);
return _continueUpdateOnError;
}
set {
_continueUpdateOnError = value;
//Bid.Trace("<comm.DataAdapter.set_ContinueUpdateOnError|API> %d#, %d\n", ObjectID, value);
}
}
[
RefreshProperties(RefreshProperties.All),
ResCategoryAttribute(Res.DataCategory_Fill),
ResDescriptionAttribute(Res.DataAdapter_FillLoadOption),
]
public LoadOption FillLoadOption { // V1.2.3300
get {
//Bid.Trace("<comm.DataAdapter.get_FillLoadOption|API> %d#\n", ObjectID);
LoadOption fillLoadOption = _fillLoadOption;
return ((0 != fillLoadOption) ? _fillLoadOption : LoadOption.OverwriteChanges);
}
set {
switch(value) {
case 0: // to allow simple resetting
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
_fillLoadOption = value;
//Bid.Trace("<comm.DataAdapter.set_FillLoadOption|API> %d#, %d{ds.LoadOption}\n", ObjectID, (int)value);
break;
default:
throw ADP.InvalidLoadOption(value);
}
}
}
[
EditorBrowsableAttribute(EditorBrowsableState.Never)
]
public void ResetFillLoadOption() {
_fillLoadOption = 0;
}
[
EditorBrowsableAttribute(EditorBrowsableState.Never)
]
virtual public bool ShouldSerializeFillLoadOption() {
return (0 != _fillLoadOption);
}
[
DefaultValue(System.Data.MissingMappingAction.Passthrough),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataAdapter_MissingMappingAction),
]
public MissingMappingAction MissingMappingAction { // V1.0.3300
get {
//Bid.Trace("<comm.DataAdapter.get_MissingMappingAction|API> %d#\n", ObjectID);
return _missingMappingAction;
}
set {
switch(value) { // @perfnote: Enum.IsDefined
case MissingMappingAction.Passthrough:
case MissingMappingAction.Ignore:
case MissingMappingAction.Error:
_missingMappingAction = value;
//Bid.Trace("<comm.DataAdapter.set_MissingMappingAction|API> %d#, %d{ds.MissingMappingAction}\n", ObjectID, (int)value);
break;
default:
throw ADP.InvalidMissingMappingAction(value);
}
}
}
[
DefaultValue(Data.MissingSchemaAction.Add),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataAdapter_MissingSchemaAction),
]
public MissingSchemaAction MissingSchemaAction { // V1.0.3300
get {
//Bid.Trace("<comm.DataAdapter.get_MissingSchemaAction|API> %d#\n", ObjectID);
return _missingSchemaAction;
}
set {
switch(value) { // @perfnote: Enum.IsDefined
case MissingSchemaAction.Add:
case MissingSchemaAction.Ignore:
case MissingSchemaAction.Error:
case MissingSchemaAction.AddWithKey:
_missingSchemaAction = value;
//Bid.Trace("<comm.DataAdapter.set_MissingSchemaAction|API> %d#, %d{MissingSchemaAction}\n", ObjectID, (int)value);
break;
default:
throw ADP.InvalidMissingSchemaAction(value);
}
}
}
internal int ObjectID {
get {
return _objectID;
}
}
[
DefaultValue(false),
ResCategoryAttribute(Res.DataCategory_Fill),
ResDescriptionAttribute(Res.DataAdapter_ReturnProviderSpecificTypes),
]
virtual public bool ReturnProviderSpecificTypes {
get {
//Bid.Trace("<comm.DataAdapter.get_ReturnProviderSpecificTypes|API> %d#\n", ObjectID);
return _returnProviderSpecificTypes;
}
set {
_returnProviderSpecificTypes = value;
//Bid.Trace("<comm.DataAdapter.set_ReturnProviderSpecificTypes|API> %d#, %d\n", ObjectID, (int)value);
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
ResCategoryAttribute(Res.DataCategory_Mapping),
ResDescriptionAttribute(Res.DataAdapter_TableMappings),
]
public DataTableMappingCollection TableMappings { // V1.0.3300
get {
//Bid.Trace("<comm.DataAdapter.get_TableMappings|API> %d#\n", ObjectID);
DataTableMappingCollection mappings = _tableMappings;
if (null == mappings) {
mappings = CreateTableMappings();
if (null == mappings) {
mappings = new DataTableMappingCollection();
}
_tableMappings = mappings;
}
return mappings; // constructed by base class
}
}
ITableMappingCollection IDataAdapter.TableMappings { // V1.0.3300
get {
return TableMappings;
}
}
virtual protected bool ShouldSerializeTableMappings() { // V1.0.3300, MDAC 65548
return true; /*HasTableMappings();*/ // VS7 300569
}
protected bool HasTableMappings() { // V1.2.3300
return ((null != _tableMappings) && (0 < TableMappings.Count));
}
[
ResCategoryAttribute(Res.DataCategory_Fill),
ResDescriptionAttribute(Res.DataAdapter_FillError),
]
public event FillErrorEventHandler FillError { // V1.2.3300, DbDataADapter V1.0.3300
add {
_hasFillErrorHandler = true;
Events.AddHandler(EventFillError, value);
}
remove {
Events.RemoveHandler(EventFillError, value);
}
}
[ Obsolete("CloneInternals() has been deprecated. Use the DataAdapter(DataAdapter from) constructor. http://go.microsoft.com/fwlink/?linkid=14202") ] // V1.1.3300, MDAC 81448
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")] // MDAC 82936
virtual protected DataAdapter CloneInternals() { // V1.0.3300
DataAdapter clone = (DataAdapter)Activator.CreateInstance(GetType(), System.Reflection.BindingFlags.Public|System.Reflection.BindingFlags.Instance, null, null, CultureInfo.InvariantCulture, null);
clone.CloneFrom(this);
return clone;
}
private void CloneFrom(DataAdapter from) {
_acceptChangesDuringUpdate = from._acceptChangesDuringUpdate;
_acceptChangesDuringUpdateAfterInsert = from._acceptChangesDuringUpdateAfterInsert;
_continueUpdateOnError = from._continueUpdateOnError;
_returnProviderSpecificTypes = from._returnProviderSpecificTypes; // WebData 101795
_acceptChangesDuringFill = from._acceptChangesDuringFill;
_fillLoadOption = from._fillLoadOption;
_missingMappingAction = from._missingMappingAction;
_missingSchemaAction = from._missingSchemaAction;
if ((null != from._tableMappings) && (0 < from.TableMappings.Count)) {
DataTableMappingCollection parameters = this.TableMappings;
foreach(object parameter in from.TableMappings) {
parameters.Add((parameter is ICloneable) ? ((ICloneable)parameter).Clone() : parameter);
}
}
}
virtual protected DataTableMappingCollection CreateTableMappings() { // V1.0.3300
Bid.Trace("<comm.DataAdapter.CreateTableMappings|API> %d#\n", ObjectID);
return new DataTableMappingCollection();
}
override protected void Dispose(bool disposing) { // V1.0.3300, MDAC 65459
if (disposing) { // release mananged objects
_tableMappings = null;
}
// release unmanaged objects
base.Dispose(disposing); // notify base classes
}
virtual public DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType) { // V1.0.3300
throw ADP.NotSupported();
}
virtual protected DataTable[] FillSchema(DataSet dataSet, SchemaType schemaType, string srcTable, IDataReader dataReader) { // V1.2.3300
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<comm.DataAdapter.FillSchema|API> %d#, dataSet, schemaType=%d{ds.SchemaType}, srcTable, dataReader\n", ObjectID, (int)schemaType);
try {
if (null == dataSet) {
throw ADP.ArgumentNull("dataSet");
}
if ((SchemaType.Source != schemaType) && (SchemaType.Mapped != schemaType)) {
throw ADP.InvalidSchemaType(schemaType);
}
if (ADP.IsEmpty(srcTable)) {
throw ADP.FillSchemaRequiresSourceTableName("srcTable");
}
if ((null == dataReader) || dataReader.IsClosed) {
throw ADP.FillRequires("dataReader");
}
// user must Close/Dispose of the dataReader
object value = FillSchemaFromReader(dataSet, null, schemaType, srcTable, dataReader);
return (DataTable[]) value;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
virtual protected DataTable FillSchema(DataTable dataTable, SchemaType schemaType, IDataReader dataReader) { // V1.2.3300
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<comm.DataAdapter.FillSchema|API> %d#, dataTable, schemaType, dataReader\n", ObjectID);
try {
if (null == dataTable) {
throw ADP.ArgumentNull("dataTable");
}
if ((SchemaType.Source != schemaType) && (SchemaType.Mapped != schemaType)) {
throw ADP.InvalidSchemaType(schemaType);
}
if ((null == dataReader) || dataReader.IsClosed) {
throw ADP.FillRequires("dataReader");
}
// user must Close/Dispose of the dataReader
// user will have to call NextResult to access remaining results
object value = FillSchemaFromReader(null, dataTable, schemaType, null, dataReader);
return (DataTable) value;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
internal object FillSchemaFromReader(DataSet dataset, DataTable datatable, SchemaType schemaType, string srcTable, IDataReader dataReader) {
DataTable[] dataTables = null;
int schemaCount = 0;
do {
DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes);
AssertReaderHandleFieldCount(readerHandler);
if (0 >= readerHandler.FieldCount) {
continue;
}
string tmp = null;
if (null != dataset) {
tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount);
schemaCount++; // don't increment if no SchemaTable ( a non-row returning result )
}
SchemaMapping mapping = new SchemaMapping(this, dataset, datatable, readerHandler, true, schemaType, tmp, false, null, null);
if (null != datatable) {
// do not read remaining results in single DataTable case
return mapping.DataTable;
}
else if (null != mapping.DataTable) {
if (null == dataTables) {
dataTables = new DataTable[1] { mapping.DataTable };
}
else {
dataTables = DataAdapter.AddDataTableToArray(dataTables, mapping.DataTable);
}
}
} while (dataReader.NextResult()); // FillSchema does not capture errors for FillError event
object value = dataTables;
if ((null == value) && (null == datatable)) { // WebData 101757
value = new DataTable[0];
}
return value; // null if datatable had no results
}
virtual public int Fill(DataSet dataSet) { // V1.0.3300
throw ADP.NotSupported();
}
virtual protected int Fill(DataSet dataSet, string srcTable, IDataReader dataReader, int startRecord, int maxRecords) { // V1.2.3300, DbDataAdapter V1.0.3300
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<comm.DataAdapter.Fill|API> %d#, dataSet, srcTable, dataReader, startRecord, maxRecords\n", ObjectID);
try {
if (null == dataSet) {
throw ADP.FillRequires("dataSet");
}
if (ADP.IsEmpty(srcTable)) {
throw ADP.FillRequiresSourceTableName("srcTable");
}
if (null == dataReader) {
throw ADP.FillRequires("dataReader");
}
if (startRecord < 0) {
throw ADP.InvalidStartRecord("startRecord", startRecord);
}
if (maxRecords < 0) {
throw ADP.InvalidMaxRecords("maxRecords", maxRecords);
}
if (dataReader.IsClosed) {
return 0;
}
// user must Close/Dispose of the dataReader
DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes);
return FillFromReader(dataSet, null, srcTable, readerHandler, startRecord, maxRecords, null, null);
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
virtual protected int Fill(DataTable dataTable, IDataReader dataReader) { // V1.2.3300, DbDataADapter V1.0.3300
DataTable[] dataTables = new DataTable[] { dataTable };
return Fill(dataTables, dataReader, 0, 0);
}
virtual protected int Fill(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords) { // V1.2.3300
IntPtr hscp;
Bid.ScopeEnter(out hscp, "<comm.DataAdapter.Fill|API> %d#, dataTables[], dataReader, startRecord, maxRecords\n", ObjectID);
try {
ADP.CheckArgumentLength(dataTables, "tables");
if ((null == dataTables) || (0 == dataTables.Length) || (null == dataTables[0])) {
throw ADP.FillRequires("dataTable");
}
if (null == dataReader) {
throw ADP.FillRequires("dataReader");
}
if ((1 < dataTables.Length) && ((0 != startRecord) || (0 != maxRecords))) {
throw ADP.NotSupported(); // FillChildren is not supported with FillPage
}
int result = 0;
bool enforceContraints = false;
DataSet commonDataSet = dataTables[0].DataSet;
try {
if (null != commonDataSet) {
enforceContraints = commonDataSet.EnforceConstraints;
commonDataSet.EnforceConstraints = false;
}
for(int i = 0; i < dataTables.Length; ++i) {
Debug.Assert(null != dataTables[i], "null DataTable Fill");
if (dataReader.IsClosed) {
#if DEBUG
Debug.Assert(!_debugHookNonEmptySelectCommand, "Debug hook asserts data reader should be open");
#endif
break;
}
DataReaderContainer readerHandler = DataReaderContainer.Create(dataReader, ReturnProviderSpecificTypes);
AssertReaderHandleFieldCount(readerHandler);
if (readerHandler.FieldCount <= 0) {
if (i == 0)
{
bool lastFillNextResult;
do {
lastFillNextResult = FillNextResult(readerHandler);
}
while (lastFillNextResult && readerHandler.FieldCount <= 0);
if (!lastFillNextResult) {
break;
}
}
else {
continue;
}
}
if ((0 < i) && !FillNextResult(readerHandler)) {
break;
}
// user must Close/Dispose of the dataReader
// user will have to call NextResult to access remaining results
int count = FillFromReader(null, dataTables[i], null, readerHandler, startRecord, maxRecords, null, null);
if (0 == i) {
result = count;
}
}
}
catch(ConstraintException) {
enforceContraints = false;
throw;
}
finally {
if (enforceContraints) {
commonDataSet.EnforceConstraints = true;
}
}
return result;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
internal int FillFromReader(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int startRecord, int maxRecords, DataColumn parentChapterColumn, object parentChapterValue) {
int rowsAddedToDataSet = 0;
int schemaCount = 0;
do {
AssertReaderHandleFieldCount(dataReader);
if (0 >= dataReader.FieldCount) {
continue; // loop to next result
}
SchemaMapping mapping = FillMapping(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue);
schemaCount++; // don't increment if no SchemaTable ( a non-row returning result )
AssertSchemaMapping(mapping);
if (null == mapping) {
continue; // loop to next result
}
if (null == mapping.DataValues) {
continue; // loop to next result
}
if (null == mapping.DataTable) {
continue; // loop to next result
}
mapping.DataTable.BeginLoadData();
try {
// startRecord and maxRecords only apply to the first resultset
if ((1 == schemaCount) && ((0 < startRecord) || (0 < maxRecords))) {
rowsAddedToDataSet = FillLoadDataRowChunk(mapping, startRecord, maxRecords);
}
else {
int count = FillLoadDataRow(mapping);
if (1 == schemaCount) { // MDAC 71347
// only return LoadDataRow count for first resultset
// not secondary or chaptered results
rowsAddedToDataSet = count;
}
}
}
finally {
mapping.DataTable.EndLoadData();
}
if (null != datatable) {
break; // do not read remaining results in single DataTable case
}
} while (FillNextResult(dataReader));
return rowsAddedToDataSet;
}
private int FillLoadDataRowChunk(SchemaMapping mapping, int startRecord, int maxRecords) {
DataReaderContainer dataReader = mapping.DataReader;
while (0 < startRecord) {
if (!dataReader.Read()) {
// there are no more rows on first resultset
return 0;
}
--startRecord;
}
int rowsAddedToDataSet = 0;
if (0 < maxRecords) {
while ((rowsAddedToDataSet < maxRecords) && dataReader.Read()) {
if (_hasFillErrorHandler) {
try {
mapping.LoadDataRowWithClear();
rowsAddedToDataSet++;
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionForCapture(e);
OnFillErrorHandler(e, mapping.DataTable, mapping.DataValues);
}
}
else {
mapping.LoadDataRow();
rowsAddedToDataSet++;
}
}
// skip remaining rows of the first resultset
}
else {
rowsAddedToDataSet = FillLoadDataRow(mapping);
}
return rowsAddedToDataSet;
}
private int FillLoadDataRow(SchemaMapping mapping) {
int rowsAddedToDataSet = 0;
DataReaderContainer dataReader = mapping.DataReader;
if (_hasFillErrorHandler) {
while (dataReader.Read()) { // read remaining rows of first and subsequent resultsets
try {
// only try-catch if a FillErrorEventHandler is registered so that
// in the default case we get the full callstack from users
mapping.LoadDataRowWithClear();
rowsAddedToDataSet++;
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionForCapture(e);
OnFillErrorHandler(e, mapping.DataTable, mapping.DataValues);
}
}
}
else {
while (dataReader.Read()) { // read remaining rows of first and subsequent resultset
mapping.LoadDataRow();
rowsAddedToDataSet++;
}
}
return rowsAddedToDataSet;
}
private SchemaMapping FillMappingInternal(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) {
bool withKeyInfo = (Data.MissingSchemaAction.AddWithKey == MissingSchemaAction);
string tmp = null;
if (null != dataset) {
tmp = DataAdapter.GetSourceTableName(srcTable, schemaCount);
}
return new SchemaMapping(this, dataset, datatable, dataReader, withKeyInfo, SchemaType.Mapped, tmp, true, parentChapterColumn, parentChapterValue);
}
private SchemaMapping FillMapping(DataSet dataset, DataTable datatable, string srcTable, DataReaderContainer dataReader, int schemaCount, DataColumn parentChapterColumn, object parentChapterValue) {
SchemaMapping mapping = null;
if (_hasFillErrorHandler) {
try {
// only try-catch if a FillErrorEventHandler is registered so that
// in the default case we get the full callstack from users
mapping = FillMappingInternal(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue);
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionForCapture(e);
OnFillErrorHandler(e, null, null);
}
}
else {
mapping = FillMappingInternal(dataset, datatable, srcTable, dataReader, schemaCount, parentChapterColumn, parentChapterValue);
}
return mapping;
}
private bool FillNextResult(DataReaderContainer dataReader) {
bool result = true;
if (_hasFillErrorHandler) {
try {
// only try-catch if a FillErrorEventHandler is registered so that
// in the default case we get the full callstack from users
result = dataReader.NextResult();
}
catch(Exception e) {
//
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionForCapture(e);
OnFillErrorHandler(e, null, null);
}
}
else {
result = dataReader.NextResult();
}
return result;
}
[ EditorBrowsableAttribute(EditorBrowsableState.Advanced) ] // MDAC 69508
virtual public IDataParameter[] GetFillParameters() { // V1.0.3300
return new IDataParameter[0];
}
internal DataTableMapping GetTableMappingBySchemaAction(string sourceTableName, string dataSetTableName, MissingMappingAction mappingAction) {
return DataTableMappingCollection.GetTableMappingBySchemaAction(_tableMappings, sourceTableName, dataSetTableName, mappingAction);
}
internal int IndexOfDataSetTable(string dataSetTable) {
if (null != _tableMappings) {
return TableMappings.IndexOfDataSetTable(dataSetTable);
}
return -1;
}
virtual protected void OnFillError(FillErrorEventArgs value) { // V1.2.3300, DbDataAdapter V1.0.3300
FillErrorEventHandler handler = (FillErrorEventHandler) Events[EventFillError];
if (null != handler) {
handler(this, value);
}
}
private void OnFillErrorHandler(Exception e, DataTable dataTable, object[] dataValues) {
FillErrorEventArgs fillErrorEvent = new FillErrorEventArgs(dataTable, dataValues);
fillErrorEvent.Errors = e;
OnFillError(fillErrorEvent);
if (!fillErrorEvent.Continue) {
if (null != fillErrorEvent.Errors) {
throw fillErrorEvent.Errors;
}
throw e;
}
}
virtual public int Update(DataSet dataSet) { // V1.0.3300
throw ADP.NotSupported();
}
// used by FillSchema which returns an array of datatables added to the dataset
static private DataTable[] AddDataTableToArray(DataTable[] tables, DataTable newTable) {
for (int i = 0; i < tables.Length; ++i) { // search for duplicates
if (tables[i] == newTable) {
return tables; // duplicate found
}
}
DataTable[] newTables = new DataTable[tables.Length+1]; // add unique data table
for (int i = 0; i < tables.Length; ++i) {
newTables[i] = tables[i];
}
newTables[tables.Length] = newTable;
return newTables;
}
// dynamically generate source table names
static private string GetSourceTableName(string srcTable, int index) {
//if ((null != srcTable) && (0 <= index) && (index < srcTable.Length)) {
if (0 == index) {
return srcTable; //[index];
}
return srcTable + index.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
}
internal sealed class LoadAdapter : DataAdapter {
internal LoadAdapter() {
}
internal int FillFromReader(DataTable[] dataTables, IDataReader dataReader, int startRecord, int maxRecords) {
return Fill(dataTables, dataReader, startRecord, maxRecords);
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace ProviderHostedCustomUIActionsWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* 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.Reflection;
using QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
using QuantConnect.Securities;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// This regression algorithm tests In The Money (ITM) index option expiry for short puts.
/// We expect 2 orders from the algorithm, which are:
///
/// * Initial entry, sell SPX Put Option (expiring ITM)
/// * Option assignment
///
/// Additionally, we test delistings for index options and assert that our
/// portfolio holdings reflect the orders the algorithm has submitted.
/// </summary>
public class IndexOptionShortPutITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spx;
private Symbol _spxOption;
private Symbol _expectedContract;
public override void Initialize()
{
SetStartDate(2021, 1, 4);
SetEndDate(2021, 1, 31);
_spx = AddIndex("SPX", Resolution.Minute).Symbol;
// Select a index option expiring ITM, and adds it to the algorithm.
_spxOption = AddIndexOptionContract(OptionChainProvider.GetOptionContractList(_spx, Time)
.Where(x => x.ID.StrikePrice <= 4200m && x.ID.OptionRight == OptionRight.Put && x.ID.Date.Year == 2021 && x.ID.Date.Month == 1)
.OrderByDescending(x => x.ID.StrikePrice)
.Take(1)
.Single(), Resolution.Minute).Symbol;
_expectedContract = QuantConnect.Symbol.CreateOption(_spx, Market.USA, OptionStyle.European, OptionRight.Put, 4200m, new DateTime(2021, 1, 15));
if (_spxOption != _expectedContract)
{
throw new Exception($"Contract {_expectedContract} was not found in the chain");
}
Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_spx, 1), () =>
{
MarketOrder(_spxOption, -1);
});
}
public override void OnData(Slice data)
{
// Assert delistings, so that we can make sure that we receive the delisting warnings at
// the expected time. These assertions detect bug #4872
foreach (var delisting in data.Delistings.Values)
{
if (delisting.Type == DelistingType.Warning)
{
if (delisting.Time != new DateTime(2021, 1, 15))
{
throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}");
}
}
if (delisting.Type == DelistingType.Delisted)
{
if (delisting.Time != new DateTime(2021, 1, 16))
{
throw new Exception($"Delisting happened at unexpected date: {delisting.Time}");
}
}
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
if (orderEvent.Status != OrderStatus.Filled)
{
// There's lots of noise with OnOrderEvent, but we're only interested in fills.
return;
}
if (!Securities.ContainsKey(orderEvent.Symbol))
{
throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}");
}
var security = Securities[orderEvent.Symbol];
if (security.Symbol == _spx)
{
AssertIndexOptionOrderExercise(orderEvent, security, Securities[_expectedContract]);
}
else if (security.Symbol == _expectedContract)
{
AssertIndexOptionContractOrder(orderEvent, security);
}
else
{
throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}");
}
Log($"{orderEvent}");
}
private void AssertIndexOptionOrderExercise(OrderEvent orderEvent, Security index, Security optionContract)
{
if (orderEvent.Message.Contains("Assignment"))
{
if (orderEvent.FillPrice != 4200)
{
throw new Exception("Option was not assigned at expected strike price (4200)");
}
if (orderEvent.Direction != OrderDirection.Buy || index.Holdings.Quantity != 0)
{
throw new Exception($"Expected Qty: 0 index holdings for assigned index option {index.Symbol}, found {index.Holdings.Quantity}");
}
}
else if (index.Holdings.Quantity != 0)
{
throw new Exception($"Expected no holdings in index: {index.Symbol}");
}
}
private void AssertIndexOptionContractOrder(OrderEvent orderEvent, Security option)
{
if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != -1)
{
throw new Exception($"No holdings were created for option contract {option.Symbol}");
}
if (orderEvent.IsAssignment && option.Holdings.Quantity != 0)
{
throw new Exception($"Holdings were found after option contract was assigned: {option.Symbol}");
}
}
/// <summary>
/// Ran at the end of the algorithm to ensure the algorithm has no holdings
/// </summary>
/// <exception cref="Exception">The algorithm has holdings</exception>
public override void OnEndOfAlgorithm()
{
if (Portfolio.Invested)
{
throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}");
}
}
/// <summary>
/// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.
/// </summary>
public bool CanRunLocally { get; } = true;
/// <summary>
/// This is used by the regression test system to indicate which languages this algorithm is written in.
/// </summary>
public Language[] Languages { get; } = { Language.CSharp, Language.Python };
/// <summary>
/// This is used by the regression test system to indicate what the expected statistics are from running the algorithm
/// </summary>
public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "51.07%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "319.986%"},
{"Drawdown", "2.400%"},
{"Expectancy", "0"},
{"Net Profit", "10.624%"},
{"Sharpe Ratio", "7.1"},
{"Probabilistic Sharpe Ratio", "89.813%"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "2.84"},
{"Beta", "-0.227"},
{"Annual Standard Deviation", "0.398"},
{"Annual Variance", "0.159"},
{"Information Ratio", "6.298"},
{"Tracking Error", "0.44"},
{"Treynor Ratio", "-12.457"},
{"Total Fees", "$0.00"},
{"Estimated Strategy Capacity", "$0"},
{"Lowest Capacity Asset", "SPX 31KC0UJHC75TA|SPX 31"},
{"Fitness Score", "0.025"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "634.943"},
{"Return Over Maximum Drawdown", "1184.633"},
{"Portfolio Turnover", "0.025"},
{"Total Insights Generated", "0"},
{"Total Insights Closed", "0"},
{"Total Insights Analysis Completed", "0"},
{"Long Insight Count", "0"},
{"Short Insight Count", "0"},
{"Long/Short Ratio", "100%"},
{"Estimated Monthly Alpha Value", "$0"},
{"Total Accumulated Estimated Alpha Value", "$0"},
{"Mean Population Estimated Insight Value", "$0"},
{"Mean Population Direction", "0%"},
{"Mean Population Magnitude", "0%"},
{"Rolling Averaged Population Direction", "0%"},
{"Rolling Averaged Population Magnitude", "0%"},
{"OrderListHash", "f243341674cb1486d7cf009d74d4e6ff"}
};
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Conditions
{
using System;
using System.Text;
using NLog.Internal;
/// <summary>
/// Hand-written tokenizer for conditions.
/// </summary>
internal sealed class ConditionTokenizer
{
private static readonly ConditionTokenType[] charIndexToTokenType = BuildCharIndexToTokenType();
private readonly SimpleStringReader stringReader;
/// <summary>
/// Initializes a new instance of the <see cref="ConditionTokenizer"/> class.
/// </summary>
/// <param name="stringReader">The string reader.</param>
public ConditionTokenizer(SimpleStringReader stringReader)
{
this.stringReader = stringReader;
this.TokenType = ConditionTokenType.BeginningOfInput;
this.GetNextToken();
}
/// <summary>
/// Gets the token position.
/// </summary>
/// <value>The token position.</value>
public int TokenPosition { get; private set; }
/// <summary>
/// Gets the type of the token.
/// </summary>
/// <value>The type of the token.</value>
public ConditionTokenType TokenType { get; private set; }
/// <summary>
/// Gets the token value.
/// </summary>
/// <value>The token value.</value>
public string TokenValue { get; private set; }
/// <summary>
/// Gets the value of a string token.
/// </summary>
/// <value>The string token value.</value>
public string StringTokenValue
{
get
{
string s = this.TokenValue;
return s.Substring(1, s.Length - 2).Replace("''", "'");
}
}
/// <summary>
/// Asserts current token type and advances to the next token.
/// </summary>
/// <param name="tokenType">Expected token type.</param>
/// <remarks>If token type doesn't match, an exception is thrown.</remarks>
public void Expect(ConditionTokenType tokenType)
{
if (this.TokenType != tokenType)
{
throw new ConditionParseException("Expected token of type: " + tokenType + ", got " + this.TokenType + " (" + this.TokenValue + ").");
}
this.GetNextToken();
}
/// <summary>
/// Asserts that current token is a keyword and returns its value and advances to the next token.
/// </summary>
/// <returns>Keyword value.</returns>
public string EatKeyword()
{
if (this.TokenType != ConditionTokenType.Keyword)
{
throw new ConditionParseException("Identifier expected");
}
string s = (string)this.TokenValue;
this.GetNextToken();
return s;
}
/// <summary>
/// Gets or sets a value indicating whether current keyword is equal to the specified value.
/// </summary>
/// <param name="keyword">The keyword.</param>
/// <returns>
/// A value of <c>true</c> if current keyword is equal to the specified value; otherwise, <c>false</c>.
/// </returns>
public bool IsKeyword(string keyword)
{
if (this.TokenType != ConditionTokenType.Keyword)
{
return false;
}
if (!this.TokenValue.Equals(keyword, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
/// <summary>
/// Gets or sets a value indicating whether the tokenizer has reached the end of the token stream.
/// </summary>
/// <returns>
/// A value of <c>true</c> if the tokenizer has reached the end of the token stream; otherwise, <c>false</c>.
/// </returns>
public bool IsEOF()
{
if (this.TokenType != ConditionTokenType.EndOfInput)
{
return false;
}
return true;
}
/// <summary>
/// Gets or sets a value indicating whether current token is a number.
/// </summary>
/// <returns>
/// A value of <c>true</c> if current token is a number; otherwise, <c>false</c>.
/// </returns>
public bool IsNumber()
{
return this.TokenType == ConditionTokenType.Number;
}
/// <summary>
/// Gets or sets a value indicating whether the specified token is of specified type.
/// </summary>
/// <param name="tokenType">The token type.</param>
/// <returns>
/// A value of <c>true</c> if current token is of specified type; otherwise, <c>false</c>.
/// </returns>
public bool IsToken(ConditionTokenType tokenType)
{
return this.TokenType == tokenType;
}
/// <summary>
/// Gets the next token and sets <see cref="TokenType"/> and <see cref="TokenValue"/> properties.
/// </summary>
public void GetNextToken()
{
if (this.TokenType == ConditionTokenType.EndOfInput)
{
throw new ConditionParseException("Cannot read past end of stream.");
}
this.SkipWhitespace();
this.TokenPosition = this.TokenPosition;
int i = this.PeekChar();
if (i == -1)
{
this.TokenType = ConditionTokenType.EndOfInput;
return;
}
char ch = (char)i;
if (char.IsDigit(ch))
{
this.ParseNumber(ch);
return;
}
if (ch == '\'')
{
this.ParseSingleQuotedString(ch);
return;
}
if (ch == '_' || char.IsLetter(ch))
{
this.ParseKeyword(ch);
return;
}
if (ch == '}' || ch == ':')
{
// when condition is embedded
this.TokenType = ConditionTokenType.EndOfInput;
return;
}
this.TokenValue = ch.ToString();
if (ch == '<')
{
this.ReadChar();
int nextChar = this.PeekChar();
if (nextChar == '>')
{
this.TokenType = ConditionTokenType.NotEqual;
this.TokenValue = "<>";
this.ReadChar();
return;
}
if (nextChar == '=')
{
this.TokenType = ConditionTokenType.LessThanOrEqualTo;
this.TokenValue = "<=";
this.ReadChar();
return;
}
this.TokenType = ConditionTokenType.LessThan;
this.TokenValue = "<";
return;
}
if (ch == '>')
{
this.ReadChar();
int nextChar = this.PeekChar();
if (nextChar == '=')
{
this.TokenType = ConditionTokenType.GreaterThanOrEqualTo;
this.TokenValue = ">=";
this.ReadChar();
return;
}
this.TokenType = ConditionTokenType.GreaterThan;
this.TokenValue = ">";
return;
}
if (ch == '!')
{
this.ReadChar();
int nextChar = this.PeekChar();
if (nextChar == '=')
{
this.TokenType = ConditionTokenType.NotEqual;
this.TokenValue = "!=";
this.ReadChar();
return;
}
this.TokenType = ConditionTokenType.Not;
this.TokenValue = "!";
return;
}
if (ch == '&')
{
this.ReadChar();
int nextChar = this.PeekChar();
if (nextChar == '&')
{
this.TokenType = ConditionTokenType.And;
this.TokenValue = "&&";
this.ReadChar();
return;
}
throw new ConditionParseException("Expected '&&' but got '&'");
}
if (ch == '|')
{
this.ReadChar();
int nextChar = this.PeekChar();
if (nextChar == '|')
{
this.TokenType = ConditionTokenType.Or;
this.TokenValue = "||";
this.ReadChar();
return;
}
throw new ConditionParseException("Expected '||' but got '|'");
}
if (ch == '=')
{
this.ReadChar();
int nextChar = this.PeekChar();
if (nextChar == '=')
{
this.TokenType = ConditionTokenType.EqualTo;
this.TokenValue = "==";
this.ReadChar();
return;
}
this.TokenType = ConditionTokenType.EqualTo;
this.TokenValue = "=";
return;
}
if (ch >= 32 && ch < 128)
{
ConditionTokenType tt = charIndexToTokenType[ch];
if (tt != ConditionTokenType.Invalid)
{
this.TokenType = tt;
this.TokenValue = new string(ch, 1);
this.ReadChar();
return;
}
throw new ConditionParseException("Invalid punctuation: " + ch);
}
throw new ConditionParseException("Invalid token: " + ch);
}
private static ConditionTokenType[] BuildCharIndexToTokenType()
{
CharToTokenType[] charToTokenType =
{
new CharToTokenType('(', ConditionTokenType.LeftParen),
new CharToTokenType(')', ConditionTokenType.RightParen),
new CharToTokenType('.', ConditionTokenType.Dot),
new CharToTokenType(',', ConditionTokenType.Comma),
new CharToTokenType('!', ConditionTokenType.Not),
new CharToTokenType('-', ConditionTokenType.Minus),
};
var result = new ConditionTokenType[128];
for (int i = 0; i < 128; ++i)
{
result[i] = ConditionTokenType.Invalid;
}
foreach (CharToTokenType cht in charToTokenType)
{
// Console.WriteLine("Setting up {0} to {1}", cht.ch, cht.tokenType);
result[(int)cht.Character] = cht.TokenType;
}
return result;
}
private void ParseSingleQuotedString(char ch)
{
int i;
this.TokenType = ConditionTokenType.String;
StringBuilder sb = new StringBuilder();
sb.Append(ch);
this.ReadChar();
while ((i = this.PeekChar()) != -1)
{
ch = (char)i;
sb.Append((char)this.ReadChar());
if (ch == '\'')
{
if (this.PeekChar() == (int)'\'')
{
sb.Append('\'');
this.ReadChar();
}
else
{
break;
}
}
}
if (i == -1)
{
throw new ConditionParseException("String literal is missing a closing quote character.");
}
this.TokenValue = sb.ToString();
}
private void ParseKeyword(char ch)
{
int i;
this.TokenType = ConditionTokenType.Keyword;
StringBuilder sb = new StringBuilder();
sb.Append((char)ch);
this.ReadChar();
while ((i = this.PeekChar()) != -1)
{
if ((char)i == '_' || (char)i == '-' || char.IsLetterOrDigit((char)i))
{
sb.Append((char)this.ReadChar());
}
else
{
break;
}
}
this.TokenValue = sb.ToString();
}
private void ParseNumber(char ch)
{
int i;
this.TokenType = ConditionTokenType.Number;
StringBuilder sb = new StringBuilder();
sb.Append(ch);
this.ReadChar();
while ((i = this.PeekChar()) != -1)
{
ch = (char)i;
if (char.IsDigit(ch) || (ch == '.'))
{
sb.Append((char)this.ReadChar());
}
else
{
break;
}
}
this.TokenValue = sb.ToString();
}
private void SkipWhitespace()
{
int ch;
while ((ch = this.PeekChar()) != -1)
{
if (!char.IsWhiteSpace((char)ch))
{
break;
}
this.ReadChar();
}
}
private int PeekChar()
{
return this.stringReader.Peek();
}
private int ReadChar()
{
return this.stringReader.Read();
}
/// <summary>
/// Mapping between characters and token types for punctuations.
/// </summary>
private struct CharToTokenType
{
public readonly char Character;
public readonly ConditionTokenType TokenType;
/// <summary>
/// Initializes a new instance of the CharToTokenType struct.
/// </summary>
/// <param name="character">The character.</param>
/// <param name="tokenType">Type of the token.</param>
public CharToTokenType(char character, ConditionTokenType tokenType)
{
this.Character = character;
this.TokenType = tokenType;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Text;
using System.Reflection;
public class DebugController : MonoBehaviour
{
#region Variables
public Texture2D m_whiteTexture;
Main m_main;
[NonSerialized] public bool m_showController = false;
enum ControllerMenus { DEBUG, CHARACTER, ENVIRONMENT, CONFIG, SOUNDS, LENGTH };
string [] m_controllerMenuText = { "debug menu", "character", "environment", "config", "sounds" };
ControllerMenus m_controllerMenuSelected = ControllerMenus.DEBUG;
float m_timeSlider = 1.0f;
int m_saccadeMode = 3;
//string [] testUtteranceButton = { "z_2", "z_3", };
//string [] testUtteranceName = { "z_viseme_test2", "z_viseme_test3", };
//string [] testUtteranceText = { "", "", };
//int testUtteranceSelected = 0;
float m_sacaadeMultiplier = 1.0f;
string [] m_mouthLayer = { "open", "W", "ShCh", "PBM", "FV", "wide", "tBack", "tTeeth", "tRoof" };
float [] m_mouthSliders = new float [100];
string [] m_expressionLayer = {
"001_inner_brow_raiser_lf",
"001_inner_brow_raiser_rt",
"002_outer_brow_raiser_lf",
"002_outer_brow_raiser_rt",
"004_brow_lowerer_lf",
"004_brow_lowerer_rt",
"005_upper_lid_raiser",
"006_cheek_raiser",
"007_lid_tightener",
"010_upper_lip_raiser",
"012_lip_corner_puller",
"014_dimpler",
"015_lip_corner_depressor",
"017_chin_raiser",
"018_lip_pucker",
"020_lip_stretcher",
"023_lip_tightener",
"024_lip_pressor",
"025_lips_part",
"026_jaw_drop",
"045_blink_lf",
"045_blink_rt", };
float [] m_expressionSliders = new float [100];
//Sounds variables
AGUtteranceDataFilter m_uttDataFilterCmp = null;
//int m_debugSoundsCharacterSelection = -1;
//int m_debugSoundsScenarioSelection = -1;
//bool[] m_debugSoundsDisposition = new bool[VitaGlobals.m_vitaMoods.Length];
//bool[] m_debugSoundsResponseType = new bool[VitaGlobals.m_vitaResponseTypes.Length];
List<AGUtteranceData> m_uttDataPrimaryReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataAcknowledgementReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataAnswerReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataBuyTimeReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataDistrationReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataEngagementReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataElaborationReponses = new List<AGUtteranceData>();
List<AGUtteranceData> m_uttDataOpeningReponses = new List<AGUtteranceData>();
#endregion
void Start()
{
m_main = GameObject.Find("Main").GetComponent<Main>();
}
void Update()
{
}
void OnGUI()
{
{
if (m_showController)
{
#if false
float buttonX = 0;
float buttonY = 0;
float buttonW = 150.0f / 1920;
if (m_main.m_vitaLaptopShowMenu)
buttonX = 238.0f / 1920;
float startX = buttonX + buttonW;
Rect rectArea = new Rect(startX, buttonY, 1.0f - startX, 1.0f);
GUILayout.BeginArea(VHGUI.ScaleToRes(ref rectArea));
GUILayout.BeginVertical(GUI.skin.box);
GUI.contentColor = Color.white;
if (m_main.m_vitaLinearMode)
{
GUILayout.Label(String.Format(@"Current Disposition: {0}", VitaGlobals.m_vitaMoods[m_main.m_vitaCurrentMood]));
GUILayout.Label(String.Format(@"Current Question ({0}/{1}): ""{2}""", m_main.m_interviewCurrentQuestion + 1, m_main.m_interviewSequence.Count, VitaGlobals.m_vitaInterviewQuestionData[m_main.m_interviewSequence[m_main.m_interviewCurrentQuestion]].text));
if (m_main.m_interviewCurrentQuestion + 1 < m_main.m_interviewSequence.Count)
GUILayout.Label(String.Format(@"Next Question ({0}/{1}): ""{2}""", m_main.m_interviewCurrentQuestion + 2, m_main.m_interviewSequence.Count, VitaGlobals.m_vitaInterviewQuestionData[m_main.m_interviewSequence[m_main.m_interviewCurrentQuestion + 1]].text));
}
else
{
GUILayout.Label(String.Format(@"Current Question ({0}/{1}): {2} - ""{3}""", 0, 0, m_main.m_vitaBranchingCurrentNode.m_data.id, m_main.m_vitaBranchingCurrentNode.m_data.text));
foreach (var child in m_main.m_vitaBranchingCurrentNode.m_children)
GUILayout.Label(String.Format(@"Next Question ({0}/{1}): {2} - ""{3}""", 0, 0, child.m_data.id, child.m_data.text));
}
GUI.contentColor = Color.white;
GUILayout.EndVertical();
GUILayout.EndArea();
#endif
}
}
if (m_showController)
{
float buttonX = 0;
float buttonY = 0;
//float buttonH = 20;
float buttonW = 550.0f / 1920;
//if (m_main.m_vitaLaptopShowMenu)
// buttonX = 238.0f / 1920;
//if (VHUtils.IsAndroid())
// buttonH = 80;
Rect rectArea = new Rect(buttonX, buttonY, buttonW, 1.0f);
GUILayout.BeginArea(VHGUI.ScaleToRes(ref rectArea));
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label(VitaGlobals.m_versionText);
GUILayout.Label(string.Format("isServer: {0}", VitaGlobals.m_isServer));
GUILayout.Label(string.Format("isGUI: {0}", VitaGlobals.m_isGUIScreen));
GUILayout.Label(string.Format("Connected: {0}", NetworkRelay.ConnectionEstablished));
GUILayout.BeginHorizontal();
if (GUILayout.Button("<", GUILayout.Width(20))) { m_controllerMenuSelected = (ControllerMenus)VHMath.DecrementWithRollover((int)m_controllerMenuSelected, m_controllerMenuText.Length); }
if (GUILayout.Button(m_controllerMenuText[(int)m_controllerMenuSelected])) { m_controllerMenuSelected = (ControllerMenus)VHMath.IncrementWithRollover((int)m_controllerMenuSelected, m_controllerMenuText.Length); }
if (GUILayout.Button(">", GUILayout.Width(20))) { m_controllerMenuSelected = (ControllerMenus)VHMath.IncrementWithRollover((int)m_controllerMenuSelected, m_controllerMenuText.Length); }
GUILayout.EndHorizontal();
if (m_controllerMenuSelected == ControllerMenus.DEBUG)
{
OnGUIDebug();
}
else if (m_controllerMenuSelected == ControllerMenus.CHARACTER)
{
OnGUICharacter();
}
else if (m_controllerMenuSelected == ControllerMenus.ENVIRONMENT)
{
OnGUIEnvironment();
}
else if (m_controllerMenuSelected == ControllerMenus.CONFIG)
{
OnGUIConfig();
}
else if (m_controllerMenuSelected == ControllerMenus.SOUNDS)
{
OnGUISounds();
}
#if false
GUILayout.BeginHorizontal();
if (GUILayout.Button(testUtteranceButton[testUtteranceSelected], GUILayout.Height(buttonH)))
{
testUtteranceSelected++;
testUtteranceSelected = testUtteranceSelected % testUtteranceButton.Length;
}
if (GUILayout.Button("Test Utt", GUILayout.Height(buttonH))) { m_sbm.SBPlayAudio(VitaGlobals.m_vitaCharacters[m_main.m_vitaCurrentCharacter], testUtteranceName[testUtteranceSelected], testUtteranceText[testUtteranceSelected]); }
GUILayout.EndHorizontal();
m_main.m_Streamer.m_SilenceThreshhold = GUILayout.HorizontalSlider(m_main.m_Streamer.m_SilenceThreshhold, 0, 1);
GUILayout.Label(string.Format("SilenceThresh: {0:f2}", m_main.m_Streamer.m_SilenceThreshhold));
if (m_main.m_micDetectionStatus == 0) GUILayout.Label("Mic: Silence");
else if (m_main.m_micDetectionStatus == 1) GUILayout.Label("Mic: Speaking");
else if (m_main.m_micDetectionStatus == 2) GUILayout.Label("Mic: Cooldown");
if (m_main.m_turnTakingState == 0) GUILayout.Label("Turn: AgentSpeaking");
else if (m_main.m_turnTakingState == 1) GUILayout.Label("Turn: WaitForUser");
else if (m_main.m_turnTakingState == 2) GUILayout.Label("Turn: UserSpeaking");
else if (m_main.m_turnTakingState == 3) GUILayout.Label("Turn: WaitForAgent");
#endif
GUILayout.EndVertical();
GUILayout.EndArea();
{
// background
Rect micFillBar = new Rect(0.94f, 0.25f, 0.03f, 0.70f);
GUI.color = new Color(0, 0, 1, 1);
VHGUI.DrawTexture(micFillBar, m_whiteTexture);
GUI.color = Color.white;
// current recording level
Rect micLevel = micFillBar;
GUI.color = new Color(1, 0, 0, 1);
micLevel.height = m_main.m_prevMicRecordingLevel * micLevel.height;
micLevel.y = micFillBar.y + (micFillBar.height - micLevel.height);
VHGUI.DrawTexture(micLevel, m_whiteTexture);
GUI.color = Color.white;
#if false
// silence threshold
Rect silenceLevel = micFillBar;
GUI.color = Color.white;
silenceLevel.height = 0.005f;
silenceLevel.width += 0.015f;
silenceLevel.x -= (0.015f / 2);
silenceLevel.y = silenceLevel.y + ((1 - m_main.m_Streamer.m_SilenceThreshhold) * micFillBar.height) - (silenceLevel.height / 2);
VHGUI.DrawTexture(silenceLevel, m_whiteTexture);
GUI.color = Color.white;
#endif
}
Time.timeScale = m_timeSlider;
}
}
void OnGUIDebug()
{
if (GUILayout.Button("Switch Screens"))
{
if (NetworkRelay.ConnectionEstablished)
{
NetworkRelay.SendNetworkMessage("switchscreens");
}
else
{
GameObject.FindObjectOfType<Main>().SwitchScreens();
}
}
if (GUILayout.Button("End Interview"))
{
NetworkRelay.SendNetworkMessage("endinterview");
}
if (GUILayout.Button("Quit"))
{
NetworkRelay.SendNetworkMessage("quit");
}
GUILayout.Space(10);
if (VHUtils.IsWindows10OrGreater())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
GUILayout.Label(string.Format("PhraseRecogntionSystem.isSupported: {0}", UnityEngine.Windows.Speech.PhraseRecognitionSystem.isSupported));
GUILayout.Label(string.Format("PhraseRecogntionSystem.status: {0}", UnityEngine.Windows.Speech.PhraseRecognitionSystem.Status));
DictationRecognizer dictationRecognizer = GameObject.FindObjectOfType<DictationRecognizer>();
GUILayout.Label(string.Format("Dictation.status: {0}", dictationRecognizer.m_dictationRecognizer.Status));
GUILayout.Label(string.Format("Dictation.AutoSilenceTimeoutSeconds: {0}", dictationRecognizer.m_dictationRecognizer.AutoSilenceTimeoutSeconds));
GUILayout.Label(string.Format("Dictation.InitialSilenceTimeoutSeconds: {0}", dictationRecognizer.m_dictationRecognizer.InitialSilenceTimeoutSeconds));
if (GUILayout.Button("Dictation Recognizer Start"))
{
dictationRecognizer.StartRecording();
}
if (GUILayout.Button("Dictation Recognizer Stop"))
{
dictationRecognizer.StopRecording();
}
GUILayout.Space(10);
#endif
}
}
void OnGUICharacter()
{
for (int i = 0; i < VitaGlobals.m_vitaCharacterInfo.Count; i++)
{
if (GUILayout.Button(VitaGlobals.m_vitaCharacterInfo[i].displayName))
{
m_main.m_vitaCurrentCharacter = i;
m_main.SpawnCharacter();
}
}
GUILayout.BeginHorizontal();
GUILayout.Label("Gaze:");
if (GUILayout.Button("Camera"))
{
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
MecanimCharacter mecanim = character.GetComponent<MecanimCharacter>();
Debug.Log(m_main.m_camera.gameObject.name);
mecanim.Gaze(m_main.m_camera.gameObject.name);
}
if (GUILayout.Button("Off"))
{
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
MecanimCharacter mecanim = character.GetComponent<MecanimCharacter>();
mecanim.StopGaze(0.5f);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Saccades:");
int prevMode = m_saccadeMode;
m_saccadeMode = GUILayout.SelectionGrid(m_saccadeMode, new string[] { "Listen", "Talk", "Think", "Off" }, 4);
if (prevMode != m_saccadeMode)
{
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
MecanimCharacter mecanim = character.GetComponent<MecanimCharacter>();
CharacterDefines.SaccadeType saccadeType = (CharacterDefines.SaccadeType)m_saccadeMode;
mecanim.GetComponent<SaccadeController>().enabled = saccadeType != CharacterDefines.SaccadeType.End;
mecanim.SetSaccadeBehaviour((CharacterDefines.SaccadeType)m_saccadeMode);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
string newText = GUILayout.TextField(m_sacaadeMultiplier.ToString("F2"), GUILayout.Width(50));
m_sacaadeMultiplier = Convert.ToSingle(newText);
float newSlider = GUILayout.HorizontalSlider(m_sacaadeMultiplier, 0, 1);
if (newSlider != m_sacaadeMultiplier)
{
m_sacaadeMultiplier = newSlider;
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
MecanimCharacter mecanim = character.GetComponent<MecanimCharacter>();
mecanim.GetComponent<SaccadeController>().MagnitudeScaler = m_sacaadeMultiplier;
}
}
GUILayout.EndHorizontal();
GUILayout.Label("Locators:");
for (int i = 0; i < VitaGlobals.m_vitaCharacterInfo.Count; i++)
{
if (GUILayout.Button(VitaGlobals.m_vitaCharacterInfo[i].locatorName))
{
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
GameObject locator = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[i].locatorName);
character.transform.position = locator.transform.position;
character.transform.rotation = locator.transform.rotation;
}
}
GUILayout.Label("Face:");
for (int i = 0; i < m_mouthLayer.Length; i++)
{
GUILayout.BeginHorizontal();
GUILayout.Label(string.Format(@"{0}:", m_mouthLayer[i]), GUILayout.Width(50));
float newSlider = GUILayout.HorizontalSlider(m_mouthSliders[i], 0, 1);
if (newSlider != m_mouthSliders[i])
{
m_mouthSliders[i] = newSlider;
//SmartbodyManager.Get().PythonCommand(string.Format(@"scene.command('char {0} viseme au_{1} {2}')", opponentName, i, newSlider));
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
MecanimCharacter mecanim = character.GetComponent<MecanimCharacter>();
mecanim.SetFloatParam(m_mouthLayer[i], newSlider);
}
GUILayout.EndHorizontal();
}
GUILayout.Space(5);
for (int i = 0; i < m_expressionLayer.Length; i++)
{
GUILayout.Label(string.Format(@"{0}:", m_expressionLayer[i]));
float newSlider = GUILayout.HorizontalSlider(m_expressionSliders[i], 0, 1);
if (newSlider != m_expressionSliders[i])
{
m_expressionSliders[i] = newSlider;
GameObject character = GameObject.Find(VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
MecanimCharacter mecanim = character.GetComponent<MecanimCharacter>();
mecanim.SetFloatParam(m_expressionLayer[i], newSlider);
}
}
}
void OnGUIEnvironment()
{
GUILayout.Label("Scenes:");
for (int i = 0; i < VitaGlobals.m_vitaBackgroundInfo.Count; i++)
{
if (GUILayout.Button(VitaGlobals.m_vitaBackgroundInfo[i].displayName))
{
string environment = VitaGlobals.m_vitaBackgroundInfo[i].sceneName;
PlayerPrefs.SetInt("vitaCurrentBackground", i);
VHUtils.SceneManagerLoadScene(environment);
}
}
GUILayout.Label("Cameras:");
for (int i = 0; i < VitaGlobals.m_vitaBackgroundInfo.Count; i++)
{
string fml = VitaGlobals.m_vitaBackgroundInfo[i].cameraPrefix + "_Fml";
if (GUILayout.Button(fml))
{
m_main.SetCamera(fml);
}
string mle = VitaGlobals.m_vitaBackgroundInfo[i].cameraPrefix + "_Mle";
if (GUILayout.Button(VitaGlobals.m_vitaBackgroundInfo[i].cameraPrefix + "_Mle"))
{
m_main.SetCamera(mle);
}
}
GUILayout.Label("Lighting:");
for (int i = 0; i < VitaGlobals.m_vitaBackgroundInfo.Count; i++)
{
if (GUILayout.Button(VitaGlobals.m_vitaBackgroundInfo[i].lightGroupName))
{
m_main.SetLighting(VitaGlobals.m_vitaBackgroundInfo[i].lightGroupName);
}
}
}
void OnGUIConfig()
{
GUILayout.Space(5);
if (GUILayout.Button("Toggle Stats"))
{
GameObject.FindObjectOfType<DebugInfo>().NextMode();
}
if (GUILayout.Button("Toggle Console"))
{
GameObject.FindObjectOfType<DebugConsole>().ToggleConsole();
}
if (GUILayout.Button("Toggle OnScreenLog"))
{
DebugOnScreenLog debugOnScreenLog = VHUtils.FindChildOfType<DebugOnScreenLog>(GameObject.Find("vhAssets"));
debugOnScreenLog.gameObject.SetActive(!debugOnScreenLog.gameObject.activeSelf);
Debug.LogWarning(string.Format(@"DebugOnScreenLog turned {0}", debugOnScreenLog.gameObject.activeSelf ? "On" : "Off"));
}
GUILayout.Space(5);
m_timeSlider = GUILayout.HorizontalSlider(m_timeSlider, 0.01f, 3);
GUILayout.Label(string.Format("Time: {0}", m_timeSlider));
GUILayout.Space(5);
if (GUILayout.Button(string.Format("{0}", QualitySettings.names[QualitySettings.GetQualityLevel()])))
{
QualitySettings.SetQualityLevel(QualitySettings.GetQualityLevel() + 1 >= QualitySettings.names.Length ? 0 : QualitySettings.GetQualityLevel() + 1);
if (QualitySettings.names[QualitySettings.GetQualityLevel()] == "Fant-NoVsync")
{
Application.targetFrameRate = 0;
}
else
{
Application.targetFrameRate = 60;
}
}
}
void OnGUISounds()
{
if (GUILayout.Button("Switch Screens"))
{
NetworkRelay.SendNetworkMessage("switchscreens");
}
GUILayout.Label("Character: " + VitaGlobals.m_vitaCharacterInfo[m_main.m_vitaCurrentCharacter].prefab);
GUILayout.Label("Scenario: " + VitaGlobals.m_vitaMoods[m_main.m_vitaCurrentMood]);
if (GUILayout.Button("Refresh Query"))
{
m_uttDataFilterCmp = null;
}
if (m_uttDataFilterCmp == null)
{
m_uttDataFilterCmp = GameObject.FindObjectOfType<AGUtteranceDataFilter>();
bool[] m_scenario = m_uttDataFilterCmp.GetScenarioBoolArrayByEnum((VitaGlobals.VitaScenarios)m_main.m_vitaCurrentMood);
m_uttDataPrimaryReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Primary));
m_uttDataAcknowledgementReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Acknowledgement));
m_uttDataAnswerReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Answer));
m_uttDataBuyTimeReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.BuyTime));
m_uttDataDistrationReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Distraction));
m_uttDataElaborationReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Elaboration));
m_uttDataEngagementReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Engagement));
m_uttDataOpeningReponses = m_uttDataFilterCmp.GetSounds(m_main.m_vitaCurrentCharacter, m_scenario, m_uttDataFilterCmp.GetResponseTypeBoolArrayByEnum(VitaGlobals.VitaResponseTypes.Opening));
}
if (m_uttDataFilterCmp == null)
{
return;
}
GUILayout.EndArea();
float soundColumnWidth = 250;
Rect rectAreaColumn1 = new Rect(Screen.width - 100 - soundColumnWidth, 0, soundColumnWidth, Screen.height);
Rect rectAreaColumn2 = new Rect(Screen.width - 100 - (soundColumnWidth * 2), 0, soundColumnWidth, Screen.height);
//Rect rectAreaColumn3 = new Rect(Screen.width - 100 - (soundColumnWidth * 3), 0, soundColumnWidth, Screen.height);
GUILayout.BeginArea(rectAreaColumn2);
//Primary
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Primary");
foreach (AGUtteranceData utterance in m_uttDataPrimaryReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
//GUILayout.EndArea();
//GUILayout.BeginArea(rectAreaColumn2);
//Opening
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Opening");
foreach (AGUtteranceData utterance in m_uttDataOpeningReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
//Engagement
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Engagement");
foreach (AGUtteranceData utterance in m_uttDataEngagementReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
//Ackowledgements
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Acknowledgements");
foreach (AGUtteranceData utterance in m_uttDataAcknowledgementReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
GUILayout.EndArea();
GUILayout.BeginArea(rectAreaColumn1);
//Elaborations
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Elaborations");
foreach (AGUtteranceData utterance in m_uttDataElaborationReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
//Distrations
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Distractions");
foreach (AGUtteranceData utterance in m_uttDataDistrationReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
//Answer
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("Answer");
foreach (AGUtteranceData utterance in m_uttDataAnswerReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
//BuyTime
GUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label("BuyTime");
foreach (AGUtteranceData utterance in m_uttDataBuyTimeReponses)
{
if (GUILayout.Button(utterance.gameObject.name))
{
NetworkRelay.SendNetworkMessage("playcutscene " + utterance.gameObject.name);
}
}
GUILayout.EndVertical();
GUILayout.EndArea();
GUILayout.BeginArea(rectAreaColumn1);
////This section can set up interactive filtering
//GUILayout.Label("Character");
//GUILayout.BeginHorizontal();
//for (int i = 0; i < VitaGlobals.m_vitaCharacters.Length; i++)
//{
// if (GUILayout.Toggle((m_debugSoundsCharacterSelection == i), VitaGlobals.m_vitaCharacters[i], GUILayout.Width(50)))
// {
// m_debugSoundsCharacterSelection = i;
// optionsUpdated = true;
// }
//}
//GUILayout.EndHorizontal();
//GUILayout.Space(5);
//GUILayout.Label("Scenario");
//GUILayout.BeginHorizontal();
//for (int i = 0; i < VitaGlobals.m_vitaMoods.Length; i++)
//{
// if (GUILayout.Toggle((m_debugSoundsScenarioSelection == i), VitaGlobals.m_vitaMoods[i], GUILayout.Width(50)))
// {
// m_debugSoundsScenarioSelection = i;
// optionsUpdated = true;
// }
//}
//GUILayout.EndHorizontal();
//GUILayout.Space(5);
//GUILayout.Label("Disposition(s)");
//GUILayout.BeginHorizontal();
//for (int i = 0; i < VitaGlobals.m_vitaMoods.Length; i++)
//{
// if (GUILayout.Toggle(m_debugSoundsDisposition[i], VitaGlobals.m_vitaMoods[i], GUILayout.Width(50)))
// {
// m_debugSoundsDisposition[i] = true;
// optionsUpdated = true;
// }
// else
// {
// m_debugSoundsDisposition[i] = false;
// optionsUpdated = true;
// }
//}
//GUILayout.EndHorizontal();
//GUILayout.Space(5);
//GUILayout.Label("Response Type(s)");
//GUILayout.BeginHorizontal();
//for (int i = 0; i < VitaGlobals.m_vitaResponseTypes.Length; i++)
//{
// if (GUILayout.Toggle(m_debugSoundsResponseType[i], VitaGlobals.m_vitaResponseTypes[i], GUILayout.Width(50)))
// {
// m_debugSoundsResponseType[i] = true;
// optionsUpdated = true;
// }
// else
// {
// m_debugSoundsResponseType[i] = false;
// optionsUpdated = true;
// }
//}
//GUILayout.EndHorizontal();
//GUILayout.Space(5);
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using Xunit;
namespace System.Reflection.Context.Tests
{
public class VirtualPropertyInfoTests
{
private readonly CustomReflectionContext _customReflectionContext = new VirtualPropertyInfoCustomReflectionContext();
// Points to a PropertyInfo instance created by reflection. This doesn't work in a reflection-only context.
private readonly PropertyInfo[] _virtualProperties;
// Fully functional virtual property with getter and setter.
private readonly PropertyInfo _virtualProperty;
private readonly PropertyInfo _noGetterVirtualProperty;
private readonly PropertyInfo _noSetterVirtualProperty;
// Test data
private readonly TestObject _testObject = new TestObject("Age");
public VirtualPropertyInfoTests()
{
TypeInfo typeInfo = typeof(TestObject).GetTypeInfo();
TypeInfo customTypeInfo = _customReflectionContext.MapType(typeInfo);
_virtualProperties = customTypeInfo.DeclaredProperties.ToArray();
_virtualProperty = _virtualProperties[2];
_noGetterVirtualProperty = _virtualProperties[3];
_noSetterVirtualProperty = _virtualProperties[4];
}
[Fact]
public void Ctor_NullPropertyName_Throws()
{
TypeInfo typeInfo = typeof(NullPropertyNameCase).GetTypeInfo();
TypeInfo customTypeInfo = _customReflectionContext.MapType(typeInfo);
AssertExtensions.Throws<ArgumentNullException>("name", () => customTypeInfo.DeclaredProperties);
}
[Fact]
public void Ctor_EmptyPropertyName_Throws()
{
TypeInfo typeInfo = typeof(EmptyPropertyNameCase).GetTypeInfo();
TypeInfo customTypeInfo = _customReflectionContext.MapType(typeInfo);
Assert.Throws<ArgumentException>(() => customTypeInfo.DeclaredProperties);
}
[Fact]
public void Ctor_NullPropertyType_Throws()
{
TypeInfo typeInfo = typeof(NullPropertyTypeCase).GetTypeInfo();
TypeInfo customTypeInfo = _customReflectionContext.MapType(typeInfo);
AssertExtensions.Throws<ArgumentNullException>("propertyType", () => customTypeInfo.DeclaredProperties);
}
[Fact]
public void Ctor_GetterAndSetterNull_Throws()
{
TypeInfo typeInfo = typeof(NullGetterAndSetterCase).GetTypeInfo();
TypeInfo customTypeInfo = _customReflectionContext.MapType(typeInfo);
Assert.Throws<ArgumentException>(() => customTypeInfo.DeclaredProperties);
}
[Fact]
public void Ctor_WrongPropertyType_Throws()
{
TypeInfo typeInfo = typeof(WrongContextCase).GetTypeInfo();
TypeInfo customTypeInfo = _customReflectionContext.MapType(typeInfo);
Assert.Throws<ArgumentException>(() => customTypeInfo.DeclaredProperties);
}
[Fact]
public void ProjectionTest()
{
Assert.Equal(ProjectionConstants.VirtualPropertyInfo, _virtualProperty.GetType().FullName);
}
[Fact]
public void GetCustomAttributes_WithType_Test()
{
object[] attributes = _virtualProperty.GetCustomAttributes(typeof(TestPropertyAttribute), true);
Assert.Single(attributes);
Assert.IsType<TestPropertyAttribute>(attributes[0]);
}
[Fact]
public void GetCustomAttributes_NoType_Test()
{
object[] attributes = _virtualProperty.GetCustomAttributes(false);
Assert.Single(attributes);
Assert.IsType<TestPropertyAttribute>(attributes[0]);
}
[Fact]
public void GetCustomAttributesDataTest()
{
// This will never return any results as virtual properties never have custom attributes
// defined in code as they are instantiated during runtime. But as the method is overriden
// we call it for code coverage.
IList<CustomAttributeData> customAttributesData = _virtualProperty.GetCustomAttributesData();
Assert.Empty(customAttributesData);
}
[Fact]
public void IsDefinedTest()
{
Assert.True(_virtualProperty.IsDefined(typeof(TestPropertyAttribute), true));
Assert.True(_virtualProperty.IsDefined(typeof(TestPropertyAttribute), false));
Assert.False(_virtualProperty.IsDefined(typeof(DataContractAttribute), true));
Assert.False(_virtualProperty.IsDefined(typeof(DataContractAttribute), false));
}
[Fact]
public void ToStringTest()
{
Assert.Equal(typeof(int).FullName + " " + "number", _virtualProperty.ToString());
}
[Fact]
public void AttributesTest()
{
Assert.Equal(PropertyAttributes.None, _virtualProperty.Attributes);
}
[Fact]
public void CanReadTest()
{
Assert.True(_virtualProperty.CanRead);
Assert.False(_noGetterVirtualProperty.CanRead);
}
[Fact]
public void CanWriteTest()
{
Assert.True(_virtualProperty.CanWrite);
Assert.False(_noSetterVirtualProperty.CanWrite);
}
[Fact]
public void MetadataTokenTest()
{
Assert.Throws<InvalidOperationException>(() => _virtualProperty.MetadataToken);
}
[Fact]
public void ModuleTest()
{
Assert.Equal(ProjectionConstants.CustomModule, _virtualProperty.Module.GetType().FullName);
}
[Fact]
public void ReflectedTypeTest()
{
Assert.Equal(ProjectionConstants.CustomType, _virtualProperty.ReflectedType.GetType().FullName);
}
[Fact]
public void GetAccessorsTest()
{
MethodInfo[] virtualAccessors = _virtualProperty.GetAccessors(false);
Assert.Equal(2, virtualAccessors.Length);
Assert.Equal(ProjectionConstants.VirtualPropertyInfoGetter, virtualAccessors[0].GetType().FullName);
Assert.Equal(ProjectionConstants.VirtualPropertyInfoSetter, virtualAccessors[1].GetType().FullName);
virtualAccessors = _noGetterVirtualProperty.GetAccessors(false);
Assert.Equal(1, virtualAccessors.Length);
Assert.Equal(ProjectionConstants.VirtualPropertyInfoSetter, virtualAccessors[0].GetType().FullName);
virtualAccessors = _noSetterVirtualProperty.GetAccessors(false);
Assert.Equal(1, virtualAccessors.Length);
Assert.Equal(ProjectionConstants.VirtualPropertyInfoGetter, virtualAccessors[0].GetType().FullName);
}
[Fact]
public void GetIndexParametersTest()
{
// Projecting
ParameterInfo[] customParameters = _virtualProperties[1].GetIndexParameters();
Assert.Single(customParameters);
Assert.Equal(ProjectionConstants.CustomParameter, customParameters[0].GetType().FullName);
// Virtual
customParameters = _noGetterVirtualProperty.GetIndexParameters();
Assert.Empty(customParameters);
// Invoke twice to get cached value.
customParameters = _noGetterVirtualProperty.GetIndexParameters();
Assert.Empty(customParameters);
customParameters = _noSetterVirtualProperty.GetIndexParameters();
Assert.Empty(customParameters);
// Invoke twice to get cached value.
customParameters = _noSetterVirtualProperty.GetIndexParameters();
Assert.Empty(customParameters);
}
[Fact]
public void GetValue_NoGetter_Throws()
{
Assert.Throws<ArgumentException>(() =>
_noGetterVirtualProperty.GetValue(_testObject, BindingFlags.Default, null, null, CultureInfo.InvariantCulture));
}
[Fact]
public void GetValue_HasGetter_Success()
{
object returnVal = _noSetterVirtualProperty.GetValue(_testObject, BindingFlags.Default, null, null, CultureInfo.InvariantCulture);
Assert.Equal(42, returnVal);
}
[Fact]
public void SetValue_NoSetter_Throws()
{
Assert.Throws<ArgumentException>(() =>
_noSetterVirtualProperty.SetValue(_testObject, 42, BindingFlags.Default, null, null, CultureInfo.InvariantCulture));
}
[Fact]
public void SetValue_HasSetter_Success()
{
_noGetterVirtualProperty.SetValue(_testObject, 42, BindingFlags.Default, null, null, CultureInfo.InvariantCulture);
}
[Fact]
public void SetValue_HasSetterWithIndex_Success()
{
_noGetterVirtualProperty.SetValue(_testObject, 42, BindingFlags.Default, null, new object[] { }, CultureInfo.InvariantCulture);
}
[Fact]
public void GetConstantValueTest()
{
Assert.Throws<InvalidOperationException>(() => _virtualProperty.GetConstantValue());
}
[Fact]
public void GetRawConstantValueTest()
{
Assert.Throws<InvalidOperationException>(() => _virtualProperty.GetRawConstantValue());
}
[Fact]
public void GetOptionalCustomModifiersTest()
{
Type[] customTypes = _virtualProperty.GetOptionalCustomModifiers();
Assert.Empty(customTypes);
}
[Fact]
public void GetRequiredCustomModifiersTest()
{
Type[] customTypes = _virtualProperty.GetRequiredCustomModifiers();
Assert.Empty(customTypes);
}
[Fact]
public void GetHashCodeTest()
{
_virtualProperty.GetHashCode();
}
}
}
| |
// 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.ServiceModel;
using System.ServiceModel.Channels;
using TestTypes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Infrastructure.Common;
using Xunit;
public static partial class TypedProxyTests
{
// ServiceContract typed proxy tests create a ChannelFactory using a provided [ServiceContract] Interface which...
// returns a generated proxy based on that Interface.
// ChannelShape typed proxy tests create a ChannelFactory using a WCF understood channel shape which...
// returns a generated proxy based on the channel shape used, such as...
// IRequestChannel (for a request-reply message exchange pattern)
// IDuplexChannel (for a two-way duplex message exchange pattern)
private const string action = "http://tempuri.org/IWcfService/MessageRequestReply";
private const string clientMessage = "[client] This is my request.";
static TimeSpan maxTestWaitTime = TimeSpan.FromSeconds(10);
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call()
{
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new TextMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());
ServiceContract_TypedProxy_AsyncBeginEnd_Call(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncBeginEnd_Call");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call()
{
NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None);
ServiceContract_TypedProxy_AsyncBeginEnd_Call(netTcpBinding, Endpoints.Tcp_NoSecurity_Address, "ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback()
{
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new TextMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());
ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call_WithNoCallback()
{
NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None);
ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback(netTcpBinding, Endpoints.Tcp_NoSecurity_Address, "ServiceContract_TypedProxy_NetTcpBinding_AsyncBeginEnd_Call_WithNoCallback");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_AsyncBeginEnd_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: TypedProxy_AsyncBeginEnd_Call_WithSingleThreadedSyncContext timed out");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncTask_Call()
{
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new TextMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());
ServiceContract_TypedProxy_AsyncTask_Call(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncTask_Call");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_NetTcpBinding_AsyncTask_Call()
{
NetTcpBinding netTcpBinding = new NetTcpBinding();
netTcpBinding.Security.Mode = SecurityMode.None;
ServiceContract_TypedProxy_AsyncTask_Call(netTcpBinding, Endpoints.Tcp_NoSecurity_Address, "ServiceContract_TypedProxy_NetTcpBinding_AsyncTask_Call");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_AsyncTask_Call_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_AsyncTask_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: TypedProxy_AsyncTask_Call_WithSingleThreadedSyncContext timed out");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_Synchronous_Call()
{
// This test verifies a typed proxy can call a service operation synchronously
StringBuilder errorBuilder = new StringBuilder();
try
{
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new TextMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());
// Note the service interface used. It was manually generated with svcutil.
ChannelFactory<IWcfServiceGenerated> factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
IWcfServiceGenerated serviceProxy = factory.CreateChannel();
string result = serviceProxy.Echo("Hello");
if (!string.Equals(result, "Hello"))
{
errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));
}
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TypedProxySynchronousCall FAILED with the following errors: {0}", errorBuilder));
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_Synchronous_Call_WithSingleThreadedSyncContext()
{
bool success = Task.Run(() =>
{
TestTypes.SingleThreadSynchronizationContext.Run(() =>
{
Task.Factory.StartNew(() => TypedProxyTests.ServiceContract_TypedProxy_Synchronous_Call(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait();
});
}).Wait(ScenarioTestHelpers.TestTimeout);
Assert.True(success, "Test Scenario: TypedProxy_Synchronous_Call_WithSingleThreadedSyncContext timed out");
}
[WcfFact]
[OuterLoop]
public static void ServiceContract_TypedProxy_Task_Call_WithSyncContext_ContinuesOnSameThread()
{
// This test verifies a task based call to a service operation continues on the same thread
StringBuilder errorBuilder = new StringBuilder();
try
{
CustomBinding customBinding = new CustomBinding();
customBinding.Elements.Add(new TextMessageEncodingBindingElement());
customBinding.Elements.Add(new HttpTransportBindingElement());
ChannelFactory<IWcfServiceGenerated> factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
IWcfServiceGenerated serviceProxy = factory.CreateChannel();
string result = String.Empty;
bool success = Task.Run(() =>
{
SingleThreadSynchronizationContext.Run(async delegate
{
int startThread = Environment.CurrentManagedThreadId;
result = await serviceProxy.EchoAsync("Hello");
if (startThread != Environment.CurrentManagedThreadId)
{
errorBuilder.AppendLine(String.Format("Expected continuation to happen on thread {0} but actually continued on thread {1}",
startThread, Environment.CurrentManagedThreadId));
}
});
}).Wait(ScenarioTestHelpers.TestTimeout);
if (!success)
{
errorBuilder.AppendLine(String.Format("Test didn't complete within the expected time"));
}
if (!string.Equals(result, "Hello"))
{
errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));
}
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TaskCallWithSynchContextContinuesOnSameThread FAILED with the following errors: {0}", errorBuilder));
}
[WcfFact]
[OuterLoop]
public static void ChannelShape_TypedProxy_InvokeIRequestChannel()
{
string address = Endpoints.DefaultCustomHttp_Address;
StringBuilder errorBuilder = new StringBuilder();
try
{
CustomBinding binding = new CustomBinding(new BindingElement[] {
new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8),
new HttpTransportBindingElement() });
EndpointAddress endpointAddress = new EndpointAddress(address);
// Create the channel factory for the request-reply message exchange pattern.
var factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress);
// Create the channel.
IRequestChannel channel = factory.CreateChannel();
channel.Open();
// Create the Message object to send to the service.
Message requestMessage = Message.CreateMessage(
binding.MessageVersion,
action,
new CustomBodyWriter(clientMessage));
// Send the Message and receive the Response.
Message replyMessage = channel.Request(requestMessage);
string replyMessageAction = replyMessage.Headers.Action;
if (!string.Equals(replyMessageAction, action + "Response"))
{
errorBuilder.AppendLine(String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction));
}
var replyReader = replyMessage.GetReaderAtBodyContents();
string actualResponse = replyReader.ReadElementContentAsString();
string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";
if (!string.Equals(actualResponse, expectedResponse))
{
errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse));
}
replyMessage.Close();
channel.Close();
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeRequestChannelViaProxy FAILED with the following errors: {0}", errorBuilder));
}
[WcfFact]
[OuterLoop]
public static void ChannelShape_TypedProxy_InvokeIRequestChannelTimeout()
{
string address = Endpoints.DefaultCustomHttp_Address;
StringBuilder errorBuilder = new StringBuilder();
try
{
CustomBinding binding = new CustomBinding(new BindingElement[] {
new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8),
new HttpTransportBindingElement() });
EndpointAddress endpointAddress = new EndpointAddress(address);
// Create the channel factory for the request-reply message exchange pattern.
var factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress);
// Create the channel.
IRequestChannel channel = factory.CreateChannel();
channel.Open();
// Create the Message object to send to the service.
Message requestMessage = Message.CreateMessage(
binding.MessageVersion,
action,
new CustomBodyWriter(clientMessage));
// Send the Message and receive the Response.
Message replyMessage = channel.Request(requestMessage, TimeSpan.FromSeconds(60));
string replyMessageAction = replyMessage.Headers.Action;
if (!string.Equals(replyMessageAction, action + "Response"))
{
errorBuilder.AppendLine(String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction));
}
var replyReader = replyMessage.GetReaderAtBodyContents();
string actualResponse = replyReader.ReadElementContentAsString();
string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";
if (!string.Equals(actualResponse, expectedResponse))
{
errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse));
}
replyMessage.Close();
channel.Close();
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeIRequestChannelViaProxyTimeout FAILED with the following errors: {0}", errorBuilder));
}
[WcfFact]
[OuterLoop]
public static void ChannelShape_TypedProxy_InvokeIRequestChannelAsync()
{
string address = Endpoints.DefaultCustomHttp_Address;
StringBuilder errorBuilder = new StringBuilder();
try
{
CustomBinding binding = new CustomBinding(new BindingElement[] {
new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8),
new HttpTransportBindingElement() });
EndpointAddress endpointAddress = new EndpointAddress(address);
// Create the channel factory for the request-reply message exchange pattern.
var factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress);
// Create the channel.
IRequestChannel channel = factory.CreateChannel();
channel.Open();
// Create the Message object to send to the service.
Message requestMessage = Message.CreateMessage(
binding.MessageVersion,
action,
new CustomBodyWriter(clientMessage));
// Send the Message and receive the Response.
IAsyncResult ar = channel.BeginRequest(requestMessage, null, null);
Message replyMessage = channel.EndRequest(ar);
string replyMessageAction = replyMessage.Headers.Action;
if (!string.Equals(replyMessageAction, action + "Response"))
{
errorBuilder.AppendLine(String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction));
}
var replyReader = replyMessage.GetReaderAtBodyContents();
string actualResponse = replyReader.ReadElementContentAsString();
string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";
if (!string.Equals(actualResponse, expectedResponse))
{
errorBuilder.AppendLine(String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse));
}
replyMessage.Close();
channel.Close();
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: InvokeIRequestChannelViaProxyAsync FAILED with the following errors: {0}", errorBuilder));
}
public class DuplexChannelServiceCallback : IDuplexChannelCallback
{
private TaskCompletionSource<Guid> _tcs;
public DuplexChannelServiceCallback()
{
_tcs = new TaskCompletionSource<Guid>();
}
public Guid CallbackGuid
{
get
{
if (_tcs.Task.Wait(maxTestWaitTime))
{
return _tcs.Task.Result;
}
throw new TimeoutException(string.Format("Not completed within the alloted time of {0}", maxTestWaitTime));
}
}
public void OnPingCallback(Guid guid)
{
_tcs.SetResult(guid);
}
}
[ServiceContract(CallbackContract = typeof(IDuplexChannelCallback))]
public interface IDuplexChannelService
{
[OperationContract(IsOneWay = true)]
void Ping(Guid guid);
}
public interface IDuplexChannelCallback
{
[OperationContract(IsOneWay = true)]
void OnPingCallback(Guid guid);
}
private static void ServiceContract_TypedProxy_AsyncBeginEnd_Call(Binding binding, string endpoint, string testName)
{
// Verifies a typed proxy can call a service operation asynchronously using Begin/End
StringBuilder errorBuilder = new StringBuilder();
try
{
ChannelFactory<IWcfServiceBeginEndGenerated> factory = new ChannelFactory<IWcfServiceBeginEndGenerated>(binding, new EndpointAddress(endpoint));
IWcfServiceBeginEndGenerated serviceProxy = factory.CreateChannel();
string result = null;
ManualResetEvent waitEvent = new ManualResetEvent(false);
// The callback is optional with this Begin call, but we want to test that it works.
// This delegate should execute when the call has completed, and that is how it gets the result of the call.
AsyncCallback callback = (iar) =>
{
result = serviceProxy.EndEcho(iar);
waitEvent.Set();
};
IAsyncResult ar = serviceProxy.BeginEcho("Hello", callback, null);
// This test requires the callback to be called.
// An actual timeout should call the callback, but we still set
// a maximum wait time in case that does not happen.
bool success = waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout);
if (!success)
{
errorBuilder.AppendLine("AsyncCallback was not called.");
}
if (!string.Equals(result, "Hello"))
{
errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));
}
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: {0} FAILED with the following errors: {1}", testName, errorBuilder));
}
private static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback(Binding binding, string endpoint, string testName)
{
// This test verifies a typed proxy can call a service operation asynchronously using Begin/End
StringBuilder errorBuilder = new StringBuilder();
try
{
ChannelFactory<IWcfServiceBeginEndGenerated> factory = new ChannelFactory<IWcfServiceBeginEndGenerated>(binding, new EndpointAddress(endpoint));
IWcfServiceBeginEndGenerated serviceProxy = factory.CreateChannel();
string result = null;
IAsyncResult ar = serviceProxy.BeginEcho("Hello", null, null);
// An actual timeout should complete the ar, but we still set
// a maximum wait time in case that does not happen.
bool success = ar.AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout);
if (success)
{
result = serviceProxy.EndEcho(ar);
}
else
{
errorBuilder.AppendLine("AsyncCallback was not called.");
}
if (!string.Equals(result, "Hello"))
{
errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));
}
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: {0} FAILED with the following errors: {1}", testName, errorBuilder));
}
private static void ServiceContract_TypedProxy_AsyncTask_Call(Binding binding, string endpoint, string testName)
{
// This test verifies a typed proxy can call a service operation asynchronously using Task<string>
StringBuilder errorBuilder = new StringBuilder();
try
{
ChannelFactory<IWcfServiceGenerated> factory = new ChannelFactory<IWcfServiceGenerated>(binding, new EndpointAddress(endpoint));
IWcfServiceGenerated serviceProxy = factory.CreateChannel();
Task<string> task = serviceProxy.EchoAsync("Hello");
string result = task.Result;
if (!string.Equals(result, "Hello"))
{
errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));
}
factory.Close();
}
catch (Exception ex)
{
errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TypedProxyAsyncTaskCall FAILED with the following errors: {0}", errorBuilder));
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using OpenCvSharp.Dnn;
using OpenCvSharp.Internal;
using OpenCvSharp.Internal.Vectors;
// ReSharper disable UnusedMember.Global
// ReSharper disable IdentifierTypo
// ReSharper disable InconsistentNaming
// ReSharper disable CommentTypo
namespace OpenCvSharp.DnnSuperres
{
/// <summary>
/// A class to upscale images via convolutional neural networks.
/// The following four models are implemented:
/// - edsr
/// - espcn
/// - fsrcnn
/// - lapsrn
/// </summary>
public class DnnSuperResImpl : DisposableCvObject
{
/// <inheritdoc />
/// <summary>
/// Empty constructor
/// </summary>
public DnnSuperResImpl()
{
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_new1(out ptr));
}
/// <inheritdoc />
/// <summary>
/// Constructor which immediately sets the desired model
/// </summary>
/// <param name="algo">String containing one of the desired models:
/// - edsr
/// - espcn
/// - fsrcnn
/// - lapsrn</param>
/// <param name="scale">Integer specifying the upscale factor</param>
public DnnSuperResImpl(string algo, int scale)
{
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_new2(algo, scale, out ptr));
}
/// <inheritdoc />
/// <summary>
/// </summary>
protected DnnSuperResImpl(IntPtr ptr)
{
this.ptr = ptr;
}
/// <inheritdoc />
/// <summary>
/// </summary>
protected override void DisposeUnmanaged()
{
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_delete(ptr));
base.DisposeUnmanaged();
}
/// <summary>
/// Read the model from the given path
/// </summary>
/// <param name="path">Path to the model file.</param>
/// <returns></returns>
public void ReadModel(string path)
{
ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_readModel1(ptr, path));
GC.KeepAlive(this);
}
/// <summary>
/// Read the model from the given path
/// </summary>
/// <param name="weights">Path to the model weights file.</param>
/// <param name="definition">Path to the model definition file.</param>
/// <returns></returns>
public void ReadModel(string weights, string definition)
{
ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_readModel2(ptr, weights, definition));
GC.KeepAlive(this);
}
/// <summary>
/// Set desired model
/// </summary>
/// <param name="algo">String containing one of the desired models:
/// - edsr
/// - espcn
/// - fsrcnn
/// - lapsrn</param>
/// <param name="scale">Integer specifying the upscale factor</param>
/// <returns></returns>
public void SetModel(string algo, int scale)
{
ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_setModel(ptr, algo, scale));
GC.KeepAlive(this);
}
/// <summary>
/// Ask network to use specific computation backend where it supported.
/// </summary>
/// <param name="backendId">backend identifier.</param>
public void SetPreferableBackend(Backend backendId)
{
ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_setPreferableBackend(ptr, (int)backendId));
GC.KeepAlive(this);
}
/// <summary>
/// Ask network to make computations on specific target device.
/// </summary>
/// <param name="targetId">target identifier.</param>
public void SetPreferableTarget(Target targetId)
{
ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_setPreferableTarget(ptr, (int)targetId));
GC.KeepAlive(this);
}
/// <summary>
/// Upsample via neural network
/// </summary>
/// <param name="img">Image to upscale</param>
/// <param name="result">Destination upscaled image</param>
public void Upsample(InputArray img, OutputArray result)
{
ThrowIfDisposed();
if (img == null)
throw new ArgumentNullException(nameof(img));
if (result == null)
throw new ArgumentNullException(nameof(result));
img.ThrowIfDisposed();
result.ThrowIfNotReady();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_upsample(ptr, img.CvPtr, result.CvPtr));
GC.KeepAlive(this);
GC.KeepAlive(img);
result.Fix();
}
/// <summary>
/// Upsample via neural network of multiple outputs
/// </summary>
/// <param name="img">Image to upscale</param>
/// <param name="imgsNew">Destination upscaled images</param>
/// <param name="scaleFactors">Scaling factors of the output nodes</param>
/// <param name="nodeNames">Names of the output nodes in the neural network</param>
[SuppressMessage("Maintainability", "CA1508: Avoid dead conditional code")]
public void UpsampleMultioutput(
InputArray img, out Mat[] imgsNew, IEnumerable<int> scaleFactors, IEnumerable<string> nodeNames)
{
ThrowIfDisposed();
if (img == null)
throw new ArgumentNullException(nameof(img));
if (scaleFactors == null)
throw new ArgumentNullException(nameof(scaleFactors));
if (nodeNames == null)
throw new ArgumentNullException(nameof(nodeNames));
using var imgsNewVec = new VectorOfMat();
var scaleFactorsArray = scaleFactors as int[] ?? scaleFactors.ToArray();
var nodeNamesArray = nodeNames as string[] ?? nodeNames.ToArray();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_upsampleMultioutput(
ptr, img.CvPtr, imgsNewVec.CvPtr,
scaleFactorsArray, scaleFactorsArray.Length,
nodeNamesArray, nodeNamesArray.Length));
GC.KeepAlive(this);
imgsNew = imgsNewVec.ToArray();
}
/// <summary>
/// Returns the scale factor of the model
/// </summary>
/// <returns>Current scale factor.</returns>
public int GetScale()
{
ThrowIfDisposed();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_getScale(
ptr, out int ret));
GC.KeepAlive(this);
return ret;
}
/// <summary>
/// Returns the scale factor of the model
/// </summary>
/// <returns>Current algorithm.</returns>
public string GetAlgorithm()
{
ThrowIfDisposed();
using var result = new StdString();
NativeMethods.HandleException(
NativeMethods.dnn_superres_DnnSuperResImpl_getAlgorithm(
ptr, result.CvPtr));
GC.KeepAlive(this);
return result.ToString();
}
}
}
| |
using Signum.Engine.Authorization;
using System.Xml.Linq;
namespace Signum.Entities.Authorization;
public interface IMerger<K, A>
{
A Merge(K key, Lite<RoleEntity> role, IEnumerable<KeyValuePair<Lite<RoleEntity>, A>> baseValues);
Func<K, A> MergeDefault(Lite<RoleEntity> role);
}
public interface IManualAuth<K, A>
{
A GetAllowed(Lite<RoleEntity> role, K key);
void SetAllowed(Lite<RoleEntity> role, K key, A allowed);
}
class Coercer<A, K>
{
public static readonly Coercer<A, K> None = new Coercer<A, K>();
public virtual Func<Lite<RoleEntity>, A, A> GetCoerceValueManual(K key) { return (role, allowed) => allowed; }
public virtual Func<K, A, A> GetCoerceValue(Lite<RoleEntity> role) { return (key, allowed) => allowed; }
}
class AuthCache<RT, AR, R, K, A> : IManualAuth<K, A>
where RT : RuleEntity<R, A>, new()
where AR : AllowedRule<R, A>, new()
where A : notnull
where R : class
where K : notnull
{
readonly ResetLazy<Dictionary<Lite<RoleEntity>, RoleAllowedCache>> runtimeRules;
Func<R, K> ToKey;
Func<K, R> ToEntity;
Expression<Func<R, R, bool>> IsEquals;
IMerger<K, A> merger;
Coercer<A, K> coercer;
public AuthCache(SchemaBuilder sb, Func<R, K> toKey, Func<K, R> toEntity,
Expression<Func<R, R, bool>> isEquals, IMerger<K, A> merger, bool invalidateWithTypes, Coercer<A, K>? coercer = null)
{
this.ToKey = toKey;
this.ToEntity = toEntity;
this.merger = merger;
this.IsEquals = isEquals;
this.coercer = coercer ?? Coercer<A, K>.None;
runtimeRules = sb.GlobalLazy(this.NewCache,
invalidateWithTypes ?
new InvalidateWith(typeof(RT), typeof(RoleEntity), typeof(RuleTypeEntity)) :
new InvalidateWith(typeof(RT), typeof(RoleEntity)), AuthLogic.NotifyRulesChanged);
}
A IManualAuth<K, A>.GetAllowed(Lite<RoleEntity> role, K key)
{
R resource = ToEntity(key);
ManualResourceCache miniCache = new ManualResourceCache(key, resource, IsEquals, merger, coercer.GetCoerceValueManual(key));
return miniCache.GetAllowed(role);
}
void IManualAuth<K, A>.SetAllowed(Lite<RoleEntity> role, K key, A allowed)
{
R resource = ToEntity(key);
var keyCoercer = coercer.GetCoerceValueManual(key);
ManualResourceCache miniCache = new ManualResourceCache(key, resource, IsEquals, merger, keyCoercer);
allowed = keyCoercer(role, allowed);
if (miniCache.GetAllowed(role).Equals(allowed))
return;
IQueryable<RT> query = Database.Query<RT>().Where(a => IsEquals.Evaluate(a.Resource, resource) && a.Role.Is(role));
if (miniCache.GetAllowedBase(role).Equals(allowed))
{
if (query.UnsafeDelete() == 0)
throw new InvalidOperationException("Inconsistency in the data");
}
else
{
if (query.UnsafeUpdate().Set(a => a.Allowed, a => allowed).Execute() == 0)
new RT
{
Role = role,
Resource = resource,
Allowed = allowed,
}.Save();
}
}
public class ManualResourceCache
{
readonly Dictionary<Lite<RoleEntity>, A> specificRules;
readonly IMerger<K, A> merger;
readonly Func<Lite<RoleEntity>, A, A> coercer;
readonly K key;
public ManualResourceCache(K key, R resource, Expression<Func<R, R, bool>> isEquals, IMerger<K, A> merger, Func<Lite<RoleEntity>, A, A> coercer)
{
this.key = key;
var list = (from r in Database.Query<RT>()
where isEquals.Evaluate(r.Resource, resource)
select new { r.Role, r.Allowed }).ToList();
specificRules = list.ToDictionary(a => a.Role!, a => a.Allowed); /*CSBUG*/
this.coercer = coercer;
this.merger = merger;
}
public A GetAllowed(Lite<RoleEntity> role)
{
if (specificRules.TryGetValue(role, out A? result))
return coercer(role, result);
return GetAllowedBase(role);
}
public A GetAllowedBase(Lite<RoleEntity> role)
{
var result = merger.Merge(key, role, AuthLogic.RelatedTo(role).Select(r => KeyValuePair.Create(r, GetAllowed(r))));
return coercer(role, result);
}
}
Dictionary<Lite<RoleEntity>, RoleAllowedCache> NewCache()
{
List<Lite<RoleEntity>> roles = AuthLogic.RolesInOrder().ToList();
Dictionary<Lite<RoleEntity>, Dictionary<K, A>> realRules =
Database.Query<RT>()
.Select(a => new { a.Role, a.Allowed, a.Resource })
.AgGroupToDictionary(ru => ru.Role!, gr => gr
.SelectCatch(ru => KeyValuePair.Create(ToKey(ru.Resource!), ru.Allowed))
.ToDictionaryEx());
Dictionary<Lite<RoleEntity>, RoleAllowedCache> newRules = new Dictionary<Lite<RoleEntity>, RoleAllowedCache>();
foreach (var role in roles)
{
var related = AuthLogic.RelatedTo(role);
newRules.Add(role, new RoleAllowedCache(
role,
merger,
related.Select(r => newRules.GetOrThrow(r)).ToList(),
realRules.TryGetC(role),
coercer.GetCoerceValue(role)));
}
return newRules;
}
internal void GetRules(BaseRulePack<AR> rules, IEnumerable<R> resources)
{
RoleAllowedCache cache = runtimeRules.Value.GetOrThrow(rules.Role);
rules.MergeStrategy = AuthLogic.GetMergeStrategy(rules.Role);
rules.SubRoles = AuthLogic.RelatedTo(rules.Role).ToMList();
rules.Rules = (from r in resources
let k = ToKey(r)
select new AR()
{
Resource = r,
AllowedBase = cache.GetAllowedBase(k),
Allowed = cache.GetAllowed(k)
}).ToMList();
}
internal void SetRules(BaseRulePack<AR> rules, Expression<Func<R, bool>> filterResources)
{
using (AuthLogic.Disable())
{
var current = Database.Query<RT>().Where(r => r.Role.Is(rules.Role) && filterResources.Evaluate(r.Resource)).ToDictionary(a => a.Resource);
var should = rules.Rules.Where(a => a.Overriden).ToDictionary(r => r.Resource);
Synchronizer.Synchronize(should, current,
(p, ar) => new RT { Resource = p, Role = rules.Role, Allowed = ar.Allowed }.Save(),
(p, pr) => pr.Delete(),
(p, ar, pr) =>
{
pr.Allowed = ar.Allowed;
if (pr.IsGraphModified)
pr.Save();
});
}
}
internal A GetAllowed(Lite<RoleEntity> role, K key)
{
return runtimeRules.Value.GetOrThrow(role).GetAllowed(key);
}
internal DefaultDictionary<K, A> GetDefaultDictionary()
{
return runtimeRules.Value.GetOrThrow(RoleEntity.Current).DefaultDictionary();
}
public class RoleAllowedCache
{
readonly Lite<RoleEntity> role;
readonly IMerger<K, A> merger;
readonly Func<K, A, A> coercer;
readonly DefaultDictionary<K, A> rules;
readonly List<RoleAllowedCache> baseCaches;
public RoleAllowedCache(Lite<RoleEntity> role, IMerger<K, A> merger, List<RoleAllowedCache> baseCaches, Dictionary<K, A>? newValues, Func<K, A, A> coercer)
{
this.role = role;
this.merger = merger;
this.coercer = coercer;
this.baseCaches = baseCaches;
Func<K, A> defaultAllowed = merger.MergeDefault(role);
Func<K, A> baseAllowed = k => merger.Merge(k, role, baseCaches.Select(b => KeyValuePair.Create(b.role, b.GetAllowed(k))));
var keys = baseCaches
.Where(b => b.rules.OverrideDictionary != null)
.SelectMany(a => a.rules.OverrideDictionary!.Keys)
.ToHashSet();
Dictionary<K, A>? tmpRules = keys.ToDictionary(k => k, baseAllowed);
if (newValues != null)
tmpRules.SetRange(newValues);
tmpRules = Simplify(tmpRules, defaultAllowed, baseAllowed);
rules = new DefaultDictionary<K, A>(defaultAllowed, tmpRules);
}
internal Dictionary<K, A>? Simplify(Dictionary<K, A> dictionary, Func<K, A> defaultAllowed, Func<K, A> baseAllowed)
{
if (dictionary == null || dictionary.Count == 0)
return null;
dictionary.RemoveRange(dictionary.Where(p =>
p.Value.Equals(defaultAllowed(p.Key)) &&
p.Value.Equals(baseAllowed(p.Key))).Select(p => p.Key).ToList());
if (dictionary.Count == 0)
return null;
return dictionary;
}
public A GetAllowed(K key)
{
var raw = rules.GetAllowed(key);
return coercer(key, raw);
}
public A GetAllowedBase(K key)
{
var raw = merger.Merge(key, role, baseCaches.Select(b => KeyValuePair.Create(b.role, b.GetAllowed(key))));
return coercer(key, raw);
}
internal DefaultDictionary<K, A> DefaultDictionary()
{
return this.rules;
}
}
internal XElement ExportXml(XName rootName, XName elementName, Func<K, string> resourceToString, Func<A, string> allowedToString, List<K>? allKeys)
{
var rules = runtimeRules.Value;
return new XElement(rootName,
(from r in AuthLogic.RolesInOrder()
let rac = rules.GetOrThrow(r)
select new XElement("Role",
new XAttribute("Name", r.ToString()!),
from k in allKeys ?? (rac.DefaultDictionary().OverrideDictionary?.Keys).EmptyIfNull()
let allowedBase = rac.GetAllowedBase(k)
let allowed = rac.GetAllowed(k)
where allKeys != null || !allowed.Equals(allowedBase)
let resource = resourceToString(k)
orderby resource
select new XElement(elementName,
new XAttribute("Resource", resource),
new XAttribute("Allowed", allowedToString(allowed)))
)));
}
internal SqlPreCommand? ImportXml(XElement element, XName rootName, XName elementName, Dictionary<string, Lite<RoleEntity>> roles,
Func<string, R?> toResource, Func<string, A> parseAllowed)
{
var current = Database.RetrieveAll<RT>().GroupToDictionary(a => a.Role);
var xRoles = (element.Element(rootName)?.Elements("Role")).EmptyIfNull();
var should = xRoles.ToDictionary(x => roles.GetOrThrow(x.Attribute("Name")!.Value));
Table table = Schema.Current.Table(typeof(RT));
return Synchronizer.SynchronizeScript(Spacing.Double, should, current,
createNew: (role, x) =>
{
var dic = (from xr in x.Elements(elementName)
let r = toResource(xr.Attribute("Resource")!.Value)
where r != null
select KeyValuePair.Create(r, parseAllowed(xr.Attribute("Allowed")!.Value)))
.ToDictionaryEx("{0} rules for {1}".FormatWith(typeof(R).NiceName(), role));
SqlPreCommand? restSql = dic.Select(kvp => table.InsertSqlSync(new RT
{
Resource = kvp.Key,
Role = role,
Allowed = kvp.Value
}, comment: Comment(role, kvp.Key, kvp.Value))).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true);
return restSql;
},
removeOld: (role, list) => list.Select(rt => table.DeleteSqlSync(rt, null)).Combine(Spacing.Simple)?.Do(p => p.GoBefore = true),
mergeBoth: (role, x, list) =>
{
var def = list.SingleOrDefaultEx(a => a.Resource == null);
var shouldResources = (from xr in x.Elements(elementName)
let r = toResource(xr.Attribute("Resource")!.Value)
where r != null
select KeyValuePair.Create(ToKey(r), xr))
.ToDictionaryEx("{0} rules for {1}".FormatWith(typeof(R).NiceName(), role));
var currentResources = list.Where(a => a.Resource != null).ToDictionary(a => ToKey(a.Resource));
SqlPreCommand? restSql = Synchronizer.SynchronizeScript(Spacing.Simple, shouldResources, currentResources,
(r, xr) =>
{
var a = parseAllowed(xr.Attribute("Allowed")!.Value);
return table.InsertSqlSync(new RT { Resource = ToEntity(r), Role = role, Allowed = a }, comment: Comment(role, ToEntity(r), a));
},
(r, rt) => table.DeleteSqlSync(rt, null, Comment(role, ToEntity(r), rt.Allowed)),
(r, xr, rt) =>
{
var oldA = rt.Allowed;
rt.Allowed = parseAllowed(xr.Attribute("Allowed")!.Value);
if (rt.IsGraphModified)
return table.UpdateSqlSync(rt, null, comment: Comment(role, ToEntity(r), oldA, rt.Allowed));
return null;
})?.Do(p => p.GoBefore = true);
return restSql;
});
}
internal static string Comment(Lite<RoleEntity> role, R resource, A allowed)
{
return "{0} {1} for {2} ({3})".FormatWith(typeof(R).NiceName(), resource.ToString(), role, allowed);
}
internal static string Comment(Lite<RoleEntity> role, R resource, A from, A to)
{
return "{0} {1} for {2} ({3} -> {4})".FormatWith(typeof(R).NiceName(), resource.ToString(), role, from, to);
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class ConditionalTests
{
[Fact]
public void VisitIfThenDoesNotCloneTree()
{
Expression ifTrue = ((Expression<Action>)(() => Nop())).Body;
ConditionalExpression e = Expression.IfThen(Expression.Constant(true), ifTrue);
Expression r = new Visitor().Visit(e);
Assert.Same(e, r);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void Conditional(bool useInterpreter)
{
Expression<Func<int, int, int>> f = (x, y) => x > 5 ? x : y;
Func<int, int, int> d = f.Compile(useInterpreter);
Assert.Equal(7, d(7, 4));
Assert.Equal(6, d(3, 6));
}
[Fact]
public void NullTest()
{
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.IfThen(null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.IfThenElse(null, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.Condition(null, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("test", () => Expression.Condition(null, Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void UnreadableTest()
{
Expression test = Expression.Property(null, typeof(Unreadable<bool>), nameof(Unreadable<bool>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(test, Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(test, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(test, Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(test, Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void NullIfTrue()
{
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.IfThen(Expression.Constant(true), null));
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.IfThenElse(Expression.Constant(true), null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.Condition(Expression.Constant(true), null, Expression.Empty()));
AssertExtensions.Throws<ArgumentNullException>("ifTrue", () => Expression.Condition(Expression.Constant(true), null, Expression.Empty(), typeof(void)));
}
[Fact]
public void UnreadableIfTrue()
{
Expression ifTrue = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.IfThen(Expression.Constant(true), ifTrue));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.IfThenElse(Expression.Constant(true), ifTrue, Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.Condition(Expression.Constant(true), ifTrue, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>("ifTrue", () => Expression.Condition(Expression.Constant(true), ifTrue, Expression.Empty(), typeof(void)));
}
[Fact]
public void NullIfFalse()
{
AssertExtensions.Throws<ArgumentNullException>("ifFalse", () => Expression.IfThenElse(Expression.Constant(true), Expression.Empty(), null));
AssertExtensions.Throws<ArgumentNullException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), null));
AssertExtensions.Throws<ArgumentNullException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), null, typeof(void)));
}
[Fact]
public void UnreadbleIfFalse()
{
Expression ifFalse = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly));
AssertExtensions.Throws<ArgumentException>("ifFalse", () => Expression.IfThenElse(Expression.Constant(true), Expression.Empty(), ifFalse));
AssertExtensions.Throws<ArgumentException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), ifFalse));
AssertExtensions.Throws<ArgumentException>("ifFalse", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), ifFalse, typeof(void)));
}
[Fact]
public void NullType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Condition(Expression.Constant(true), Expression.Empty(), Expression.Empty(), null));
}
[Fact]
public void NonBooleanTest()
{
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Constant(0), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Constant(0), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(0), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(0), Expression.Empty(), Expression.Empty(), typeof(void)));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Empty(), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Empty(), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Empty(), Expression.Empty(), Expression.Empty(), typeof(void)));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Constant(true, typeof(bool?)), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(true, typeof(bool?)), Expression.Empty(), Expression.Empty(), typeof(void)));
ConstantExpression truthyConstant = Expression.Constant(new Truthiness(true));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThen(Expression.Constant(truthyConstant), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.IfThenElse(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty()));
AssertExtensions.Throws<ArgumentException>("test", () => Expression.Condition(Expression.Constant(truthyConstant), Expression.Empty(), Expression.Empty(), typeof(void)));
}
[Fact]
public void IncompatibleImplicitTypes()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant("hello"), Expression.Constant(new object())));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(new object()), Expression.Constant("hello")));
}
[Fact]
public void IncompatibleExplicitTypes()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(int)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(int)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(long)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(long)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant("hello"), typeof(object)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(Expression.Constant(true), Expression.Constant("hello"), Expression.Constant(0), typeof(object)));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AnyTypesAllowedWithExplicitVoid(bool useInterpreter)
{
Action act = Expression.Lambda<Action>(
Expression.Condition(Expression.Constant(true), Expression.Constant(0), Expression.Constant(0L), typeof(void))
).Compile(useInterpreter);
act();
act = Expression.Lambda<Action>(
Expression.Condition(Expression.Constant(true), Expression.Constant(0L), Expression.Constant(0), typeof(void))
).Compile(useInterpreter);
act();
}
[Theory, PerCompilationType(nameof(ConditionalValues))]
public void ConditionalSelectsCorrectExpression(bool test, object ifTrue, object ifFalse, object expected, bool useInterpreter)
{
Func<object> func = Expression.Lambda<Func<object>>(
Expression.Convert(
Expression.Condition(
Expression.Constant(test),
Expression.Constant(ifTrue),
Expression.Constant(ifFalse)
),
typeof(object)
)
).Compile(useInterpreter);
Assert.Equal(expected, func());
}
[Theory, PerCompilationType(nameof(ConditionalValuesWithTypes))]
public void ConditionalSelectsCorrectExpressionWithType(bool test, object ifTrue, object ifFalse, object expected, Type type, bool useInterpreter)
{
Func<object> func = Expression.Lambda<Func<object>>(
Expression.Condition(
Expression.Constant(test),
Expression.Constant(ifTrue),
Expression.Constant(ifFalse),
type
)
).Compile(useInterpreter);
Assert.Same(expected, func());
}
[Fact]
public void ByRefType()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(string).MakeByRefType()));
}
[Fact]
public void PointerType()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(string).MakePointerType()));
}
[Fact]
public void GenericType()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>)));
}
[Fact]
public void TypeContainsGenericParameters()
{
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>.Enumerator)));
AssertExtensions.Throws<ArgumentException>(null, () => Expression.Condition(
Expression.Constant(true),
Expression.Constant(null),
Expression.Constant(null),
typeof(List<>).MakeGenericType(typeof(List<>))));
}
[Fact]
public static void ToStringTest()
{
ConditionalExpression e1 = Expression.Condition(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(int), "b"), Expression.Parameter(typeof(int), "c"));
Assert.Equal("IIF(a, b, c)", e1.ToString());
ConditionalExpression e2 = Expression.IfThen(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(int), "b"));
Assert.Equal("IIF(a, b, default(Void))", e2.ToString());
}
private static IEnumerable<object[]> ConditionalValues()
{
yield return new object[] { true, "yes", "no", "yes" };
yield return new object[] { false, "yes", "no", "no" };
yield return new object[] { true, 42, 12, 42 };
yield return new object[] { false, 42L, 12L, 12L };
}
private static IEnumerable<object[]> ConditionalValuesWithTypes()
{
ConstantExpression ce = Expression.Constant(98);
BinaryExpression be = Expression.And(Expression.Constant(2), Expression.Constant(3));
yield return new object[] { true, ce, be, ce, typeof(Expression) };
yield return new object[] { false, ce, be, be, typeof(Expression) };
}
private static class Unreadable<T>
{
public static T WriteOnly
{
set { }
}
}
private static void Nop()
{
}
private class Visitor : ExpressionVisitor
{
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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 SharpDX.Mathematics;
using SharpDX.Mathematics.Interop;
#if WIN8METRO
using Windows.UI.Core;
using Windows.Graphics.Display;
using Windows.UI.Xaml.Controls;
#elif WP8
#else
using System.Windows.Forms;
#endif
using SharpDX.DXGI;
namespace SharpDX.Toolkit.Graphics
{
/// <summary>
/// Graphics presenter for SwapChain.
/// </summary>
public class SwapChainGraphicsPresenter : GraphicsPresenter
{
private RenderTarget2D backBuffer;
private SwapChain swapChain;
#if DIRECTX11_2
private SwapChain2 swapChain2;
#endif
private int bufferCount;
public SwapChainGraphicsPresenter(GraphicsDevice device, PresentationParameters presentationParameters)
: base(device, presentationParameters)
{
PresentInterval = presentationParameters.PresentationInterval;
// Initialize the swap chain
swapChain = ToDispose(CreateSwapChain());
#if DIRECTX11_2
swapChain2 = ToDispose(swapChain.QueryInterface<SwapChain2>());
#endif
backBuffer = ToDispose(RenderTarget2D.New(device, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));
}
public override RenderTarget2D BackBuffer
{
get
{
return backBuffer;
}
}
public override object NativePresenter
{
get
{
return swapChain;
}
}
public override bool IsFullScreen
{
get
{
#if WIN8METRO
return true;
#else
return swapChain.IsFullScreen;
#endif
}
set
{
#if !WIN8METRO
if(swapChain == null)
return;
var outputIndex = PrefferedFullScreenOutputIndex;
// no outputs connected to the current graphics adapter
var output = GraphicsDevice.Adapter == null || GraphicsDevice.Adapter.OutputsCount == 0 ? null : GraphicsDevice.Adapter.GetOutputAt(outputIndex);
Output currentOutput = null;
try
{
RawBool isCurrentlyFullscreen;
swapChain.GetFullscreenState(out isCurrentlyFullscreen, out currentOutput);
// check if the current fullscreen monitor is the same as new one
if (isCurrentlyFullscreen == value && output != null && currentOutput != null && currentOutput.NativePointer == ((Output)output).NativePointer)
return;
}
finally
{
if (currentOutput != null)
currentOutput.Dispose();
}
bool switchToFullScreen = value;
// If going to fullscreen mode: call 1) SwapChain.ResizeTarget 2) SwapChain.IsFullScreen
var description = new ModeDescription(backBuffer.Width, backBuffer.Height, Description.RefreshRate, Description.BackBufferFormat);
if(switchToFullScreen)
{
Description.IsFullScreen = true;
// Destroy and recreate the full swapchain in case of fullscreen switch
// It seems to be more reliable then trying to change the current swap-chain.
RemoveAndDispose(ref backBuffer);
RemoveAndDispose(ref swapChain);
swapChain = CreateSwapChain();
backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));
}
else
{
Description.IsFullScreen = false;
swapChain.IsFullScreen = false;
// call 1) SwapChain.IsFullScreen 2) SwapChain.Resize
Resize(backBuffer.Width, backBuffer.Height, backBuffer.Format);
}
// If going to window mode:
if (!switchToFullScreen)
{
// call 1) SwapChain.IsFullScreen 2) SwapChain.Resize
description.RefreshRate = new Rational(0, 0);
swapChain.ResizeTarget(ref description);
}
#endif
}
}
public override void Present()
{
swapChain.Present((int)PresentInterval, PresentFlags.None);
}
/// <summary>
/// Called when name changed for this component.
/// </summary>
protected override void OnPropertyChanged(string propertyName)
{
base.OnPropertyChanged(propertyName);
if (propertyName == "Name")
{
if (GraphicsDevice.IsDebugMode && swapChain != null)
{
swapChain.DebugName = Name;
}
}
}
public override bool Resize(int width, int height, Format format, Rational? refreshRate = null)
{
if (!base.Resize(width, height, format, refreshRate)) return false;
RemoveAndDispose(ref backBuffer);
#if DIRECTX11_2 && WIN8METRO
var swapChainPanel = Description.DeviceWindowHandle as SwapChainPanel;
if (swapChainPanel != null && swapChain2 != null)
{
swapChain2.MatrixTransform = Matrix3x2.Scaling(1f / swapChainPanel.CompositionScaleX, 1f / swapChainPanel.CompositionScaleY);
}
#endif
swapChain.ResizeBuffers(bufferCount, width, height, format, Description.Flags);
// Recreate the back buffer
backBuffer = ToDispose(RenderTarget2D.New(GraphicsDevice, swapChain.GetBackBuffer<Direct3D11.Texture2D>(0)));
// Reinit the Viewport
DefaultViewport = new ViewportF(0, 0, backBuffer.Width, backBuffer.Height);
return true;
}
private SwapChain CreateSwapChain()
{
// Check for Window Handle parameter
if (Description.DeviceWindowHandle == null)
{
throw new ArgumentException("DeviceWindowHandle cannot be null");
}
#if WIN8METRO
return CreateSwapChainForWinRT();
#else
return CreateSwapChainForDesktop();
#endif
}
#if WIN8METRO
private SwapChain CreateSwapChainForWinRT()
{
var coreWindow = Description.DeviceWindowHandle as CoreWindow;
var swapChainBackgroundPanel = Description.DeviceWindowHandle as SwapChainBackgroundPanel;
bufferCount = 2;
var description = new SwapChainDescription1
{
// Automatic sizing
Width = Description.BackBufferWidth,
Height = Description.BackBufferHeight,
Format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, // TODO: Check if we can use the Description.BackBufferFormat
Stereo = false,
SampleDescription = new SharpDX.DXGI.SampleDescription((int)Description.MultiSampleCount, 0),
Usage = Description.RenderTargetUsage,
// Use two buffers to enable flip effect.
BufferCount = bufferCount,
Scaling = SharpDX.DXGI.Scaling.Stretch,
SwapEffect = SharpDX.DXGI.SwapEffect.FlipSequential,
};
if (coreWindow != null)
{
// Creates a SwapChain from a CoreWindow pointer
using (var comWindow = new ComObject(coreWindow))
return new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, comWindow, ref description);
}
else if (swapChainBackgroundPanel != null)
{
var nativePanel = ComObject.As<ISwapChainBackgroundPanelNative>(swapChainBackgroundPanel);
// Creates the swap chain for XAML composition
var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);
// Associate the SwapChainBackgroundPanel with the swap chain
nativePanel.SwapChain = swapChain;
return swapChain;
}
else
{
#if DIRECTX11_2
using (var comObject = new ComObject(Description.DeviceWindowHandle))
{
var swapChainPanel = comObject.QueryInterfaceOrNull<ISwapChainPanelNative>();
if (swapChainPanel != null)
{
var swapChain = new SwapChain1((DXGI.Factory2)GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, ref description);
swapChainPanel.SwapChain = swapChain;
return swapChain;
}
}
#endif
throw new NotSupportedException();
}
}
#elif WP8
private SwapChain CreateSwapChainForDesktop()
{
throw new NotImplementedException();
}
#else
private SwapChain CreateSwapChainForDesktop()
{
IntPtr? handle = null;
var control = Description.DeviceWindowHandle as Control;
if (control != null) handle = control.Handle;
else if (Description.DeviceWindowHandle is IntPtr) handle = (IntPtr)Description.DeviceWindowHandle;
if (!handle.HasValue)
{
throw new NotSupportedException(string.Format("DeviceWindowHandle of type [{0}] is not supported. Only System.Windows.Control or IntPtr are supported", Description.DeviceWindowHandle != null ? Description.DeviceWindowHandle.GetType().Name : "null"));
}
bufferCount = 1;
var description = new SwapChainDescription
{
ModeDescription = new ModeDescription(Description.BackBufferWidth, Description.BackBufferHeight, Description.RefreshRate, Description.BackBufferFormat),
BufferCount = bufferCount, // TODO: Do we really need this to be configurable by the user?
OutputHandle = handle.Value,
SampleDescription = new SampleDescription((int)Description.MultiSampleCount, 0),
SwapEffect = SwapEffect.Discard,
Usage = Description.RenderTargetUsage,
IsWindowed = true,
Flags = Description.Flags,
};
var newSwapChain = new SwapChain(GraphicsAdapter.Factory, (Direct3D11.Device)GraphicsDevice, description);
if (Description.IsFullScreen)
{
// Before fullscreen switch
newSwapChain.ResizeTarget(ref description.ModeDescription);
// Switch to full screen
newSwapChain.IsFullScreen = true;
// This is really important to call ResizeBuffers AFTER switching to IsFullScreen
newSwapChain.ResizeBuffers(bufferCount, Description.BackBufferWidth, Description.BackBufferHeight, Description.BackBufferFormat, SwapChainFlags.AllowModeSwitch);
}
return newSwapChain;
}
#endif
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Test.ModuleCore;
using System;
using System.IO;
using System.Text;
using System.Xml;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
public partial class XNodeReaderTests : XLinqTestCase
{
public partial class TCReadContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
byte[] buffer = new byte[1];
if (!DataReader.CanReadBinaryContent) return;
try
{
int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element on CDATA", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
string xmlStr = "<root><![CDATA[ABCDEF]]></root>";
XmlReader DataReader = GetReader(new StringReader(xmlStr));
PositionOnElement(DataReader, "root");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 0, "BinHex");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.Element, "ElemText", String.Empty), "1vn");
}
//[Variation("Current node on multiple calls")]
public void TestReadBinHex_17()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[30];
int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2);
TestLog.Compare(nRead, 2, "0");
nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19);
TestLog.Compare(nRead, 18, "1");
TestLog.Compare(VerifyNode(DataReader, XmlNodeType.EndElement, "ElemNum", String.Empty), "1vn");
}
//[Variation("ReadBinHex with whitespaces")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
DataReader.ReadContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going whIdbey to everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
int bytes = -1;
DataReader.Read();
if (!DataReader.CanReadBinaryContent) return;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("DebugAssert in ReadContentAsBinHex")]
public void DebugAssertInReadContentAsBinHex()
{
XmlReader DataReader = GetReaderStr(@"<root>
<boo>hey</boo>
</root>");
byte[] buffer = new byte[5];
int iCount = 0;
while (DataReader.Read())
{
if (DataReader.NodeType == XmlNodeType.Element)
break;
}
if (!DataReader.CanReadBinaryContent) return;
DataReader.Read();
iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0);
}
}
//[TestCase(Name = "ReadElementContentAsBinHex", Desc = "ReadElementContentAsBinHex")]
public partial class TCReadElementContentAsBinHex : BridgeHelpers
{
public const string ST_ELEM_NAME1 = "ElemAll";
public const string ST_ELEM_NAME2 = "ElemEmpty";
public const string ST_ELEM_NAME3 = "ElemNum";
public const string ST_ELEM_NAME4 = "ElemText";
public const string ST_ELEM_NAME5 = "ElemNumText";
public const string ST_ELEM_NAME6 = "ElemLong";
public const string strTextBinHex = "ABCDEF";
public const string strNumBinHex = "0123456789";
public override void Init()
{
base.Init();
CreateBinHexTestFile(pBinHexXml);
}
public override void Terminate()
{
base.Terminate();
}
private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType)
{
bool bPassed = false;
byte[] buffer = new byte[iBufferSize];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return true;
try
{
DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount);
}
catch (Exception e)
{
bPassed = (e.GetType().ToString() == exceptionType.ToString());
if (!bPassed)
{
TestLog.WriteLine("Actual exception:{0}", e.GetType().ToString());
TestLog.WriteLine("Expected exception:{0}", exceptionType.ToString());
}
}
return bPassed;
}
protected void TestInvalidNodeType(XmlNodeType nt)
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnNodeType(DataReader, nt);
string name = DataReader.Name;
string value = DataReader.Value;
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[1];
try
{
int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
}
catch (InvalidOperationException)
{
return;
}
TestLog.Compare(false, "Invalid OP exception not thrown on wrong nodetype");
}
//[Variation("ReadBinHex Element with all valid value")]
public void TestReadBinHex_1()
{
int binhexlen = 0;
byte[] binhex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length);
string strActbinhex = "";
for (int i = 0; i < binhexlen; i = i + 2)
{
strActbinhex += System.BitConverter.ToChar(binhex, i);
}
TestLog.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Num value", Priority = 0)]
public void TestReadBinHex_2()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME3);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all valid Text value")]
public void TestReadBinHex_3()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with Comments and PIs", Priority = 0)]
public void TestReadBinHex_4()
{
int BinHexlen = 0;
byte[] BinHex = new byte[3];
XmlReader DataReader = GetReader(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>"));
PositionOnElement(DataReader, "root");
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
TestLog.Compare(BinHexlen, 3, "BinHex");
}
//[Variation("ReadBinHex Element with all valid value (from concatenation), Priority=0")]
public void TestReadBinHex_5()
{
int BinHexlen = 0;
byte[] BinHex = new byte[1000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME5);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
TestLog.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex");
}
//[Variation("ReadBinHex Element with all long valid value (from concatenation)")]
public void TestReadBinHex_6()
{
int BinHexlen = 0;
byte[] BinHex = new byte[2000];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME6);
if (!DataReader.CanReadBinaryContent) return;
BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length);
string strActBinHex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
strActBinHex += System.BitConverter.ToChar(BinHex, i);
}
string strExpBinHex = "";
for (int i = 0; i < 10; i++)
strExpBinHex += (strNumBinHex + strTextBinHex);
TestLog.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex");
}
//[Variation("ReadBinHex with count > buffer size")]
public void TestReadBinHex_7()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with count < 0")]
public void TestReadBinHex_8()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index > buffer size")]
public void vReadBinHex_9()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index < 0")]
public void TestReadBinHex_10()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex with index + count exceeds buffer")]
public void TestReadBinHex_11()
{
BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException)));
}
//[Variation("ReadBinHex index & count =0")]
public void TestReadBinHex_12()
{
byte[] buffer = new byte[5];
int iCount = 0;
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME1);
if (!DataReader.CanReadBinaryContent) return;
try
{
iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0);
}
catch (Exception e)
{
TestLog.WriteLine(e.ToString());
throw new TestException(TestResult.Failed, "");
}
TestLog.Compare(iCount, 0, "has to be zero");
}
//[Variation("ReadBinHex Element multiple into same buffer (using offset), Priority=0")]
public void TestReadBinHex_13()
{
int BinHexlen = 10;
byte[] BinHex = new byte[BinHexlen];
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
string strActbinhex = "";
for (int i = 0; i < BinHexlen; i = i + 2)
{
DataReader.ReadElementContentAsBinHex(BinHex, i, 2);
strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString();
TestLog.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64");
}
}
//[Variation("ReadBinHex with buffer == null")]
public void TestReadBinHex_14()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, ST_ELEM_NAME4);
if (!DataReader.CanReadBinaryContent) return;
try
{
DataReader.ReadElementContentAsBinHex(null, 0, 0);
}
catch (ArgumentNullException)
{
return;
}
throw new TestException(TestResult.Failed, "");
}
//[Variation("ReadBinHex after failed ReadBinHex")]
public void TestReadBinHex_15()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemErr");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = 0;
try
{
nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1);
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
int idx = e.Message.IndexOf("a&");
TestLog.Compare(idx >= 0, "msg");
CheckXmlException("Xml_UserException", e, 1, 968);
}
}
//[Variation("Read after partial ReadBinHex")]
public void TestReadBinHex_16()
{
XmlReader DataReader = GetReader(pBinHexXml);
PositionOnElement(DataReader, "ElemNum");
if (!DataReader.CanReadBinaryContent) return;
byte[] buffer = new byte[10];
int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8);
TestLog.Compare(nRead, 8, "0");
DataReader.Read();
TestLog.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node");
}
//[Variation("ReadBinHex with whitespaces")]
public void TestTextReadBinHex_21()
{
byte[] buffer = new byte[1];
string strxml = "<abc> 1 1 B </abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex with odd number of chars")]
public void TestTextReadBinHex_22()
{
byte[] buffer = new byte[1];
string strxml = "<abc>11B</abc>";
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "abc");
if (!DataReader.CanReadBinaryContent) return;
int result = 0;
int nRead;
while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0)
result += nRead;
TestLog.Compare(result, 1, "res");
TestLog.Compare(buffer[0], (byte)17, "buffer[0]");
}
//[Variation("ReadBinHex when end tag doesn't exist")]
public void TestTextReadBinHex_23()
{
byte[] buffer = new byte[5000];
string strxml = "<B>" + new string('A', 5000);
try
{
XmlReader DataReader = GetReaderStr(strxml);
PositionOnElement(DataReader, "B");
DataReader.ReadElementContentAsBinHex(buffer, 0, 5000);
TestLog.WriteLine("Accepted incomplete element");
throw new TestException(TestResult.Failed, "");
}
catch (XmlException e)
{
CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004);
}
}
//[Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes going whIdbey to everett")]
public void TestTextReadBinHex_24()
{
string filename = Path.Combine("TestData", "XmlReader", "Common", "Bug99148.xml");
XmlReader DataReader = GetReader(filename);
DataReader.MoveToContent();
if (!DataReader.CanReadBinaryContent) return;
int bytes = -1;
StringBuilder output = new StringBuilder();
while (bytes != 0)
{
byte[] bbb = new byte[1024];
bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length);
for (int i = 0; i < bytes; i++)
{
output.AppendFormat(bbb[i].ToString());
}
}
if (TestLog.Compare(output.ToString().Length, 1735, "Expected Length : 1735"))
return;
else
throw new TestException(TestResult.Failed, "");
}
//[Variation("SubtreeReader inserted attributes don't work with ReadContentAsBinHex")]
public void TestTextReadBinHex_25()
{
string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>";
using (XmlReader r = GetReader(new StringReader(strxml)))
{
r.Read();
r.Read();
using (XmlReader sr = r.ReadSubtree())
{
if (!sr.CanReadBinaryContent) return;
sr.Read();
sr.MoveToFirstAttribute();
sr.MoveToFirstAttribute();
byte[] bytes = new byte[4];
while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { }
}
}
}
}
}
}
}
| |
//
// BigInteger.cs - Big Integer implementation
//
// Authors:
// Ben Maurer
// Chew Keong TAN
// Sebastien Pouliot <sebastien@ximian.com>
// Pieter Philippaerts <Pieter@mentalis.org>
//
// Copyright (c) 2003 Ben Maurer
// All rights reserved
//
// Copyright (c) 2002 Chew Keong TAN
// All rights reserved.
//
// Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Math
{
using System;
internal class BigInteger
{
#region Data Storage
/// <summary>
/// The Length of this BigInteger
/// </summary>
uint length = 1;
/// <summary>
/// The data for this BigInteger
/// </summary>
uint[] data;
#endregion
#region Constants
/// <summary>
/// Default length of a BigInteger in bytes
/// </summary>
const uint DefaultLength = 20;
public enum Sign
{
Negative = -1,
Zero = 0,
Positive = 1
};
#region Exception Messages
const string WouldReturnNegVal = "Operation would return a negative value";
#endregion
#endregion
#region Constructors
public BigInteger()
{
data = new uint[DefaultLength];
this.length = DefaultLength;
}
public BigInteger(uint ui)
{
data = new uint[] { ui };
}
public BigInteger(Sign sign, uint len)
{
this.data = new uint[len];
this.length = len;
}
public BigInteger(BigInteger bi)
{
this.data = (uint[])bi.data.Clone();
this.length = bi.length;
}
public BigInteger(BigInteger bi, uint len)
{
this.data = new uint[len];
for (uint i = 0; i < bi.length; i++)
this.data[i] = bi.data[i];
this.length = bi.length;
}
#endregion
#region Conversions
public BigInteger(byte[] inData)
{
if (inData.Length == 0)
inData = new byte[1];
length = (uint)inData.Length >> 2;
int leftOver = inData.Length & 0x3;
// length not multiples of 4
if (leftOver != 0) length++;
data = new uint[length];
for (int i = inData.Length - 1, j = 0; i >= 3; i -= 4, j++)
{
data[j] = (uint)(
(inData[i - 3] << (3 * 8)) |
(inData[i - 2] << (2 * 8)) |
(inData[i - 1] << (1 * 8)) |
(inData[i])
);
}
switch (leftOver)
{
case 1: data[length - 1] = (uint)inData[0]; break;
case 2: data[length - 1] = (uint)((inData[0] << 8) | inData[1]); break;
case 3: data[length - 1] = (uint)((inData[0] << 16) | (inData[1] << 8) | inData[2]); break;
}
this.Normalize();
}
public static implicit operator BigInteger(uint value)
{
return (new BigInteger(value));
}
#endregion
#region Operators
public static BigInteger operator +(BigInteger bi1, BigInteger bi2)
{
if (bi1 == 0)
return new BigInteger(bi2);
else if (bi2 == 0)
return new BigInteger(bi1);
else
return Kernel.AddSameSign(bi1, bi2);
}
public static BigInteger operator -(BigInteger bi1, BigInteger bi2)
{
if (bi2 == 0)
return new BigInteger(bi1);
if (bi1 == 0)
throw new ArithmeticException(WouldReturnNegVal);
switch (Kernel.Compare(bi1, bi2))
{
case Sign.Zero:
return 0;
case Sign.Positive:
return Kernel.Subtract(bi1, bi2);
case Sign.Negative:
throw new ArithmeticException(WouldReturnNegVal);
default:
throw new Exception();
}
}
public static int operator %(BigInteger bi, int i)
{
if (i > 0)
return (int)Kernel.DwordMod(bi, (uint)i);
else
return -(int)Kernel.DwordMod(bi, (uint)-i);
}
public static uint operator %(BigInteger bi, uint ui)
{
return Kernel.DwordMod(bi, (uint)ui);
}
public static BigInteger operator %(BigInteger bi1, BigInteger bi2)
{
return Kernel.multiByteDivide(bi1, bi2)[1];
}
public static BigInteger operator /(BigInteger bi, int i)
{
if (i > 0)
return Kernel.DwordDiv(bi, (uint)i);
throw new ArithmeticException(WouldReturnNegVal);
}
public static BigInteger operator /(BigInteger bi1, BigInteger bi2)
{
return Kernel.multiByteDivide(bi1, bi2)[0];
}
public static BigInteger operator *(BigInteger bi1, BigInteger bi2)
{
if (bi1 == 0 || bi2 == 0) return 0;
//
// Validate pointers
//
if (bi1.data.Length < bi1.length) throw new IndexOutOfRangeException("bi1 out of range");
if (bi2.data.Length < bi2.length) throw new IndexOutOfRangeException("bi2 out of range");
BigInteger ret = new BigInteger(Sign.Positive, bi1.length + bi2.length);
Kernel.Multiply(bi1.data, 0, bi1.length, bi2.data, 0, bi2.length, ret.data, 0);
ret.Normalize();
return ret;
}
public static BigInteger operator *(BigInteger bi, int i)
{
if (i < 0) throw new ArithmeticException(WouldReturnNegVal);
if (i == 0) return 0;
if (i == 1) return new BigInteger(bi);
return Kernel.MultiplyByDword(bi, (uint)i);
}
public static BigInteger operator <<(BigInteger bi1, int shiftVal)
{
return Kernel.LeftShift(bi1, shiftVal);
}
public static BigInteger operator >>(BigInteger bi1, int shiftVal)
{
return Kernel.RightShift(bi1, shiftVal);
}
#endregion
#region Bitwise
public int BitCount()
{
this.Normalize();
uint value = data[length - 1];
uint mask = 0x80000000;
uint bits = 32;
while (bits > 0 && (value & mask) == 0)
{
bits--;
mask >>= 1;
}
bits += ((length - 1) << 5);
return (int)bits;
}
public bool TestBit(int bitNum)
{
if (bitNum < 0) throw new IndexOutOfRangeException("bitNum out of range");
uint bytePos = (uint)bitNum >> 5; // divide by 32
byte bitPos = (byte)(bitNum & 0x1F); // get the lowest 5 bits
uint mask = (uint)1 << bitPos;
return ((this.data[bytePos] | mask) == this.data[bytePos]);
}
public void SetBit(uint bitNum, bool value)
{
uint bytePos = bitNum >> 5; // divide by 32
if (bytePos < this.length)
{
uint mask = (uint)1 << (int)(bitNum & 0x1F);
if (value)
this.data[bytePos] |= mask;
else
this.data[bytePos] &= ~mask;
}
}
public byte[] GetBytes()
{
if (this == 0) return new byte[1];
int numBits = BitCount();
int numBytes = numBits >> 3;
if ((numBits & 0x7) != 0)
numBytes++;
byte[] result = new byte[numBytes];
int numBytesInWord = numBytes & 0x3;
if (numBytesInWord == 0) numBytesInWord = 4;
int pos = 0;
for (int i = (int)length - 1; i >= 0; i--)
{
uint val = data[i];
for (int j = numBytesInWord - 1; j >= 0; j--)
{
result[pos + j] = (byte)(val & 0xFF);
val >>= 8;
}
pos += numBytesInWord;
numBytesInWord = 4;
}
return result;
}
#endregion
#region Compare
public static bool operator ==(BigInteger bi1, uint ui)
{
if (bi1.length != 1) bi1.Normalize();
return bi1.length == 1 && bi1.data[0] == ui;
}
public static bool operator !=(BigInteger bi1, uint ui)
{
if (bi1.length != 1) bi1.Normalize();
return !(bi1.length == 1 && bi1.data[0] == ui);
}
public static bool operator ==(BigInteger bi1, BigInteger bi2)
{
// we need to compare with null
if ((bi1 as object) == (bi2 as object))
return true;
if (null == bi1 || null == bi2)
return false;
return Kernel.Compare(bi1, bi2) == 0;
}
public static bool operator !=(BigInteger bi1, BigInteger bi2)
{
// we need to compare with null
if ((bi1 as object) == (bi2 as object))
return false;
if (null == bi1 || null == bi2)
return true;
return Kernel.Compare(bi1, bi2) != 0;
}
public static bool operator >(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) > 0;
}
public static bool operator <(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) < 0;
}
public static bool operator >=(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) >= 0;
}
public static bool operator <=(BigInteger bi1, BigInteger bi2)
{
return Kernel.Compare(bi1, bi2) <= 0;
}
public Sign Compare(BigInteger bi)
{
return Kernel.Compare(this, bi);
}
#endregion
#region Formatting
public string ToString(uint radix)
{
return ToString(radix, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
}
public string ToString(uint radix, string characterSet)
{
if (characterSet.Length < radix)
throw new ArgumentException("charSet length less than radix", "characterSet");
if (radix == 1)
throw new ArgumentException("There is no such thing as radix one notation", "radix");
if (this == 0) return "0";
if (this == 1) return "1";
var result = "";
var a = new BigInteger(this);
while (a != 0)
{
var rem = Kernel.SingleByteDivideInPlace(a, radix);
result = characterSet[(int)rem] + result;
}
return result;
}
#endregion
#region Misc
/// <summary>
/// Normalizes this by setting the length to the actual number of
/// uints used in data and by setting the sign to Sign.Zero if the
/// value of this is 0.
/// </summary>
private void Normalize()
{
// Normalize length
while (length > 0 && data[length - 1] == 0) length--;
// Check for zero
if (length == 0)
length++;
}
#endregion
#region Object Impl
public override int GetHashCode()
{
uint val = 0;
for (uint i = 0; i < length; i++)
val ^= data[i];
return (int)val;
}
public override string ToString()
{
return ToString(10);
}
public override bool Equals(object o)
{
if (o == null) return false;
if (o is int) return (int)o >= 0 && this == (uint)o;
return Kernel.Compare(this, (BigInteger)o) == 0;
}
#endregion
#region Number Theory
public BigInteger ModPow(BigInteger exp, BigInteger n)
{
return new ModulusRing(n).Pow(this, exp);
}
#endregion
public sealed class ModulusRing
{
private readonly BigInteger _mod;
private readonly BigInteger _constant;
public ModulusRing(BigInteger modulus)
{
_mod = modulus;
// calculate constant = b^ (2k) / m
var i = _mod.length << 1;
_constant = new BigInteger(Sign.Positive, i + 1);
_constant.data[i] = 0x00000001;
_constant = _constant / _mod;
}
public void BarrettReduction(BigInteger x)
{
var n = _mod;
uint k = n.length,
kPlusOne = k + 1,
kMinusOne = k - 1;
// x < mod, so nothing to do.
if (x.length < k) return;
//
// Validate pointers
//
if (x.data.Length < x.length) throw new IndexOutOfRangeException("x out of range");
// q1 = x / b^ (k-1)
// q2 = q1 * constant
// q3 = q2 / b^ (k+1), Needs to be accessed with an offset of kPlusOne
// TODO: We should the method in HAC p 604 to do this (14.45)
var q3 = new BigInteger(Sign.Positive, x.length - kMinusOne + _constant.length);
Kernel.Multiply(x.data, kMinusOne, x.length - kMinusOne, _constant.data, 0, _constant.length, q3.data, 0);
// r1 = x mod b^ (k+1)
// i.e. keep the lowest (k+1) words
var lengthToCopy = (x.length > kPlusOne) ? kPlusOne : x.length;
x.length = lengthToCopy;
x.Normalize();
// r2 = (q3 * n) mod b^ (k+1)
// partial multiplication of q3 and n
var r2 = new BigInteger(Sign.Positive, kPlusOne);
Kernel.MultiplyMod2p32pmod(q3.data, (int)kPlusOne, (int)q3.length - (int)kPlusOne, n.data, 0, (int)n.length, r2.data, 0, (int)kPlusOne);
r2.Normalize();
if (r2 <= x)
Kernel.MinusEq(x, r2);
else
{
var val = new BigInteger(Sign.Positive, kPlusOne + 1);
val.data[kPlusOne] = 0x00000001;
Kernel.MinusEq(val, r2);
Kernel.PlusEq(x, val);
}
while (x >= n)
Kernel.MinusEq(x, n);
}
public BigInteger Multiply(BigInteger a, BigInteger b)
{
if (a == 0 || b == 0) return 0;
if (a > _mod)
a %= _mod;
if (b > _mod)
b %= _mod;
var ret = a * b;
BarrettReduction(ret);
return ret;
}
public BigInteger Difference(BigInteger a, BigInteger b)
{
var cmp = Kernel.Compare(a, b);
BigInteger diff;
switch (cmp)
{
case Sign.Zero:
return 0;
case Sign.Positive:
diff = a - b; break;
case Sign.Negative:
diff = b - a; break;
default:
throw new Exception();
}
if (diff >= _mod)
{
if (diff.length >= _mod.length << 1)
diff %= _mod;
else
BarrettReduction(diff);
}
if (cmp == Sign.Negative)
diff = _mod - diff;
return diff;
}
public BigInteger Pow(BigInteger a, BigInteger k)
{
var b = new BigInteger(1);
if (k == 0)
return b;
var A = a;
if (k.TestBit(0))
b = a;
int bitCount = k.BitCount();
for (int i = 1; i < bitCount; i++)
{
A = Multiply(A, A);
if (k.TestBit(i))
b = Multiply(A, b);
}
return b;
}
public BigInteger Pow(uint b, BigInteger exp)
{
return Pow(new BigInteger(b), exp);
}
}
private sealed class Kernel
{
#region Addition/Subtraction
/// <summary>
/// Adds two numbers with the same sign.
/// </summary>
/// <param name="bi1">A BigInteger</param>
/// <param name="bi2">A BigInteger</param>
/// <returns>bi1 + bi2</returns>
public static BigInteger AddSameSign(BigInteger bi1, BigInteger bi2)
{
uint[] x, y;
uint yMax, xMax, i = 0;
// x should be bigger
if (bi1.length < bi2.length)
{
x = bi2.data;
xMax = bi2.length;
y = bi1.data;
yMax = bi1.length;
}
else
{
x = bi1.data;
xMax = bi1.length;
y = bi2.data;
yMax = bi2.length;
}
BigInteger result = new BigInteger(Sign.Positive, xMax + 1);
uint[] r = result.data;
ulong sum = 0;
// Add common parts of both numbers
do
{
sum = ((ulong)x[i]) + ((ulong)y[i]) + sum;
r[i] = (uint)sum;
sum >>= 32;
} while (++i < yMax);
// Copy remainder of longer number while carry propagation is required
bool carry = (sum != 0);
if (carry)
{
if (i < xMax)
{
do
carry = ((r[i] = x[i] + 1) == 0);
while (++i < xMax && carry);
}
if (carry)
{
r[i] = 1;
result.length = ++i;
return result;
}
}
// Copy the rest
if (i < xMax)
{
do
r[i] = x[i];
while (++i < xMax);
}
result.Normalize();
return result;
}
public static BigInteger Subtract(BigInteger big, BigInteger small)
{
BigInteger result = new BigInteger(Sign.Positive, big.length);
uint[] r = result.data, b = big.data, s = small.data;
uint i = 0, c = 0;
do
{
uint x = s[i];
if (((x += c) < c) | ((r[i] = b[i] - x) > ~x))
c = 1;
else
c = 0;
} while (++i < small.length);
if (i == big.length) goto fixup;
if (c == 1)
{
do
r[i] = b[i] - 1;
while (b[i++] == 0 && i < big.length);
if (i == big.length) goto fixup;
}
do
r[i] = b[i];
while (++i < big.length);
fixup:
result.Normalize();
return result;
}
public static void MinusEq(BigInteger big, BigInteger small)
{
uint[] b = big.data, s = small.data;
uint i = 0, c = 0;
do
{
uint x = s[i];
if (((x += c) < c) | ((b[i] -= x) > ~x))
c = 1;
else
c = 0;
} while (++i < small.length);
if (i == big.length) goto fixup;
if (c == 1)
{
do
b[i]--;
while (b[i++] == 0 && i < big.length);
}
fixup:
// Normalize length
while (big.length > 0 && big.data[big.length - 1] == 0) big.length--;
// Check for zero
if (big.length == 0)
big.length++;
}
public static void PlusEq(BigInteger bi1, BigInteger bi2)
{
uint[] x, y;
uint yMax, xMax, i = 0;
bool flag = false;
// x should be bigger
if (bi1.length < bi2.length)
{
flag = true;
x = bi2.data;
xMax = bi2.length;
y = bi1.data;
yMax = bi1.length;
}
else
{
x = bi1.data;
xMax = bi1.length;
y = bi2.data;
yMax = bi2.length;
}
uint[] r = bi1.data;
ulong sum = 0;
// Add common parts of both numbers
do
{
sum += ((ulong)x[i]) + ((ulong)y[i]);
r[i] = (uint)sum;
sum >>= 32;
} while (++i < yMax);
// Copy remainder of longer number while carry propagation is required
bool carry = (sum != 0);
if (carry)
{
if (i < xMax)
{
do
carry = ((r[i] = x[i] + 1) == 0);
while (++i < xMax && carry);
}
if (carry)
{
r[i] = 1;
bi1.length = ++i;
return;
}
}
// Copy the rest
if (flag && i < xMax - 1)
{
do
r[i] = x[i];
while (++i < xMax);
}
bi1.length = xMax + 1;
bi1.Normalize();
}
#endregion
#region Compare
/// <summary>
/// Compares two BigInteger
/// </summary>
/// <param name="bi1">A BigInteger</param>
/// <param name="bi2">A BigInteger</param>
/// <returns>The sign of bi1 - bi2</returns>
public static Sign Compare(BigInteger bi1, BigInteger bi2)
{
//
// Step 1. Compare the lengths
//
uint l1 = bi1.length, l2 = bi2.length;
while (l1 > 0 && bi1.data[l1 - 1] == 0) l1--;
while (l2 > 0 && bi2.data[l2 - 1] == 0) l2--;
if (l1 == 0 && l2 == 0) return Sign.Zero;
// bi1 len < bi2 len
if (l1 < l2) return Sign.Negative;
// bi1 len > bi2 len
else if (l1 > l2) return Sign.Positive;
//
// Step 2. Compare the bits
//
uint pos = l1 - 1;
while (pos != 0 && bi1.data[pos] == bi2.data[pos]) pos--;
if (bi1.data[pos] < bi2.data[pos])
return Sign.Negative;
else if (bi1.data[pos] > bi2.data[pos])
return Sign.Positive;
else
return Sign.Zero;
}
#endregion
#region Division
#region Dword
/// <summary>
/// Performs n / d and n % d in one operation.
/// </summary>
/// <param name="n">A BigInteger, upon exit this will hold n / d</param>
/// <param name="d">The divisor</param>
/// <returns>n % d</returns>
public static uint SingleByteDivideInPlace(BigInteger n, uint d)
{
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
n.data[i] = (uint)(r / d);
r %= d;
}
n.Normalize();
return (uint)r;
}
public static uint DwordMod(BigInteger n, uint d)
{
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
r %= d;
}
return (uint)r;
}
public static BigInteger DwordDiv(BigInteger n, uint d)
{
BigInteger ret = new BigInteger(Sign.Positive, n.length);
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
ret.data[i] = (uint)(r / d);
r %= d;
}
ret.Normalize();
return ret;
}
public static BigInteger[] DwordDivMod(BigInteger n, uint d)
{
BigInteger ret = new BigInteger(Sign.Positive, n.length);
ulong r = 0;
uint i = n.length;
while (i-- > 0)
{
r <<= 32;
r |= n.data[i];
ret.data[i] = (uint)(r / d);
r %= d;
}
ret.Normalize();
BigInteger rem = (uint)r;
return new BigInteger[] { ret, rem };
}
#endregion
#region BigNum
public static BigInteger[] multiByteDivide(BigInteger bi1, BigInteger bi2)
{
if (Compare(bi1, bi2) == Sign.Negative)
return new BigInteger[] { 0, new BigInteger(bi1) };
bi1.Normalize(); bi2.Normalize();
if (bi2.length == 1)
return DwordDivMod(bi1, bi2.data[0]);
var remainderLen = bi1.length + 1;
var divisorLen = (int)bi2.length + 1;
var mask = 0x80000000;
var val = bi2.data[bi2.length - 1];
var shift = 0;
var resultPos = (int)bi1.length - (int)bi2.length;
while (mask != 0 && (val & mask) == 0)
{
shift++; mask >>= 1;
}
var quot = new BigInteger(Sign.Positive, bi1.length - bi2.length + 1);
var rem = (bi1 << shift);
var remainder = rem.data;
bi2 = bi2 << shift;
var j = (int)(remainderLen - bi2.length);
int pos = (int)remainderLen - 1;
uint firstDivisorByte = bi2.data[bi2.length - 1];
ulong secondDivisorByte = bi2.data[bi2.length - 2];
while (j > 0)
{
var dividend = ((ulong)remainder[pos] << 32) + remainder[pos - 1];
var qHat = dividend / firstDivisorByte;
var rHat = dividend % firstDivisorByte;
do
{
if (qHat == 0x100000000 ||
(qHat * secondDivisorByte) > ((rHat << 32) + remainder[pos - 2]))
{
qHat--;
rHat += firstDivisorByte;
if (rHat < 0x100000000)
continue;
}
break;
} while (true);
//
// At this point, q_hat is either exact, or one too large
// (more likely to be exact) so, we attempt to multiply the
// divisor by q_hat, if we get a borrow, we just subtract
// one from q_hat and add the divisor back.
//
uint t;
uint dPos = 0;
int nPos = pos - divisorLen + 1;
ulong mc = 0;
uint uint_q_hat = (uint)qHat;
do
{
mc += (ulong) bi2.data[dPos] * uint_q_hat;
t = remainder[nPos];
remainder[nPos] -= (uint)mc;
mc >>= 32;
if (remainder[nPos] > t) mc++;
dPos++; nPos++;
} while (dPos < divisorLen);
nPos = pos - divisorLen + 1;
dPos = 0;
// Overestimate
if (mc != 0)
{
uint_q_hat--;
ulong sum = 0;
do
{
sum = ((ulong)remainder[nPos]) + bi2.data[dPos] + sum;
remainder[nPos] = (uint)sum;
sum >>= 32;
dPos++; nPos++;
} while (dPos < divisorLen);
}
quot.data[resultPos--] = uint_q_hat;
pos--;
j--;
}
quot.Normalize();
rem.Normalize();
var ret = new[] { quot, rem };
if (shift != 0)
ret[1] >>= shift;
return ret;
}
#endregion
#endregion
#region Shift
public static BigInteger LeftShift(BigInteger bi, int n)
{
if (n == 0) return new BigInteger(bi, bi.length + 1);
int w = n >> 5;
n &= ((1 << 5) - 1);
BigInteger ret = new BigInteger(Sign.Positive, bi.length + 1 + (uint)w);
uint i = 0, l = bi.length;
if (n != 0)
{
uint x, carry = 0;
while (i < l)
{
x = bi.data[i];
ret.data[i + w] = (x << n) | carry;
carry = x >> (32 - n);
i++;
}
ret.data[i + w] = carry;
}
else
{
while (i < l)
{
ret.data[i + w] = bi.data[i];
i++;
}
}
ret.Normalize();
return ret;
}
public static BigInteger RightShift(BigInteger bi, int n)
{
if (n == 0) return new BigInteger(bi);
int w = n >> 5;
int s = n & ((1 << 5) - 1);
BigInteger ret = new BigInteger(Sign.Positive, bi.length - (uint)w + 1);
uint l = (uint)ret.data.Length - 1;
if (s != 0)
{
uint x, carry = 0;
while (l-- > 0)
{
x = bi.data[l + w];
ret.data[l] = (x >> n) | carry;
carry = x << (32 - n);
}
}
else
{
while (l-- > 0)
ret.data[l] = bi.data[l + w];
}
ret.Normalize();
return ret;
}
#endregion
#region Multiply
public static BigInteger MultiplyByDword(BigInteger n, uint f)
{
BigInteger ret = new BigInteger(Sign.Positive, n.length + 1);
uint i = 0;
ulong c = 0;
do
{
c += (ulong)n.data[i] * (ulong)f;
ret.data[i] = (uint)c;
c >>= 32;
} while (++i < n.length);
ret.data[i] = (uint)c;
ret.Normalize();
return ret;
}
/// <summary>
/// Multiplies the data in x [xOffset:xOffset+xLen] by
/// y [yOffset:yOffset+yLen] and puts it into
/// d [dOffset:dOffset+xLen+yLen].
/// </summary>
/// <remarks>
/// This code is unsafe! It is the caller's responsibility to make
/// sure that it is safe to access x [xOffset:xOffset+xLen],
/// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+xLen+yLen].
/// </remarks>
public static unsafe void Multiply(uint[] x, uint xOffset, uint xLen, uint[] y, uint yOffset, uint yLen, uint[] d, uint dOffset)
{
fixed (uint* xx = x, yy = y, dd = d)
{
uint* xP = xx + xOffset,
xE = xP + xLen,
yB = yy + yOffset,
yE = yB + yLen,
dB = dd + dOffset;
for (; xP < xE; xP++, dB++)
{
if (*xP == 0) continue;
ulong mcarry = 0;
uint* dP = dB;
for (uint* yP = yB; yP < yE; yP++, dP++)
{
mcarry += ((ulong)*xP * (ulong)*yP) + (ulong)*dP;
*dP = (uint)mcarry;
mcarry >>= 32;
}
if (mcarry != 0)
*dP = (uint)mcarry;
}
}
}
/// <summary>
/// Multiplies the data in x [xOffset:xOffset+xLen] by
/// y [yOffset:yOffset+yLen] and puts the low mod words into
/// d [dOffset:dOffset+mod].
/// </summary>
/// <remarks>
/// This code is unsafe! It is the caller's responsibility to make
/// sure that it is safe to access x [xOffset:xOffset+xLen],
/// y [yOffset:yOffset+yLen], and d [dOffset:dOffset+mod].
/// </remarks>
public static unsafe void MultiplyMod2p32pmod(uint[] x, int xOffset, int xLen, uint[] y, int yOffest, int yLen, uint[] d, int dOffset, int mod)
{
fixed (uint* xx = x, yy = y, dd = d)
{
uint* xP = xx + xOffset,
xE = xP + xLen,
yB = yy + yOffest,
yE = yB + yLen,
dB = dd + dOffset,
dE = dB + mod;
for (; xP < xE; xP++, dB++)
{
if (*xP == 0) continue;
ulong mcarry = 0;
uint* dP = dB;
for (uint* yP = yB; yP < yE && dP < dE; yP++, dP++)
{
mcarry += ((ulong)*xP * (ulong)*yP) + (ulong)*dP;
*dP = (uint)mcarry;
mcarry >>= 32;
}
if (mcarry != 0 && dP < dE)
*dP = (uint)mcarry;
}
}
}
#endregion
#region Number Theory
public static BigInteger gcd(BigInteger a, BigInteger b)
{
BigInteger x = a;
BigInteger y = b;
BigInteger g = y;
while (x.length > 1)
{
g = x;
x = y % x;
y = g;
}
if (x == 0) return g;
// TODO: should we have something here if we can convert to long?
//
// Now we can just do it with single precision. I am using the binary gcd method,
// as it should be faster.
//
uint yy = x.data[0];
uint xx = y % yy;
int t = 0;
while (((xx | yy) & 1) == 0)
{
xx >>= 1; yy >>= 1; t++;
}
while (xx != 0)
{
while ((xx & 1) == 0) xx >>= 1;
while ((yy & 1) == 0) yy >>= 1;
if (xx >= yy)
xx = (xx - yy) >> 1;
else
yy = (yy - xx) >> 1;
}
return yy << t;
}
public static BigInteger modInverse(BigInteger bi, BigInteger modulus)
{
if (modulus.length == 1) return modInverse(bi, modulus.data[0]);
BigInteger[] p = { 0, 1 };
BigInteger[] q = new BigInteger[2]; // quotients
BigInteger[] r = { 0, 0 }; // remainders
int step = 0;
BigInteger a = modulus;
BigInteger b = bi;
ModulusRing mr = new ModulusRing(modulus);
while (b != 0)
{
if (step > 1)
{
BigInteger pval = mr.Difference(p[0], p[1] * q[0]);
p[0] = p[1]; p[1] = pval;
}
BigInteger[] divret = multiByteDivide(a, b);
q[0] = q[1]; q[1] = divret[0];
r[0] = r[1]; r[1] = divret[1];
a = b;
b = divret[1];
step++;
}
if (r[0] != 1)
throw (new ArithmeticException("No inverse!"));
return mr.Difference(p[0], p[1] * q[0]);
}
#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.
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
namespace BasicEventSourceTests
{
/// <summary>
/// Tests the user experience for common user errors.
/// </summary>
public class TestsUserErrors
{
/// <summary>
/// Try to pass a user defined class (even with EventData)
/// to a manifest based eventSource
/// </summary>
[Fact]
public void Test_BadTypes_Manifest_UserClass()
{
var badEventSource = new BadEventSource_Bad_Type_UserClass();
Test_BadTypes_Manifest(badEventSource);
}
private void Test_BadTypes_Manifest(EventSource source)
{
try
{
using (var listener = new EventListenerListener())
{
var events = new List<Event>();
Debug.WriteLine("Adding delegate to onevent");
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceCommand(source.Name, EventCommand.Enable);
listener.Dispose();
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
// Check the exception text if not ProjectN.
if (!PlatformDetection.IsNetNative)
{
string message = _event.PayloadString(0, "message");
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. "
Assert.True(Regex.IsMatch(message, "Unsupported type"));
}
}
}
finally
{
source.Dispose();
}
}
/// <summary>
/// Test the
/// </summary>
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")]
public void Test_BadEventSource_MismatchedIds()
{
#if USE_ETW
// We expect only one session to be on when running the test but if a ETW session was left
// hanging, it will confuse the EventListener tests.
EtwListener.EnsureStopped();
#endif // USE_ETW
TestUtilities.CheckNoEventSourcesRunning("Start");
var onStartups = new bool[] { false, true };
var listenerGenerators = new Func<Listener>[]
{
() => new EventListenerListener(),
#if USE_ETW
() => new EtwListener()
#endif // USE_ETW
};
var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };
// For every interesting combination, run the test and see that we get a nice failure message.
foreach (bool onStartup in onStartups)
{
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
foreach (EventSourceSettings setting in settings)
{
Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
}
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
/// <summary>
/// A helper that can run the test under a variety of conditions
/// * Whether the eventSource is enabled at startup
/// * Whether the listener is ETW or an EventListern
/// * Whether the ETW output is self describing or not.
/// </summary>
private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings)
{
var eventSourceName = typeof(BadEventSource_MismatchedIds).Name;
Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")");
// Activate the source before the source exists (if told to).
if (onStartup)
listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
var events = new List<Event>();
listener.OnEvent = delegate (Event data) { events.Add(data); };
using (var source = new BadEventSource_MismatchedIds(settings))
{
Assert.Equal(eventSourceName, source.Name);
// activate the source after the source exists (if told to).
if (!onStartup)
listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
source.Event1(1); // Try to send something.
}
listener.Dispose();
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
string message = _event.PayloadString(0, "message");
Debug.WriteLine(String.Format("Message=\"{0}\"", message));
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. "
if (!PlatformDetection.IsFullFramework) // Full framework has typo
Assert.True(Regex.IsMatch(message, "Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent"));
}
[Fact]
public void Test_Bad_WriteRelatedID_ParameterName()
{
#if true
Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet.");
#else
BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null;
EventListenerListener listener = null;
try
{
Guid oldGuid;
Guid newGuid = Guid.NewGuid();
Guid newGuid2 = Guid.NewGuid();
EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid);
bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter();
using (var listener = new EventListenerListener())
{
var events = new List<Event>();
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceCommand(bes.Name, EventCommand.Enable);
bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB");
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
string message = _event.PayloadString(0, "message");
// expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId."
Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId."));
}
}
finally
{
if (bes != null)
{
bes.Dispose();
}
if (listener != null)
{
listener.Dispose();
}
}
#endif
}
}
/// <summary>
/// This EventSource has a common user error, and we want to make sure EventSource
/// gives a reasonable experience in that case.
/// </summary>
internal class BadEventSource_MismatchedIds : EventSource
{
public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { }
public void Event1(int arg) { WriteEvent(1, arg); }
// Error Used the same event ID for this event.
public void Event2(int arg) { WriteEvent(1, arg); }
}
/// <summary>
/// A manifest based provider with a bad type byte[]
/// </summary>
internal class BadEventSource_Bad_Type_ByteArray : EventSource
{
public void Event1(byte[] myArray) { WriteEvent(1, myArray); }
}
public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource
{
public void E2()
{
this.Write("sampleevent", new { a = "a string" });
}
[Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)]
public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId)
{
WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId);
}
public class Keywords
{
public const EventKeywords Debug = (EventKeywords)0x0002;
}
}
[EventData]
public class UserClass
{
public int i;
};
/// <summary>
/// A manifest based provider with a bad type (only supported in self describing)
/// </summary>
internal class BadEventSource_Bad_Type_UserClass : EventSource
{
public void Event1(UserClass myClass) { WriteEvent(1, myClass); }
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Text.Tests
{
public partial class EncodingTest : IClassFixture<CultureSetup>
{
public EncodingTest(CultureSetup setup)
{
// Setting up the culture happens externally, and only once, which is what we want.
// xUnit will keep track of it, do nothing.
}
public static IEnumerable<object[]> CodePageInfo()
{
// The layout is code page, IANA(web) name, and query string.
// Query strings may be undocumented, and IANA names will be returned from Encoding objects.
// Entries are sorted by code page.
yield return new object[] { 37, "ibm037", "ibm037" };
yield return new object[] { 37, "ibm037", "cp037" };
yield return new object[] { 37, "ibm037", "csibm037" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-us" };
yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" };
yield return new object[] { 437, "ibm437", "ibm437" };
yield return new object[] { 437, "ibm437", "437" };
yield return new object[] { 437, "ibm437", "cp437" };
yield return new object[] { 437, "ibm437", "cspc8codepage437" };
yield return new object[] { 500, "ibm500", "ibm500" };
yield return new object[] { 500, "ibm500", "cp500" };
yield return new object[] { 500, "ibm500", "csibm500" };
yield return new object[] { 500, "ibm500", "ebcdic-cp-be" };
yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" };
yield return new object[] { 708, "asmo-708", "asmo-708" };
yield return new object[] { 720, "dos-720", "dos-720" };
yield return new object[] { 737, "ibm737", "ibm737" };
yield return new object[] { 775, "ibm775", "ibm775" };
yield return new object[] { 850, "ibm850", "ibm850" };
yield return new object[] { 850, "ibm850", "cp850" };
yield return new object[] { 852, "ibm852", "ibm852" };
yield return new object[] { 852, "ibm852", "cp852" };
yield return new object[] { 855, "ibm855", "ibm855" };
yield return new object[] { 855, "ibm855", "cp855" };
yield return new object[] { 857, "ibm857", "ibm857" };
yield return new object[] { 857, "ibm857", "cp857" };
yield return new object[] { 858, "ibm00858", "ibm00858" };
yield return new object[] { 858, "ibm00858", "ccsid00858" };
yield return new object[] { 858, "ibm00858", "cp00858" };
yield return new object[] { 858, "ibm00858", "cp858" };
yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" };
yield return new object[] { 860, "ibm860", "ibm860" };
yield return new object[] { 860, "ibm860", "cp860" };
yield return new object[] { 861, "ibm861", "ibm861" };
yield return new object[] { 861, "ibm861", "cp861" };
yield return new object[] { 862, "dos-862", "dos-862" };
yield return new object[] { 862, "dos-862", "cp862" };
yield return new object[] { 862, "dos-862", "ibm862" };
yield return new object[] { 863, "ibm863", "ibm863" };
yield return new object[] { 863, "ibm863", "cp863" };
yield return new object[] { 864, "ibm864", "ibm864" };
yield return new object[] { 864, "ibm864", "cp864" };
yield return new object[] { 865, "ibm865", "ibm865" };
yield return new object[] { 865, "ibm865", "cp865" };
yield return new object[] { 866, "cp866", "cp866" };
yield return new object[] { 866, "cp866", "ibm866" };
yield return new object[] { 869, "ibm869", "ibm869" };
yield return new object[] { 869, "ibm869", "cp869" };
yield return new object[] { 870, "ibm870", "ibm870" };
yield return new object[] { 870, "ibm870", "cp870" };
yield return new object[] { 870, "ibm870", "csibm870" };
yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" };
yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" };
yield return new object[] { 874, "windows-874", "windows-874" };
yield return new object[] { 874, "windows-874", "dos-874" };
yield return new object[] { 874, "windows-874", "iso-8859-11" };
yield return new object[] { 874, "windows-874", "tis-620" };
yield return new object[] { 875, "cp875", "cp875" };
yield return new object[] { 932, "shift_jis", "shift_jis" };
yield return new object[] { 932, "shift_jis", "csshiftjis" };
yield return new object[] { 932, "shift_jis", "cswindows31j" };
yield return new object[] { 932, "shift_jis", "ms_kanji" };
yield return new object[] { 932, "shift_jis", "shift-jis" };
yield return new object[] { 932, "shift_jis", "sjis" };
yield return new object[] { 932, "shift_jis", "x-ms-cp932" };
yield return new object[] { 932, "shift_jis", "x-sjis" };
yield return new object[] { 936, "gb2312", "gb2312" };
yield return new object[] { 936, "gb2312", "chinese" };
yield return new object[] { 936, "gb2312", "cn-gb" };
yield return new object[] { 936, "gb2312", "csgb2312" };
yield return new object[] { 936, "gb2312", "csgb231280" };
yield return new object[] { 936, "gb2312", "csiso58gb231280" };
yield return new object[] { 936, "gb2312", "gb_2312-80" };
yield return new object[] { 936, "gb2312", "gb231280" };
yield return new object[] { 936, "gb2312", "gb2312-80" };
yield return new object[] { 936, "gb2312", "gbk" };
yield return new object[] { 936, "gb2312", "iso-ir-58" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" };
yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" };
yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" };
yield return new object[] { 949, "ks_c_5601-1987", "korean" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" };
yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" };
yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" };
yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" };
yield return new object[] { 950, "big5", "big5" };
yield return new object[] { 950, "big5", "big5-hkscs" };
yield return new object[] { 950, "big5", "cn-big5" };
yield return new object[] { 950, "big5", "csbig5" };
yield return new object[] { 950, "big5", "x-x-big5" };
yield return new object[] { 1026, "ibm1026", "ibm1026" };
yield return new object[] { 1026, "ibm1026", "cp1026" };
yield return new object[] { 1026, "ibm1026", "csibm1026" };
yield return new object[] { 1047, "ibm01047", "ibm01047" };
yield return new object[] { 1140, "ibm01140", "ibm01140" };
yield return new object[] { 1140, "ibm01140", "ccsid01140" };
yield return new object[] { 1140, "ibm01140", "cp01140" };
yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" };
yield return new object[] { 1141, "ibm01141", "ibm01141" };
yield return new object[] { 1141, "ibm01141", "ccsid01141" };
yield return new object[] { 1141, "ibm01141", "cp01141" };
yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" };
yield return new object[] { 1142, "ibm01142", "ibm01142" };
yield return new object[] { 1142, "ibm01142", "ccsid01142" };
yield return new object[] { 1142, "ibm01142", "cp01142" };
yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" };
yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" };
yield return new object[] { 1143, "ibm01143", "ibm01143" };
yield return new object[] { 1143, "ibm01143", "ccsid01143" };
yield return new object[] { 1143, "ibm01143", "cp01143" };
yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" };
yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" };
yield return new object[] { 1144, "ibm01144", "ibm01144" };
yield return new object[] { 1144, "ibm01144", "ccsid01144" };
yield return new object[] { 1144, "ibm01144", "cp01144" };
yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" };
yield return new object[] { 1145, "ibm01145", "ibm01145" };
yield return new object[] { 1145, "ibm01145", "ccsid01145" };
yield return new object[] { 1145, "ibm01145", "cp01145" };
yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" };
yield return new object[] { 1146, "ibm01146", "ibm01146" };
yield return new object[] { 1146, "ibm01146", "ccsid01146" };
yield return new object[] { 1146, "ibm01146", "cp01146" };
yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" };
yield return new object[] { 1147, "ibm01147", "ibm01147" };
yield return new object[] { 1147, "ibm01147", "ccsid01147" };
yield return new object[] { 1147, "ibm01147", "cp01147" };
yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" };
yield return new object[] { 1148, "ibm01148", "ibm01148" };
yield return new object[] { 1148, "ibm01148", "ccsid01148" };
yield return new object[] { 1148, "ibm01148", "cp01148" };
yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" };
yield return new object[] { 1149, "ibm01149", "ibm01149" };
yield return new object[] { 1149, "ibm01149", "ccsid01149" };
yield return new object[] { 1149, "ibm01149", "cp01149" };
yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" };
yield return new object[] { 1250, "windows-1250", "windows-1250" };
yield return new object[] { 1250, "windows-1250", "x-cp1250" };
yield return new object[] { 1251, "windows-1251", "windows-1251" };
yield return new object[] { 1251, "windows-1251", "x-cp1251" };
yield return new object[] { 1252, "windows-1252", "windows-1252" };
yield return new object[] { 1252, "windows-1252", "x-ansi" };
yield return new object[] { 1253, "windows-1253", "windows-1253" };
yield return new object[] { 1254, "windows-1254", "windows-1254" };
yield return new object[] { 1255, "windows-1255", "windows-1255" };
yield return new object[] { 1256, "windows-1256", "windows-1256" };
yield return new object[] { 1256, "windows-1256", "cp1256" };
yield return new object[] { 1257, "windows-1257", "windows-1257" };
yield return new object[] { 1258, "windows-1258", "windows-1258" };
yield return new object[] { 1361, "johab", "johab" };
yield return new object[] { 10000, "macintosh", "macintosh" };
yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" };
yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" };
yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" };
yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" };
yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" };
yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" };
yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" };
yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" };
yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" };
yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" };
yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" };
yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" };
yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" };
yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" };
yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" };
yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" };
yield return new object[] { 20001, "x-cp20001", "x-cp20001" };
yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" };
yield return new object[] { 20003, "x-cp20003", "x-cp20003" };
yield return new object[] { 20004, "x-cp20004", "x-cp20004" };
yield return new object[] { 20005, "x-cp20005", "x-cp20005" };
yield return new object[] { 20105, "x-ia5", "x-ia5" };
yield return new object[] { 20105, "x-ia5", "irv" };
yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" };
yield return new object[] { 20106, "x-ia5-german", "din_66003" };
yield return new object[] { 20106, "x-ia5-german", "german" };
yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" };
yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" };
yield return new object[] { 20107, "x-ia5-swedish", "swedish" };
yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" };
yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" };
yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" };
yield return new object[] { 20261, "x-cp20261", "x-cp20261" };
yield return new object[] { 20269, "x-cp20269", "x-cp20269" };
yield return new object[] { 20273, "ibm273", "ibm273" };
yield return new object[] { 20273, "ibm273", "cp273" };
yield return new object[] { 20273, "ibm273", "csibm273" };
yield return new object[] { 20277, "ibm277", "ibm277" };
yield return new object[] { 20277, "ibm277", "csibm277" };
yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" };
yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" };
yield return new object[] { 20278, "ibm278", "ibm278" };
yield return new object[] { 20278, "ibm278", "cp278" };
yield return new object[] { 20278, "ibm278", "csibm278" };
yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" };
yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" };
yield return new object[] { 20280, "ibm280", "ibm280" };
yield return new object[] { 20280, "ibm280", "cp280" };
yield return new object[] { 20280, "ibm280", "csibm280" };
yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" };
yield return new object[] { 20284, "ibm284", "ibm284" };
yield return new object[] { 20284, "ibm284", "cp284" };
yield return new object[] { 20284, "ibm284", "csibm284" };
yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" };
yield return new object[] { 20285, "ibm285", "ibm285" };
yield return new object[] { 20285, "ibm285", "cp285" };
yield return new object[] { 20285, "ibm285", "csibm285" };
yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" };
yield return new object[] { 20290, "ibm290", "ibm290" };
yield return new object[] { 20290, "ibm290", "cp290" };
yield return new object[] { 20290, "ibm290", "csibm290" };
yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" };
yield return new object[] { 20297, "ibm297", "ibm297" };
yield return new object[] { 20297, "ibm297", "cp297" };
yield return new object[] { 20297, "ibm297", "csibm297" };
yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" };
yield return new object[] { 20420, "ibm420", "ibm420" };
yield return new object[] { 20420, "ibm420", "cp420" };
yield return new object[] { 20420, "ibm420", "csibm420" };
yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" };
yield return new object[] { 20423, "ibm423", "ibm423" };
yield return new object[] { 20423, "ibm423", "cp423" };
yield return new object[] { 20423, "ibm423", "csibm423" };
yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" };
yield return new object[] { 20424, "ibm424", "ibm424" };
yield return new object[] { 20424, "ibm424", "cp424" };
yield return new object[] { 20424, "ibm424", "csibm424" };
yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" };
yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" };
yield return new object[] { 20838, "ibm-thai", "ibm-thai" };
yield return new object[] { 20838, "ibm-thai", "csibmthai" };
yield return new object[] { 20866, "koi8-r", "koi8-r" };
yield return new object[] { 20866, "koi8-r", "cskoi8r" };
yield return new object[] { 20866, "koi8-r", "koi" };
yield return new object[] { 20866, "koi8-r", "koi8" };
yield return new object[] { 20866, "koi8-r", "koi8r" };
yield return new object[] { 20871, "ibm871", "ibm871" };
yield return new object[] { 20871, "ibm871", "cp871" };
yield return new object[] { 20871, "ibm871", "csibm871" };
yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" };
yield return new object[] { 20880, "ibm880", "ibm880" };
yield return new object[] { 20880, "ibm880", "cp880" };
yield return new object[] { 20880, "ibm880", "csibm880" };
yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" };
yield return new object[] { 20905, "ibm905", "ibm905" };
yield return new object[] { 20905, "ibm905", "cp905" };
yield return new object[] { 20905, "ibm905", "csibm905" };
yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" };
yield return new object[] { 20924, "ibm00924", "ibm00924" };
yield return new object[] { 20924, "ibm00924", "ccsid00924" };
yield return new object[] { 20924, "ibm00924", "cp00924" };
yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" };
yield return new object[] { 20932, "euc-jp", "euc-jp" };
yield return new object[] { 20936, "x-cp20936", "x-cp20936" };
yield return new object[] { 20949, "x-cp20949", "x-cp20949" };
yield return new object[] { 21025, "cp1025", "cp1025" };
yield return new object[] { 21866, "koi8-u", "koi8-u" };
yield return new object[] { 21866, "koi8-u", "koi8-ru" };
yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" };
yield return new object[] { 28592, "iso-8859-2", "csisolatin2" };
yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" };
yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" };
yield return new object[] { 28592, "iso-8859-2", "iso8859-2" };
yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" };
yield return new object[] { 28592, "iso-8859-2", "l2" };
yield return new object[] { 28592, "iso-8859-2", "latin2" };
yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" };
yield return new object[] { 28593, "iso-8859-3", "csisolatin3" };
yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" };
yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" };
yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" };
yield return new object[] { 28593, "iso-8859-3", "l3" };
yield return new object[] { 28593, "iso-8859-3", "latin3" };
yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" };
yield return new object[] { 28594, "iso-8859-4", "csisolatin4" };
yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" };
yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" };
yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" };
yield return new object[] { 28594, "iso-8859-4", "l4" };
yield return new object[] { 28594, "iso-8859-4", "latin4" };
yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" };
yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" };
yield return new object[] { 28595, "iso-8859-5", "cyrillic" };
yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" };
yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" };
yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" };
yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" };
yield return new object[] { 28596, "iso-8859-6", "arabic" };
yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" };
yield return new object[] { 28596, "iso-8859-6", "ecma-114" };
yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" };
yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" };
yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" };
yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" };
yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" };
yield return new object[] { 28597, "iso-8859-7", "ecma-118" };
yield return new object[] { 28597, "iso-8859-7", "elot_928" };
yield return new object[] { 28597, "iso-8859-7", "greek" };
yield return new object[] { 28597, "iso-8859-7", "greek8" };
yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" };
yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" };
yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" };
yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" };
yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" };
yield return new object[] { 28598, "iso-8859-8", "hebrew" };
yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" };
yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" };
yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" };
yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" };
yield return new object[] { 28598, "iso-8859-8", "logical" };
yield return new object[] { 28598, "iso-8859-8", "visual" };
yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" };
yield return new object[] { 28599, "iso-8859-9", "csisolatin5" };
yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" };
yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" };
yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" };
yield return new object[] { 28599, "iso-8859-9", "l5" };
yield return new object[] { 28599, "iso-8859-9", "latin5" };
yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" };
yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" };
yield return new object[] { 28605, "iso-8859-15", "csisolatin9" };
yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" };
yield return new object[] { 28605, "iso-8859-15", "l9" };
yield return new object[] { 28605, "iso-8859-15", "latin9" };
yield return new object[] { 29001, "x-europa", "x-europa" };
yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" };
yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" };
yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" };
yield return new object[] { 50222, "iso-2022-jp", "iso-2022-jp" };
yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" };
yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" };
yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" };
yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" };
yield return new object[] { 50227, "x-cp50227", "x-cp50227" };
yield return new object[] { 50227, "x-cp50227", "cp50227" };
yield return new object[] { 51932, "euc-jp", "euc-jp" };
yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" };
yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" };
yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" };
yield return new object[] { 51932, "euc-jp", "x-euc" };
yield return new object[] { 51932, "euc-jp", "x-euc-jp" };
yield return new object[] { 51936, "euc-cn", "euc-cn" };
yield return new object[] { 51936, "euc-cn", "x-euc-cn" };
yield return new object[] { 51949, "euc-kr", "euc-kr" };
yield return new object[] { 51949, "euc-kr", "cseuckr" };
yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" };
yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" };
yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" };
yield return new object[] { 54936, "gb18030", "gb18030" };
yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" };
yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" };
yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" };
yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" };
yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" };
yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" };
yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" };
yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" };
yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" };
yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" };
}
public static IEnumerable<object[]> SpecificCodepageEncodings()
{
// Layout is codepage encoding, bytes, and matching unicode string.
yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" };
yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } ,
"\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"};
yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" };
yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } ,
"\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"};
}
public static IEnumerable<object[]> MultibyteCharacterEncodings()
{
// Layout is the encoding, bytes, and expected result.
yield return new object[] { "iso-2022-jp",
new byte[] { 0xA,
0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A,
0x1B, 0x28, 0x42,
0x1B, 0x24, 0x42, 0x25, 0x4A,
0x1B, 0x28, 0x42,
0x1B, 0x24, 0x42, 0x25, 0x4A,
0x1B, 0x28, 0x42,
0x1B, 0x1, 0x2, 0x3, 0x4,
0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A,
0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 },
new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4,
0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43}
};
yield return new object[] { "GB18030",
new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 },
new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 }
};
yield return new object[] { "shift_jis",
new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 },
new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 }
};
yield return new object[] { "iso-2022-kr",
new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E },
new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E }
};
yield return new object[] { "hz-gb-2312",
new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 },
new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, }
};
}
private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings()
{
yield return Map(1200, "utf-16");
yield return Map(12000, "utf-32");
yield return Map(20127, "us-ascii");
yield return Map(65000, "utf-7");
yield return Map(65001, "utf-8");
}
private static KeyValuePair<int, string> Map(int codePage, string webName)
{
return new KeyValuePair<int, string>(codePage, webName);
}
[Fact]
public static void TestDefaultEncodings()
{
ValidateDefaultEncodings();
// The default encoding should be something from the known list.
Encoding defaultEncoding = Encoding.GetEncoding(0);
Assert.NotNull(defaultEncoding);
KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName);
if (defaultEncoding.CodePage == Encoding.UTF8.CodePage)
{
// if the default encoding is not UTF8 that means either we are running on the full framework
// or the encoding provider is registered throw the call Encoding.RegisterProvider.
// at that time we shouldn't expect exceptions when creating the following encodings.
foreach (object[] mapping in CodePageInfo())
{
Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0]));
AssertExtensions.Throws<ArgumentException>("name", () => Encoding.GetEncoding((string)mapping[2]));
}
// Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present.
// When it is, comment out this line and remove the previous foreach/assert.
// Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName)));
Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings());
}
// Add the code page provider.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
// Make sure added code pages are identical between the provider and the Encoding class.
foreach (object[] mapping in CodePageInfo())
{
Encoding encoding = Encoding.GetEncoding((int)mapping[0]);
Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]);
Assert.Equal(encoding, codePageEncoding);
Assert.Equal(encoding.CodePage, (int)mapping[0]);
Assert.Equal(encoding.WebName, (string)mapping[1]);
// Get encoding via query string.
Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2]));
}
// Adding the code page provider should keep the originals, too.
ValidateDefaultEncodings();
// Currently the class EncodingInfo isn't present in corefx, so this checks the complete list
// When it is, comment out this line and remove the previous foreach/assert.
// Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)),
// Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName)));
// Default encoding may have changed, should still be something on the combined list.
defaultEncoding = Encoding.GetEncoding(0);
Assert.NotNull(defaultEncoding);
mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName);
Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1]))));
TestRegister1252();
}
private static void ValidateDefaultEncodings()
{
foreach (var mapping in CrossplatformDefaultEncodings())
{
Encoding encoding = Encoding.GetEncoding(mapping.Key);
Assert.NotNull(encoding);
Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value));
Assert.Equal(mapping.Value, encoding.WebName);
}
}
[Theory]
[MemberData(nameof(SpecificCodepageEncodings))]
public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected)
{
Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName);
string encoded = encoding.GetString(bytes, 0, bytes.Length);
Assert.Equal(expected, encoded);
Assert.Equal(bytes, encoding.GetBytes(encoded));
byte[] resultBytes = encoding.GetBytes(encoded);
}
[Theory]
[MemberData(nameof(CodePageInfo))]
public static void TestCodepageEncoding(int codePage, string webName, string queryString)
{
Encoding encoding;
// There are two names that have duplicate associated CodePages. For those two names,
// we have to test with the expectation that querying the name will always return the
// same codepage.
if (codePage != 20932 && codePage != 50222)
{
encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString);
Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage));
Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName));
}
else
{
encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage);
Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(queryString));
Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName));
}
Assert.NotNull(encoding);
Assert.Equal(codePage, encoding.CodePage);
Assert.Equal(webName, encoding.WebName);
// Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!)
// Start with space.
string asciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] traveled = encoding.GetChars(encoding.GetBytes(asciiPrintable));
Assert.Equal(asciiPrintable.ToCharArray(), traveled);
}
[Theory]
[MemberData(nameof(MultibyteCharacterEncodings))]
public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected)
{
Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder();
char[] buffer = new char[expected.Length];
for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount)
{
charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex);
}
Assert.Equal(expected, buffer.Select(c => (int)c));
}
[Theory]
[MemberData(nameof(CodePageInfo))]
public static void TestEncodingDisplayNames(int codePage, string webName, string queryString)
{
var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage);
string name = encoding.EncodingName;
// Names can't be empty, and must be printable characters.
Assert.False(string.IsNullOrWhiteSpace(name));
Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c));
}
// This test is run as part of the default mappings test, since it modifies global state which that test
// depends on.
public static void TestRegister1252()
{
// This test case ensure we can map all 1252 codepage codepoints without any exception.
string s1252Result =
"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f" +
"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f" +
"\u0020\u0021\u0022\u0023\u0024\u0025\u0026\u0027\u0028\u0029\u002a\u002b\u002c\u002d\u002e\u002f" +
"\u0030\u0031\u0032\u0033\u0034\u0035\u0036\u0037\u0038\u0039\u003a\u003b\u003c\u003d\u003e\u003f" +
"\u0040\u0041\u0042\u0043\u0044\u0045\u0046\u0047\u0048\u0049\u004a\u004b\u004c\u004d\u004e\u004f" +
"\u0050\u0051\u0052\u0053\u0054\u0055\u0056\u0057\u0058\u0059\u005a\u005b\u005c\u005d\u005e\u005f" +
"\u0060\u0061\u0062\u0063\u0064\u0065\u0066\u0067\u0068\u0069\u006a\u006b\u006c\u006d\u006e\u006f" +
"\u0070\u0071\u0072\u0073\u0074\u0075\u0076\u0077\u0078\u0079\u007a\u007b\u007c\u007d\u007e\u007f" +
"\u20ac\u0081\u201a\u0192\u201e\u2026\u2020\u2021\u02c6\u2030\u0160\u2039\u0152\u008d\u017d\u008f" +
"\u0090\u2018\u2019\u201c\u201d\u2022\u2013\u2014\u02dc\u2122\u0161\u203a\u0153\u009d\u017e\u0178" +
"\u00a0\u00a1\u00a2\u00a3\u00a4\u00a5\u00a6\u00a7\u00a8\u00a9\u00aa\u00ab\u00ac\u00ad\u00ae\u00af" +
"\u00b0\u00b1\u00b2\u00b3\u00b4\u00b5\u00b6\u00b7\u00b8\u00b9\u00ba\u00bb\u00bc\u00bd\u00be\u00bf" +
"\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf" +
"\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d7\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de\u00df" +
"\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef" +
"\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f7\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding win1252 = Encoding.GetEncoding("windows-1252", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
byte[] enc = new byte[256];
for (int j = 0; j < 256; j++)
{
enc[j] = (byte)j;
}
Assert.Equal(s1252Result, win1252.GetString(enc));
}
}
public class CultureSetup : IDisposable
{
private readonly CultureInfo _originalUICulture;
public CultureSetup()
{
_originalUICulture = CultureInfo.CurrentUICulture;
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
}
public void Dispose()
{
CultureInfo.CurrentUICulture = _originalUICulture;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.