context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//******************************************************************************************************************************************************************************************//
// Public Domain //
// //
// Written by Peter O. in 2014. //
// //
// Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ //
// //
// If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ //
//******************************************************************************************************************************************************************************************//
using System;
using System.Text;
namespace Neos.IdentityServer.MultiFactor.WebAuthN.Library.Cbor.Numbers
{
internal static class ERationalCharArrayString {
private const int MaxSafeInt = EDecimal.MaxSafeInt;
public static ERational FromString(
char[] chars,
int offset,
int length,
bool throwException) {
int tmpoffset = offset;
if (chars == null) {
if (!throwException) {
return null;
} else {
throw new ArgumentNullException(nameof(chars));
}
}
if (tmpoffset < 0) {
if (!throwException) {
return null;
} else { throw new FormatException("offset(" + tmpoffset + ") is" +
"\u0020less" + "\u0020than " + "0");
}
}
if (tmpoffset > chars.Length) {
if (!throwException) {
return null;
} else { throw new FormatException("offset(" + tmpoffset + ") is" +
"\u0020more" + "\u0020than " + chars.Length);
}
}
if (length < 0) {
if (!throwException) {
return null;
} else {
throw new FormatException("length(" + length + ") is less than " + "0");
}
}
if (length > chars.Length) {
if (!throwException) {
return null;
} else {
throw new FormatException("length(" + length + ") is more than " +
chars.Length);
}
}
if (chars.Length - tmpoffset < length) {
if (!throwException) {
return null;
} else { throw new FormatException("chars's length minus " +
tmpoffset + "(" + (chars.Length - tmpoffset) + ") is less than " + length);
}
}
if (length == 0) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
var negative = false;
int endStr = tmpoffset + length;
if (chars[tmpoffset] == '+' || chars[tmpoffset] == '-') {
negative = chars[tmpoffset] == '-';
++tmpoffset;
}
var numerInt = 0;
EInteger numer = null;
var haveDigits = false;
var haveDenominator = false;
var ndenomInt = 0;
EInteger ndenom = null;
int i = tmpoffset;
if (i + 8 == endStr) {
if ((chars[i] == 'I' || chars[i] == 'i') &&
(chars[i + 1] == 'N' || chars[i + 1] == 'n') &&
(chars[i + 2] == 'F' || chars[i + 2] == 'f') &&
(chars[i + 3] == 'I' || chars[i + 3] == 'i') && (chars[i + 4] ==
'N' ||
chars[i + 4] == 'n') && (chars[i + 5] == 'I' || chars[i + 5] ==
'i') &&
(chars[i + 6] == 'T' || chars[i + 6] == 't') && (chars[i + 7] ==
'Y' || chars[i + 7] == 'y')) {
return negative ? ERational.NegativeInfinity :
ERational.PositiveInfinity;
}
}
if (i + 3 == endStr) {
if ((chars[i] == 'I' || chars[i] == 'i') &&
(chars[i + 1] == 'N' || chars[i + 1] == 'n') && (chars[i + 2] ==
'F' || chars[i + 2] == 'f')) {
return negative ? ERational.NegativeInfinity :
ERational.PositiveInfinity;
}
}
var numerStart = 0;
if (i + 3 <= endStr) {
// Quiet NaN
if ((chars[i] == 'N' || chars[i] == 'n') && (chars[i + 1] == 'A' ||
chars[i +
1] == 'a') && (chars[i + 2] == 'N' || chars[i + 2] == 'n')) {
if (i + 3 == endStr) {
return (!negative) ? ERational.NaN : ERational.NaN.Negate();
}
i += 3;
numerStart = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
var thisdigit = (int)(chars[i] - '0');
if (numerInt <= MaxSafeInt) {
numerInt *= 10;
numerInt += thisdigit;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (numerInt > MaxSafeInt) {
numer = EInteger.FromSubstring(chars, numerStart, endStr);
return ERational.CreateNaN(numer, false, negative);
} else {
return ERational.CreateNaN(
EInteger.FromInt32(numerInt),
false,
negative);
}
}
}
if (i + 4 <= endStr) {
// Signaling NaN
if ((chars[i] == 'S' || chars[i] == 's') && (chars[i + 1] == 'N' ||
chars[i +
1] == 'n') && (chars[i + 2] == 'A' || chars[i + 2] == 'a') &&
(chars[i + 3] == 'N' || chars[i + 3] == 'n')) {
if (i + 4 == endStr) {
return (!negative) ? ERational.SignalingNaN :
ERational.SignalingNaN.Negate();
}
i += 4;
numerStart = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
var thisdigit = (int)(chars[i] - '0');
haveDigits = haveDigits || thisdigit != 0;
if (numerInt <= MaxSafeInt) {
numerInt *= 10;
numerInt += thisdigit;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
int flags3 = (negative ? BigNumberFlags.FlagNegative : 0) |
BigNumberFlags.FlagSignalingNaN;
if (numerInt > MaxSafeInt) {
numer = EInteger.FromSubstring(chars, numerStart, endStr);
return ERational.CreateNaN(numer, true, negative);
} else {
return ERational.CreateNaN(
EInteger.FromInt32(numerInt),
true,
negative);
}
}
}
// Ordinary number
numerStart = i;
int numerEnd = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
var thisdigit = (int)(chars[i] - '0');
numerEnd = i + 1;
if (numerInt <= MaxSafeInt) {
numerInt *= 10;
numerInt += thisdigit;
}
haveDigits = true;
} else if (chars[i] == '/') {
haveDenominator = true;
++i;
break;
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (!haveDigits) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (numerInt > MaxSafeInt) {
numer = EInteger.FromSubstring(chars, numerStart, numerEnd);
}
if (haveDenominator) {
EInteger denom = null;
var denomInt = 0;
tmpoffset = 1;
haveDigits = false;
if (i == endStr) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
numerStart = i;
for (; i < endStr; ++i) {
if (chars[i] >= '0' && chars[i] <= '9') {
haveDigits = true;
var thisdigit = (int)(chars[i] - '0');
numerEnd = i + 1;
if (denomInt <= MaxSafeInt) {
denomInt *= 10;
denomInt += thisdigit;
}
} else {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
}
if (!haveDigits) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (denomInt > MaxSafeInt) {
denom = EInteger.FromSubstring(chars, numerStart, numerEnd);
}
if (denom == null) {
ndenomInt = denomInt;
} else {
ndenom = denom;
}
} else {
ndenomInt = 1;
}
if (i != endStr) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
if (ndenom == null ? (ndenomInt == 0) : ndenom.IsZero) {
if (!throwException) {
return null;
} else {
throw new FormatException();
}
}
ERational erat = ERational.Create(
numer == null ? (EInteger)numerInt : numer,
ndenom == null ? (EInteger)ndenomInt : ndenom);
return negative ? erat.Negate() : erat;
}
}
}
| |
#region license
// Copyright (c) 2003, 2004, 2005 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using Boo.Lang.Compiler.TypeSystem.Internal;
using Boo.Lang.Environments;
namespace Boo.Lang.Compiler.TypeSystem.Generics
{
/// <summary>
/// A method constructed by supplying type arguments to a generic method, involving internal types.
/// </summary>
/// <remarks>
/// Constructed methods constructed from external generic methods with external type parameters
/// are themselves external, and are represented as ExternalMethod instances. All other cases
/// are represented by this type.
/// </remarks>
public class GenericConstructedMethod : IMethod, IConstructedMethodInfo
{
IType[] _genericArguments;
IMethod _definition;
GenericMapping _genericMapping;
bool _fullyConstructed;
string _fullName;
IParameter[] _parameters;
public GenericConstructedMethod(IMethod definition, IType[] arguments)
{
_definition = definition;
_genericArguments = arguments;
_genericMapping = new InternalGenericMapping(this, arguments);
_fullyConstructed = IsFullyConstructed();
}
private bool IsFullyConstructed()
{
foreach (IType arg in GenericArguments)
{
if (GenericsServices.IsOpenGenericType(arg))
{
return false;
}
}
return true;
}
private string BuildFullName()
{
string[] argumentNames = Array.ConvertAll<IType, string>(
GenericArguments,
delegate(IType t) { return t.FullName; });
return string.Format(
"{0}.{1}[of {2}]",
DeclaringType.FullName,
Name,
string.Join(", ", argumentNames));
}
protected GenericMapping GenericMapping
{
get { return _genericMapping; }
}
public IParameter[] GetParameters()
{
return _parameters ?? (_parameters = GenericMapping.MapParameters(_definition.GetParameters()));
}
public IType ReturnType
{
get { return GenericMapping.MapType(_definition.ReturnType); }
}
public bool IsAbstract
{
get { return _definition.IsAbstract; }
}
public bool IsVirtual
{
get { return _definition.IsVirtual; }
}
public bool IsFinal
{
get { return _definition.IsFinal; }
}
public bool IsSpecialName
{
get { return _definition.IsSpecialName; }
}
public bool IsPInvoke
{
get { return _definition.IsPInvoke; }
}
public IConstructedMethodInfo ConstructedInfo
{
get { return this; }
}
public IGenericMethodInfo GenericInfo
{
get { return null; }
}
public ICallableType CallableType
{
get { return My<TypeSystemServices>.Instance.GetCallableType(this); }
}
public bool IsExtension
{
get { return _definition.IsExtension; }
}
public bool IsProtected
{
get { return _definition.IsProtected; }
}
public bool IsInternal
{
get { return _definition.IsInternal; }
}
public bool IsPrivate
{
get { return _definition.IsPrivate; }
}
public bool AcceptVarArgs
{
get { return _definition.AcceptVarArgs; }
}
public bool IsDuckTyped
{
get { return _definition.IsDuckTyped; }
}
public IType DeclaringType
{
get { return _definition.DeclaringType; }
}
public bool IsStatic
{
get { return _definition.IsStatic; }
}
public bool IsPublic
{
get { return _definition.IsPublic; }
}
public IType Type
{
get { return CallableType; }
}
public string Name
{
get { return _definition.Name; }
}
public string FullName
{
get { return _fullName ?? (_fullName = BuildFullName()); }
}
public EntityType EntityType
{
get { return EntityType.Method; }
}
public IMethod GenericDefinition
{
get { return _definition; }
}
public IType[] GenericArguments
{
get { return _genericArguments; }
}
public bool FullyConstructed
{
get { return _fullyConstructed; }
}
public bool IsDefined(IType attributeType)
{
return _definition.IsDefined(attributeType);
}
public override string ToString()
{
return FullName;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace PSTaskDialog
{
//--------------------------------------------------------------------------------
#region PUBLIC enums
//--------------------------------------------------------------------------------
public enum eSysIcons { Information, Question, Warning, Error };
public enum eTaskDialogButtons { YesNo, YesNoCancel, OKCancel, OK, Close, Cancel, None }
#endregion
//--------------------------------------------------------------------------------
public static class cTaskDialog
{
// PUBLIC static values...
static public bool VerificationChecked = false;
static public int RadioButtonResult = -1;
static public int CommandButtonResult = -1;
static public int EmulatedFormWidth = 450;
static public bool ForceEmulationMode = false;
static public bool UseToolWindowOnXP = true;
static public bool PlaySystemSounds = true;
static public EventHandler OnTaskDialogShown = null;
static public EventHandler OnTaskDialogClosed = null;
//--------------------------------------------------------------------------------
#region ShowTaskDialogBox
//--------------------------------------------------------------------------------
static public DialogResult ShowTaskDialogBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string RadioButtons,
string CommandButtons,
eTaskDialogButtons Buttons,
eSysIcons MainIcon,
eSysIcons FooterIcon,
int DefaultIndex)
{
DialogResult result;
if (OnTaskDialogShown != null)
OnTaskDialogShown(null, EventArgs.Empty);
if (VistaTaskDialog.IsAvailableOnThisOS && !ForceEmulationMode)
{
// [OPTION 1] Show Vista TaskDialog
VistaTaskDialog vtd = new VistaTaskDialog();
vtd.WindowTitle = Title;
vtd.MainInstruction = MainInstruction;
vtd.Content = Content;
vtd.ExpandedInformation = ExpandedInfo;
vtd.Footer = Footer;
// Radio Buttons
if (RadioButtons != "")
{
List<VistaTaskDialogButton> lst = new List<VistaTaskDialogButton>();
string[] arr = RadioButtons.Split(new char[] { '|' });
for (int i = 0; i < arr.Length; i++)
{
try
{
VistaTaskDialogButton button = new VistaTaskDialogButton();
button.ButtonId = 1000 + i;
button.ButtonText = arr[i];
lst.Add(button);
}
catch (FormatException)
{
}
}
vtd.RadioButtons = lst.ToArray();
vtd.NoDefaultRadioButton = (DefaultIndex == -1);
if (DefaultIndex >= 0)
vtd.DefaultRadioButton = DefaultIndex;
}
// Custom Buttons
if (CommandButtons != "")
{
List<VistaTaskDialogButton> lst = new List<VistaTaskDialogButton>();
string[] arr = CommandButtons.Split(new char[] { '|' });
for (int i = 0; i < arr.Length; i++)
{
try
{
VistaTaskDialogButton button = new VistaTaskDialogButton();
button.ButtonId = 2000 + i;
button.ButtonText = arr[i];
lst.Add(button);
}
catch (FormatException)
{
}
}
vtd.Buttons = lst.ToArray();
if (DefaultIndex >= 0)
vtd.DefaultButton = DefaultIndex;
}
switch (Buttons)
{
case eTaskDialogButtons.YesNo:
vtd.CommonButtons = VistaTaskDialogCommonButtons.Yes | VistaTaskDialogCommonButtons.No;
break;
case eTaskDialogButtons.YesNoCancel:
vtd.CommonButtons = VistaTaskDialogCommonButtons.Yes | VistaTaskDialogCommonButtons.No | VistaTaskDialogCommonButtons.Cancel;
break;
case eTaskDialogButtons.OKCancel:
vtd.CommonButtons = VistaTaskDialogCommonButtons.Ok | VistaTaskDialogCommonButtons.Cancel;
break;
case eTaskDialogButtons.OK:
vtd.CommonButtons = VistaTaskDialogCommonButtons.Ok;
break;
case eTaskDialogButtons.Close:
vtd.CommonButtons = VistaTaskDialogCommonButtons.Close;
break;
case eTaskDialogButtons.Cancel:
vtd.CommonButtons = VistaTaskDialogCommonButtons.Cancel;
break;
default:
vtd.CommonButtons = 0;
break;
}
switch (MainIcon)
{
case eSysIcons.Information: vtd.MainIcon = VistaTaskDialogIcon.Information; break;
case eSysIcons.Question: vtd.MainIcon = VistaTaskDialogIcon.Information; break;
case eSysIcons.Warning: vtd.MainIcon = VistaTaskDialogIcon.Warning; break;
case eSysIcons.Error: vtd.MainIcon = VistaTaskDialogIcon.Error; break;
}
switch (FooterIcon)
{
case eSysIcons.Information: vtd.FooterIcon = VistaTaskDialogIcon.Information; break;
case eSysIcons.Question: vtd.FooterIcon = VistaTaskDialogIcon.Information; break;
case eSysIcons.Warning: vtd.FooterIcon = VistaTaskDialogIcon.Warning; break;
case eSysIcons.Error: vtd.FooterIcon = VistaTaskDialogIcon.Error; break;
}
vtd.EnableHyperlinks = false;
vtd.ShowProgressBar = false;
vtd.AllowDialogCancellation = (Buttons == eTaskDialogButtons.Cancel ||
Buttons == eTaskDialogButtons.Close ||
Buttons == eTaskDialogButtons.OKCancel ||
Buttons == eTaskDialogButtons.YesNoCancel);
vtd.CallbackTimer = false;
vtd.ExpandedByDefault = false;
vtd.ExpandFooterArea = false;
vtd.PositionRelativeToWindow = true;
vtd.RightToLeftLayout = false;
vtd.NoDefaultRadioButton = false;
vtd.CanBeMinimized = false;
vtd.ShowMarqueeProgressBar = false;
vtd.UseCommandLinks = (CommandButtons != "");
vtd.UseCommandLinksNoIcon = false;
vtd.VerificationText = VerificationText;
vtd.VerificationFlagChecked = false;
vtd.ExpandedControlText = "Hide details";
vtd.CollapsedControlText = "Show details";
vtd.Callback = null;
// Show the Dialog
result = (DialogResult)vtd.Show((vtd.CanBeMinimized ? null : Owner), out VerificationChecked, out RadioButtonResult);
// if a command button was clicked, then change return result
// to "DialogResult.OK" and set the CommandButtonResult
if ((int)result >= 2000)
{
CommandButtonResult = ((int)result - 2000);
result = DialogResult.OK;
}
if (RadioButtonResult >= 1000)
RadioButtonResult -= 1000; // deduct the ButtonID start value for radio buttons
}
else
{
// [OPTION 2] Show Emulated Form
using (frmTaskDialog td = new frmTaskDialog())
{
td.Title = Title;
td.MainInstruction = MainInstruction;
td.Content = Content;
td.ExpandedInfo = ExpandedInfo;
td.Footer = Footer;
td.RadioButtons = RadioButtons;
td.CommandButtons = CommandButtons;
td.Buttons = Buttons;
td.MainIcon = MainIcon;
td.FooterIcon = FooterIcon;
td.VerificationText = VerificationText;
td.Width = EmulatedFormWidth;
td.DefaultButtonIndex = DefaultIndex;
td.BuildForm();
result = td.ShowDialog(Owner);
RadioButtonResult = td.RadioButtonIndex;
CommandButtonResult = td.CommandButtonClickedIndex;
VerificationChecked = td.VerificationCheckBoxChecked;
}
}
if (OnTaskDialogClosed != null)
OnTaskDialogClosed(null, EventArgs.Empty);
return result;
}
//--------------------------------------------------------------------------------
// Overloaded versions...
//--------------------------------------------------------------------------------
static public DialogResult ShowTaskDialogBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string RadioButtons,
string CommandButtons,
eTaskDialogButtons Buttons,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
return ShowTaskDialogBox(Owner, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText, RadioButtons, CommandButtons, Buttons, MainIcon, FooterIcon, 0);
}
static public DialogResult ShowTaskDialogBox(string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string RadioButtons,
string CommandButtons,
eTaskDialogButtons Buttons,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
return ShowTaskDialogBox(null, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText, RadioButtons, CommandButtons, Buttons, MainIcon, FooterIcon, 0);
}
#endregion
//--------------------------------------------------------------------------------
#region MessageBox
//--------------------------------------------------------------------------------
static public DialogResult MessageBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
eTaskDialogButtons Buttons,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
return ShowTaskDialogBox(Owner, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText, "", "", Buttons, MainIcon, FooterIcon);
}
//--------------------------------------------------------------------------------
// Overloaded versions...
//--------------------------------------------------------------------------------
static public DialogResult MessageBox(string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
eTaskDialogButtons Buttons,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
return ShowTaskDialogBox(null, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText, "", "", Buttons, MainIcon, FooterIcon);
}
static public DialogResult MessageBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
eTaskDialogButtons Buttons,
eSysIcons MainIcon)
{
return MessageBox(Owner, Title, MainInstruction, Content, "", "", "", Buttons, MainIcon, eSysIcons.Information);
}
static public DialogResult MessageBox(string Title,
string MainInstruction,
string Content,
eTaskDialogButtons Buttons,
eSysIcons MainIcon)
{
return MessageBox(null, Title, MainInstruction, Content, "", "", "", Buttons, MainIcon, eSysIcons.Information);
}
//--------------------------------------------------------------------------------
#endregion
//--------------------------------------------------------------------------------
#region ShowRadioBox
//--------------------------------------------------------------------------------
static public int ShowRadioBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string RadioButtons,
eSysIcons MainIcon,
eSysIcons FooterIcon,
int DefaultIndex)
{
DialogResult res = ShowTaskDialogBox(Owner, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText,
RadioButtons, "", eTaskDialogButtons.OKCancel, MainIcon, FooterIcon, DefaultIndex);
if (res == DialogResult.OK)
return RadioButtonResult;
else
return -1;
}
//--------------------------------------------------------------------------------
// Overloaded versions...
//--------------------------------------------------------------------------------
static public int ShowRadioBox(string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string RadioButtons,
eSysIcons MainIcon,
eSysIcons FooterIcon,
int DefaultIndex)
{
DialogResult res = ShowTaskDialogBox(null, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText,
RadioButtons, "", eTaskDialogButtons.OKCancel, MainIcon, FooterIcon, DefaultIndex);
if (res == DialogResult.OK)
return RadioButtonResult;
else
return -1;
}
static public int ShowRadioBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string RadioButtons,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
return ShowRadioBox(Owner, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText, RadioButtons, eSysIcons.Question, eSysIcons.Information, 0);
}
static public int ShowRadioBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string RadioButtons,
int DefaultIndex)
{
return ShowRadioBox(Owner, Title, MainInstruction, Content, "", "", "", RadioButtons, eSysIcons.Question, eSysIcons.Information, DefaultIndex);
}
static public int ShowRadioBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string RadioButtons)
{
return ShowRadioBox(Owner, Title, MainInstruction, Content, "", "", "", RadioButtons, eSysIcons.Question, eSysIcons.Information, 0);
}
static public int ShowRadioBox(string Title,
string MainInstruction,
string Content,
string RadioButtons)
{
return ShowRadioBox(null, Title, MainInstruction, Content, "", "", "", RadioButtons, eSysIcons.Question, eSysIcons.Information, 0);
}
#endregion
//--------------------------------------------------------------------------------
#region ShowCommandBox
//--------------------------------------------------------------------------------
static public int ShowCommandBox(IWin32Window Owner,
string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string CommandButtons,
bool ShowCancelButton,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
DialogResult res = ShowTaskDialogBox(Owner, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText,
"", CommandButtons, (ShowCancelButton ? eTaskDialogButtons.Cancel : eTaskDialogButtons.None),
MainIcon, FooterIcon);
if (res == DialogResult.OK)
return CommandButtonResult;
else
return -1;
}
//--------------------------------------------------------------------------------
// Overloaded versions...
//--------------------------------------------------------------------------------
static public int ShowCommandBox(string Title,
string MainInstruction,
string Content,
string ExpandedInfo,
string Footer,
string VerificationText,
string CommandButtons,
bool ShowCancelButton,
eSysIcons MainIcon,
eSysIcons FooterIcon)
{
DialogResult res = ShowTaskDialogBox(null, Title, MainInstruction, Content, ExpandedInfo, Footer, VerificationText,
"", CommandButtons, (ShowCancelButton ? eTaskDialogButtons.Cancel : eTaskDialogButtons.None),
MainIcon, FooterIcon);
if (res == DialogResult.OK)
return CommandButtonResult;
else
return -1;
}
static public int ShowCommandBox(IWin32Window Owner, string Title, string MainInstruction, string Content, string CommandButtons, bool ShowCancelButton)
{
return ShowCommandBox(Owner, Title, MainInstruction, Content, "", "", "", CommandButtons, ShowCancelButton, eSysIcons.Question, eSysIcons.Information);
}
static public int ShowCommandBox(string Title, string MainInstruction, string Content, string CommandButtons, bool ShowCancelButton)
{
return ShowCommandBox(null, Title, MainInstruction, Content, "", "", "", CommandButtons, ShowCancelButton, eSysIcons.Question, eSysIcons.Information);
}
#endregion
//--------------------------------------------------------------------------------
}
}
| |
using System.Collections.Generic;
using PDNUtils.Compare;
using PDNUtils.Help;
using PDNUtils.Runner.Attributes;
namespace NET4.TestClasses
{
[RunableClass]
public class TestDictionary
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[Run(false)]
protected static void DictionaryTest()
{
//IEqualityComparer<object[]> comparer = new ObjectArrayComparer();
//var d = new Dictionary<object[], string>(comparer);
//var foo = new object[] { "1", "2" };
//var bar = new object[] { "1", "2" };
//var foobar = new object[] { "3", "1" };
//var barfoo = new object[] { "3", "1xxxccc" };
//d[foo] = "foo";
//d[bar] = "bar";
//d[foobar] = "foobar";
//d[barfoo] = "barfoo";
//IEqualityComparer<string[]> comparer = new StringArrayComparer();
//var d = new Dictionary<string[], string>(comparer);
//var foo = new string[] { "1", "2xcxcxc" };
//var bar = new string[] { "1", "2" };
//var foobar = new string[] { "3", "1" };
//var barfoo = new string[] { "3", "1" };
//d[foo] = "foo";
//d[bar] = "bar";
//d[foobar] = "foobar";
//d[barfoo] = "barfoo";
var netObjects = CreateNetObjects();
var relatedEntityKeysDictionary = getRelatedEntityKeysDictionary();
var res = CreateNetObjectMappings(relatedEntityKeysDictionary, netObjects);
//ConsolePrint.print(d);
}
private static IDictionary<string, IDictionary<object[], NetObject>> CreateNetObjectMappings(IEnumerable<KeyValuePair<string, string[]>> relatedEntityKeysDictionary, IEnumerable<NetObject> netObjects)
{
var result = new Dictionary<string, IDictionary<object[], NetObject>>();
var keysCache = new Dictionary<string[], IDictionary<object[], NetObject>>(new StringArrayComparer());
foreach (var keyValuePair in relatedEntityKeysDictionary)
{
var keySet = keyValuePair.Value;
IDictionary<object[], NetObject> mapping;
if (!keysCache.TryGetValue(keySet, out mapping))
{
mapping = MakeMapping(keySet, netObjects);
keysCache[keySet] = mapping;
}
result.Add(keyValuePair.Key, mapping);
}
return result;
}
private static Dictionary<object[], NetObject> MakeMapping(string[] keySet, IEnumerable<NetObject> netObjects)
{
var res = new Dictionary<object[], NetObject>(new ObjectArrayComparer());
foreach (var netObject in netObjects)
{
object[] key = GenerateKey(keySet, netObject);
if (key != null)
{
res[key] = netObject;
}
}
return res;
}
private static object[] GenerateKey(string[] keySet, NetObject netObject)
{
var res = new object[keySet.Length];
int cout = 0;
foreach (var keyName in keySet)
{
var dictionary = netObject.RelatedEntityRow.Properties;
object value;
if (dictionary.TryGetValue(keyName, out value))
{
res[cout++] = value;
}
else
{
//TODO probably throw an exception
log.WarnFormat("there is no property with name '{0}'", keyName);
return null;
}
}
return res;
}
private static Dictionary<string, string[]> getRelatedEntityKeysDictionary()
{
return new Dictionary<string, string[]>()
{
{"Interface",new string[]{"id"}},
{"Volume",new string[]{"id"}},
{"Component",new string[]{"id1","id2"}},
};
}
private static IEnumerable<NetObject> CreateNetObjects()
{
return new[]
{
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Node 1"},
{"id",19},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Node 2"},
{"id",19},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Node 3"},
{"id",199},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Node 21"},
{"id",219},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Node 22"},
{"id",2190},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Comp 1"},
{"id1",190},
{"id2",2190},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Comp 2"},
{"id1",190},
{"id2",2190},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Comp 3"},
{"id1",9190},
{"id2",2190},
}
},
new NetObject
{
Properties = new Dictionary<string,object>
{
{"name","Comp 4"},
{"id1",9190},
{"id2",2190},
}
},
};
}
public class NetObject
{
public ManagedEntity relatedEntityRow = new ManagedEntity();
public ManagedEntity RelatedEntityRow
{
get
{
return relatedEntityRow;
}
}
public IDictionary<string, object> Properties
{
set
{
foreach (var keyValuePair in value)
{
relatedEntityRow.Properties.Add(keyValuePair.Key, keyValuePair.Value);
}
}
}
}
public class ManagedEntity
{
private Dictionary<string, object> properties = new Dictionary<string, object>();
public Dictionary<string, object> Properties
{
get
{
return properties;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace PETools
{
public partial class PETool
{
public IMAGE_DOS_HEADER dosHeader;
public byte[] dosStub;
public IMAGE_NT_HEADERS ntSignature;
public IMAGE_FILE_HEADER fileHeader;
public IMAGE_OPTIONAL_HEADER32 optionalHeader;
public IMAGE_DATA_DIRECTORIES dataDirectories;
List<PESection> sections;
/// <summary>
/// Raw data content of entire PE.
/// </summary>
public byte[] rawData;
bool Is32BitHeader
{
get
{
return (PECharacteristics.IMAGE_FILE_32BIT_MACHINE & fileHeader.Characteristics) == PECharacteristics.IMAGE_FILE_32BIT_MACHINE;
}
}
/// <summary>
/// Read a PE file.
/// </summary>
/// <param name="filePath">Path to PE file.</param>
public void Read(string filePath)
{
// Read in the DLL or EXE and get the timestamp
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
Parse(stream);
stream.Close();
}
}
/// <summary>
/// Read a PE file.
/// </summary>
/// <param name="data">Contents of a PE as a byte array.</param>
public void Read(byte[] data)
{
using (MemoryStream stream = new MemoryStream(data))
{
Parse(stream);
stream.Close();
}
}
/// <summary>
/// Parse a PE.
/// </summary>
/// <param name="stream">A stream of the PE contents.</param>
private void Parse(Stream stream)
{
rawData = new byte[stream.Length];
stream.Read(rawData, 0, (int)stream.Length);
stream.Seek(0, SeekOrigin.Begin);
BinaryReader reader = new BinaryReader(stream);
dosHeader = PEUtility.FromBinaryReader<IMAGE_DOS_HEADER>(reader);
int stubSize = (int)dosHeader.e_lfanew - Marshal.SizeOf(typeof(IMAGE_DOS_HEADER));
dosStub = reader.ReadBytes(stubSize);
// Add 4 bytes to the offset
stream.Seek(dosHeader.e_lfanew, SeekOrigin.Begin);
ntSignature = PEUtility.FromBinaryReader<IMAGE_NT_HEADERS>(reader);
fileHeader = PEUtility.FromBinaryReader<IMAGE_FILE_HEADER>(reader);
optionalHeader = PEUtility.FromBinaryReader<IMAGE_OPTIONAL_HEADER32>(reader);
dataDirectories = PEUtility.FromBinaryReader<IMAGE_DATA_DIRECTORIES>(reader);
sections = new List<PESection>();
for (int i = 0; i < fileHeader.NumberOfSections; i++)
{
IMAGE_SECTION_HEADER header = PEUtility.FromBinaryReader<IMAGE_SECTION_HEADER>(reader);
PESection section = new PESection(header);
section.Parse(ref rawData);
sections.Add(section);
}
}
/// <summary>
/// Layout contents of PE file, updating headers and order sections.
/// </summary>
/// <returns>Returns bool describing if layout succeeded.</returns>
public bool Layout()
{
uint virtualAlignment = optionalHeader.SectionAlignment;
uint fileAlignment = optionalHeader.FileAlignment;
uint totalSize = 0;
uint initializedDataSize = 0;
totalSize += optionalHeader.SizeOfHeaders;
/* Calculate total physical size required */
foreach (PESection s in sections)
{
totalSize += PEUtility.AlignUp((uint)s.Data.Length, fileAlignment);
}
/* Layout the sections in physical order */
uint filePosition = optionalHeader.SizeOfHeaders;
sections.Sort(new SectionPhysicalComparer());
foreach (PESection s in sections)
{
if (s.ContributesToFileSize())
{
s.RawSize = PEUtility.AlignUp((uint)s.Data.Length, fileAlignment);
s.PhysicalAddress = filePosition;
filePosition += s.RawSize;
initializedDataSize += PEUtility.AlignUp((uint)s.Data.Length, fileAlignment);
}
break;
}
optionalHeader.SizeOfInitializedData = initializedDataSize;
/*
* Fix up virtual addresses of the sections.
* We start at 0x1000 (seems to be the convention)
* Text should come first, then followed by data, then reloc
* As we encounter certain sections, we need to update
* special fields (data directory entries etc.).
*/
uint virtAddr = 0x1000;
bool dataSectionEncountered = false;
sections.Sort(new SectionVirtualComparer());
foreach (PESection s in sections)
{
if (s.Name == ".text")
{
optionalHeader.BaseOfCode = virtAddr;
}
if (!dataSectionEncountered &&
((s.Name == ".data") || (s.Name == ".rdata")))
{
dataSectionEncountered = true;
optionalHeader.BaseOfData = virtAddr;
}
if (s.Name == ".rdata")
{
dataDirectories.debug.VirtualAddress = virtAddr;
}
if (s.Name == ".reloc")
{
dataDirectories.baseReloc.VirtualAddress = virtAddr;
}
s.VirtualAddress = virtAddr;
if (s.HasUninitializedData)
{
// Leave uninitialized data sizes untouched, their raw size is 0
virtAddr += PEUtility.AlignUp(s.VirtualSize, virtualAlignment);
}
else if (s.HasInitializedData && s.HasCode)
{
// It is possible for the virtual size to be greater than the size of raw data
// Leave the virtual size untouched if this is the case
if (s.VirtualSize > s.RawSize)
{
virtAddr += PEUtility.AlignUp(s.VirtualSize, virtualAlignment);
}
else
{
s.VirtualSize = (uint)s.Data.Length;
virtAddr += PEUtility.AlignUp((uint)s.Data.Length, virtualAlignment);
}
}
break;
}
/* Total virtual size is the final virtual address, which includes the initial virtual offset. */
optionalHeader.SizeOfImage = virtAddr;
/* Serialize and write the header contents */
Serialize(totalSize);
return true;
}
private void SortSectionsForLayout()
{
}
public void UpdateHeader()
{
SerializeHeader(ref rawData);
}
private uint SerializeHeader(ref byte[] file)
{
uint filePosition = 0;
Array.Copy(PEUtility.RawSerialize(dosHeader), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER));
Array.Copy(dosStub, 0, file, filePosition, dosStub.Length);
filePosition += (uint)dosStub.Length;
Array.Copy(PEUtility.RawSerialize(ntSignature), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_NT_HEADERS)));
filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_NT_HEADERS));
Array.Copy(PEUtility.RawSerialize(fileHeader), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_FILE_HEADER)));
filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_FILE_HEADER));
Array.Copy(PEUtility.RawSerialize(optionalHeader), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_OPTIONAL_HEADER32)));
filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_OPTIONAL_HEADER32));
return filePosition;
}
private void Serialize(uint totalSize)
{
/* Allocate enough space to contain the whole new file */
byte[] file = new byte[totalSize];
uint filePosition = SerializeHeader(ref file);
Array.Copy(PEUtility.RawSerialize(dataDirectories), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORIES)));
filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_DATA_DIRECTORIES));
// XXX: Sections must be sorted in layout order!
foreach (PESection section in sections)
{
Array.Copy(PEUtility.RawSerialize(section.Header), 0, file, filePosition, Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)));
filePosition += (uint)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER));
}
/* Copy the section data */
filePosition = optionalHeader.SizeOfHeaders;
sections.Sort(new SectionPhysicalComparer());
foreach (PESection s in sections)
{
Array.Copy(s.Data, 0, file, filePosition, s.Data.Length);
filePosition += s.RawSize;
break;
}
/* Overwrite the container data */
rawData = file;
}
/// <summary>
/// Write contents of PE.
/// </summary>
/// <param name="filename">Path of file to write to.</param>
public void WriteFile(string filename)
{
/* Flush the contents of rawData back to disk */
FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
fs.Write(rawData, 0, rawData.Length);
fs.Close();
}
public void AddCOFFSections(List<PESection> sections)
{
}
/// <summary>
/// Write the contents of the provided byte array into the section specified.
/// </summary>
/// <param name="name">Name of section</param>
/// <param name="data">Byte array of section data</param>
/// <returns></returns>
public uint WriteSectionData(string name, byte[] data)
{
PESection section = sections.Find(s => s.Name == name);
if (section == null)
return 0;
section.Data = new byte[data.Length];
Array.Copy(data, 0, section.Data, 0, data.Length);
return (uint)data.Length;
}
/// <summary>
/// Retrieve the contents of the specified section.
/// </summary>
/// <param name="name">Name of section whose contents should be retrieved</param>
/// <returns>Byte array of section contents</returns>
public byte[] GetSectionData(string name)
{
PESection section = sections.Find(s => s.Name == name);
if (section == null)
return null;
else
return section.Data;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GraphUnzipSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class GraphUnzipSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public GraphUnzipSpec(ITestOutputHelper helper) : base (helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 16);
Materializer = ActorMaterializer.Create(Sys, settings);
}
[Fact]
public void A_Unzip_must_unzip_to_two_subscribers()
{
this.AssertAllStagesStopped(() =>
{
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<string>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var unzip = b.Add(new UnZip<int, string>());
var source =
Source.From(new[]
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b"),
new KeyValuePair<int, string>(3, "c")
});
b.From(source).To(unzip.In);
b.From(unzip.Out0)
.Via(Flow.Create<int>().Buffer(16, OverflowStrategy.Backpressure).Select(x => x*2))
.To(Sink.FromSubscriber(c1));
b.From(unzip.Out1)
.Via(Flow.Create<string>().Buffer(16, OverflowStrategy.Backpressure))
.To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub1.Request(1);
sub2.Request(2);
c1.ExpectNext(1*2);
c1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
c2.ExpectNext("a", "b");
c2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
sub1.Request(3);
c1.ExpectNext(2*2, 3*2);
c1.ExpectComplete();
sub2.Request(3);
c2.ExpectNext("c");
c2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Unzip_must_produce_to_right_downstream_even_though_left_downstream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<string>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var unzip = b.Add(new UnZip<int, string>());
var source =
Source.From(new[]
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b"),
new KeyValuePair<int, string>(3, "c")
});
b.From(source).To(unzip.In);
b.From(unzip.Out0).To(Sink.FromSubscriber(c1));
b.From(unzip.Out1).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub1.Cancel();
sub2.Request(3);
c2.ExpectNext("a", "b", "c");
c2.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Unzip_must_produce_to_left_downstream_even_though_right_downstream_cancels()
{
this.AssertAllStagesStopped(() =>
{
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<string>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var unzip = b.Add(new UnZip<int, string>());
var source =
Source.From(new[]
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b"),
new KeyValuePair<int, string>(3, "c")
});
b.From(source).To(unzip.In);
b.From(unzip.Out0).To(Sink.FromSubscriber(c1));
b.From(unzip.Out1).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub2.Cancel();
sub1.Request(3);
c1.ExpectNext(1, 2, 3);
c1.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Unzip_must_not_push_twice_when_pull_is_followed_by_cancel_before_element_has_been_pushed()
{
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<string>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var unzip = b.Add(new UnZip<int, string>());
var source = Source.From(new[]
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b"),
new KeyValuePair<int, string>(3, "c")
});
b.From(source).To(unzip.In);
b.From(unzip.Out0).To(Sink.FromSubscriber(c1));
b.From(unzip.Out1).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub2.Request(3);
sub1.Request(3);
sub2.Cancel();
c1.ExpectNext(1,2,3);
c1.ExpectComplete();
}
[Fact]
public void A_Unzip_must_not_loose_elements_when_pull_is_followed_by_cancel_before_other_sink_has_requested()
{
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<string>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var unzip = b.Add(new UnZip<int, string>());
var source = Source.From(new[]
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b"),
new KeyValuePair<int, string>(3, "c")
});
b.From(source).To(unzip.In);
b.From(unzip.Out0).To(Sink.FromSubscriber(c1));
b.From(unzip.Out1).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub2.Request(3);
sub2.Cancel();
sub1.Request(3);
c1.ExpectNext(1, 2, 3);
c1.ExpectComplete();
}
[Fact]
public void A_Unzip_must_cancel_upstream_when_downstream_cancel()
{
this.AssertAllStagesStopped(() =>
{
var p1 = this.CreateManualPublisherProbe<KeyValuePair<int, string>>();
var c1 = this.CreateManualSubscriberProbe<int>();
var c2 = this.CreateManualSubscriberProbe<string>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var unzip = b.Add(new UnZip<int, string>());
var source = Source.FromPublisher(p1.Publisher);
b.From(source).To(unzip.In);
b.From(unzip.Out0).To(Sink.FromSubscriber(c1));
b.From(unzip.Out1).To(Sink.FromSubscriber(c2));
return ClosedShape.Instance;
})).Run(Materializer);
var p1Sub = p1.ExpectSubscription();
var sub1 = c1.ExpectSubscription();
var sub2 = c2.ExpectSubscription();
sub1.Request(3);
sub2.Request(3);
p1.ExpectRequest(p1Sub, 16);
p1Sub.SendNext(new KeyValuePair<int, string>(1, "a"));
c1.ExpectNext(1);
c2.ExpectNext("a");
p1Sub.SendNext(new KeyValuePair<int, string>(2, "b"));
c1.ExpectNext(2);
c2.ExpectNext("b");
sub1.Cancel();
sub2.Cancel();
p1Sub.ExpectCancellation();
}, Materializer);
}
[Fact]
public void A_Unzip_must_work_with_Zip()
{
this.AssertAllStagesStopped(() =>
{
var c1 = this.CreateManualSubscriberProbe<Tuple<int, string>>();
RunnableGraph.FromGraph(GraphDsl.Create(b =>
{
var zip = b.Add(new Zip<int, string>());
var unzip = b.Add(new UnZip<int, string>());
var source =
Source.From(new[]
{
new KeyValuePair<int, string>(1, "a"),
new KeyValuePair<int, string>(2, "b"),
new KeyValuePair<int, string>(3, "c")
});
b.From(source).To(unzip.In);
b.From(unzip.Out0).To(zip.In0);
b.From(unzip.Out1).To(zip.In1);
b.From(zip.Out).To(Sink.FromSubscriber(c1));
return ClosedShape.Instance;
})).Run(Materializer);
var sub1 = c1.ExpectSubscription();
sub1.Request(5);
c1.ExpectNext(Tuple.Create(1, "a"));
c1.ExpectNext(Tuple.Create(2, "b"));
c1.ExpectNext(Tuple.Create(3, "c"));
c1.ExpectComplete();
}, Materializer);
}
}
}
| |
// 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.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Use these APIs to manage Azure Websites resources through the Azure
/// Resource Manager. All task operations conform to the HTTP/1.1
/// protocol specification and each operation returns an x-ms-request-id
/// header that can be used to obtain information about the request. You
/// must make sure that requests made to these resources are secure. For
/// more information, see <a
/// href="https://msdn.microsoft.com/en-us/library/azure/dn790557.aspx">Authenticating
/// Azure Resource Manager requests.</a>
/// </summary>
public partial class WebSiteManagementClient : ServiceClient<WebSiteManagementClient>, IWebSiteManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription Id
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// API Version
/// </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; }
public virtual ICertificatesOperations Certificates { get; private set; }
public virtual IClassicMobileServicesOperations ClassicMobileServices { get; private set; }
public virtual IDomainsOperations Domains { get; private set; }
public virtual IGlobalModelOperations GlobalModel { get; private set; }
public virtual IGlobalDomainRegistrationOperations GlobalDomainRegistration { get; private set; }
public virtual IGlobalResourceGroupsOperations GlobalResourceGroups { get; private set; }
public virtual IHostingEnvironmentsOperations HostingEnvironments { get; private set; }
public virtual IManagedHostingEnvironmentsOperations ManagedHostingEnvironments { get; private set; }
public virtual IProviderOperations Provider { get; private set; }
public virtual IRecommendationsOperations Recommendations { get; private set; }
public virtual IServerFarmsOperations ServerFarms { get; private set; }
public virtual ISitesOperations Sites { get; private set; }
public virtual ITopLevelDomainsOperations TopLevelDomains { get; private set; }
public virtual IUsageOperations Usage { get; private set; }
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected WebSiteManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient 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 WebSiteManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient 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>
protected WebSiteManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient 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>
protected WebSiteManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public WebSiteManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </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>
public WebSiteManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public WebSiteManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </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>
public WebSiteManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
this.Certificates = new CertificatesOperations(this);
this.ClassicMobileServices = new ClassicMobileServicesOperations(this);
this.Domains = new DomainsOperations(this);
this.GlobalModel = new GlobalModelOperations(this);
this.GlobalDomainRegistration = new GlobalDomainRegistrationOperations(this);
this.GlobalResourceGroups = new GlobalResourceGroupsOperations(this);
this.HostingEnvironments = new HostingEnvironmentsOperations(this);
this.ManagedHostingEnvironments = new ManagedHostingEnvironmentsOperations(this);
this.Provider = new ProviderOperations(this);
this.Recommendations = new RecommendationsOperations(this);
this.ServerFarms = new ServerFarmsOperations(this);
this.Sites = new SitesOperations(this);
this.TopLevelDomains = new TopLevelDomainsOperations(this);
this.Usage = new UsageOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2015-08-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new ResourceJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvc = Google.Ads.GoogleAds.V9.Common;
using gagve = Google.Ads.GoogleAds.V9.Enums;
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedAdGroupSimulationServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetAdGroupSimulationRequestObject()
{
moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient>(moq::MockBehavior.Strict);
GetAdGroupSimulationRequest request = new GetAdGroupSimulationRequest
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::AdGroupSimulation expectedResponse = new gagvr::AdGroupSimulation
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
CpvBidPointList = new gagvc::CpvBidSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
AdGroupId = -2072405675042603230L,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetAdGroupSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupSimulationServiceClient client = new AdGroupSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupSimulation response = client.GetAdGroupSimulation(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupSimulationRequestObjectAsync()
{
moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient>(moq::MockBehavior.Strict);
GetAdGroupSimulationRequest request = new GetAdGroupSimulationRequest
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::AdGroupSimulation expectedResponse = new gagvr::AdGroupSimulation
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
CpvBidPointList = new gagvc::CpvBidSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
AdGroupId = -2072405675042603230L,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetAdGroupSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupSimulationServiceClient client = new AdGroupSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupSimulation responseCallSettings = await client.GetAdGroupSimulationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupSimulation responseCancellationToken = await client.GetAdGroupSimulationAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupSimulation()
{
moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient>(moq::MockBehavior.Strict);
GetAdGroupSimulationRequest request = new GetAdGroupSimulationRequest
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::AdGroupSimulation expectedResponse = new gagvr::AdGroupSimulation
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
CpvBidPointList = new gagvc::CpvBidSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
AdGroupId = -2072405675042603230L,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetAdGroupSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupSimulationServiceClient client = new AdGroupSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupSimulation response = client.GetAdGroupSimulation(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupSimulationAsync()
{
moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient>(moq::MockBehavior.Strict);
GetAdGroupSimulationRequest request = new GetAdGroupSimulationRequest
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::AdGroupSimulation expectedResponse = new gagvr::AdGroupSimulation
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
CpvBidPointList = new gagvc::CpvBidSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
AdGroupId = -2072405675042603230L,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetAdGroupSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupSimulationServiceClient client = new AdGroupSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupSimulation responseCallSettings = await client.GetAdGroupSimulationAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupSimulation responseCancellationToken = await client.GetAdGroupSimulationAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetAdGroupSimulationResourceNames()
{
moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient>(moq::MockBehavior.Strict);
GetAdGroupSimulationRequest request = new GetAdGroupSimulationRequest
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::AdGroupSimulation expectedResponse = new gagvr::AdGroupSimulation
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
CpvBidPointList = new gagvc::CpvBidSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
AdGroupId = -2072405675042603230L,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetAdGroupSimulation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
AdGroupSimulationServiceClient client = new AdGroupSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupSimulation response = client.GetAdGroupSimulation(request.ResourceNameAsAdGroupSimulationName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetAdGroupSimulationResourceNamesAsync()
{
moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient> mockGrpcClient = new moq::Mock<AdGroupSimulationService.AdGroupSimulationServiceClient>(moq::MockBehavior.Strict);
GetAdGroupSimulationRequest request = new GetAdGroupSimulationRequest
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
};
gagvr::AdGroupSimulation expectedResponse = new gagvr::AdGroupSimulation
{
ResourceNameAsAdGroupSimulationName = gagvr::AdGroupSimulationName.FromCustomerAdGroupTypeModificationMethodStartDateEndDate("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[TYPE]", "[MODIFICATION_METHOD]", "[START_DATE]", "[END_DATE]"),
Type = gagve::SimulationTypeEnum.Types.SimulationType.BidModifier,
ModificationMethod = gagve::SimulationModificationMethodEnum.Types.SimulationModificationMethod.Default,
CpcBidPointList = new gagvc::CpcBidSimulationPointList(),
TargetCpaPointList = new gagvc::TargetCpaSimulationPointList(),
CpvBidPointList = new gagvc::CpvBidSimulationPointList(),
TargetRoasPointList = new gagvc::TargetRoasSimulationPointList(),
AdGroupId = -2072405675042603230L,
StartDate = "start_date11b9dbea",
EndDate = "end_date89dae890",
};
mockGrpcClient.Setup(x => x.GetAdGroupSimulationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupSimulation>(stt::Task.FromResult(expectedResponse), null, null, null, null));
AdGroupSimulationServiceClient client = new AdGroupSimulationServiceClientImpl(mockGrpcClient.Object, null);
gagvr::AdGroupSimulation responseCallSettings = await client.GetAdGroupSimulationAsync(request.ResourceNameAsAdGroupSimulationName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::AdGroupSimulation responseCancellationToken = await client.GetAdGroupSimulationAsync(request.ResourceNameAsAdGroupSimulationName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
//***************************************************
//* This file was generated by tool
//* SharpKit
//* At: 29/08/2012 03:59:41 p.m.
//***************************************************
using SharpKit.JavaScript;
namespace Ext.layout
{
#region Context
/// <inheritdocs />
/// <summary>
/// <p>Manages context information during a layout.</p>
/// <h1>Algorithm</h1>
/// <p>This class performs the following jobs:</p>
/// <ul>
/// <li>Cache DOM reads to avoid reading the same values repeatedly.</li>
/// <li>Buffer DOM writes and flush them as a block to avoid read/write interleaving.</li>
/// <li>Track layout dependencies so each layout does not have to figure out the source of
/// its dependent values.</li>
/// <li>Intelligently run layouts when the values on which they depend change (a trigger).</li>
/// <li>Allow layouts to avoid processing when required values are unavailable (a block).</li>
/// </ul>
/// <p>Work done during layout falls into either a "read phase" or a "write phase" and it is
/// essential to always be aware of the current phase. Most methods in
/// <see cref="Ext.layout.Layout">Layout</see> are called during a read phase:
/// <see cref="Ext.layout.Layout.calculate">calculate</see>,
/// <see cref="Ext.layout.Layout.completeLayout">completeLayout</see> and
/// <see cref="Ext.layout.Layout.finalizeLayout">finalizeLayout</see>. The exceptions to this are
/// <see cref="Ext.layout.Layout.beginLayout">beginLayout</see>,
/// <see cref="Ext.layout.Layout.beginLayoutCycle">beginLayoutCycle</see> and
/// <see cref="Ext.layout.Layout.finishedLayout">finishedLayout</see> which are called during
/// a write phase. While <see cref="Ext.layout.Layout.finishedLayout">finishedLayout</see> is called
/// a write phase, it is really intended to be a catch-all for post-processing after a
/// layout run.</p>
/// <p>In a read phase, it is OK to read the DOM but this should be done using the appropriate
/// <see cref="Ext.layout.ContextItem">ContextItem</see> where possible since that provides a cache
/// to avoid redundant reads. No writes should be made to the DOM in a read phase! Instead,
/// the values should be written to the proper ContextItem for later write-back.</p>
/// <p>The rules flip-flop in a write phase. The only difference is that ContextItem methods
/// like <see cref="Ext.layout.ContextItem.getStyle">getStyle</see> will still read the DOM unless the
/// value was previously read. This detail is unknowable from the outside of ContextItem, so
/// read calls to ContextItem should also be avoided in a write phase.</p>
/// <p>Calculating interdependent layouts requires a certain amount of iteration. In a given
/// cycle, some layouts will contribute results that allow other layouts to proceed. The
/// general flow then is to gather all of the layouts (both component and container) in a
/// component tree and queue them all for processing. The initial queue order is bottom-up
/// and component layout first, then container layout (if applicable) for each component.</p>
/// <p>This initial step also calls the beginLayout method on all layouts to clear any values
/// from the DOM that might interfere with calculations and measurements. In other words,
/// this is a "write phase" and reads from the DOM should be strictly avoided.</p>
/// <p>Next the layout enters into its iterations or "cycles". Each cycle consists of calling
/// the <see cref="Ext.layout.Layout.calculate">calculate</see> method on all layouts in the
/// <see cref="Ext.layout.Context.layoutQueue">layoutQueue</see>. These calls are part of a "read phase" and writes to the DOM should
/// be strictly avoided.</p>
/// <h1>Considerations</h1>
/// <p><strong>RULE 1</strong>: Respect the read/write cycles. Always use the <see cref="Ext.layout.ContextItem.getProp">getProp</see>
/// or <see cref="Ext.layout.ContextItem.getDomProp">getDomProp</see> methods to get calculated values;
/// only use the <see cref="Ext.layout.ContextItem.getStyle">getStyle</see> method to read styles; use
/// <see cref="Ext.layout.ContextItem.setProp">setProp</see> to set DOM values. Some reads will, of
/// course, still go directly to the DOM, but if there is a method in
/// <see cref="Ext.layout.ContextItem">ContextItem</see> to do a certain job, it should be used instead
/// of a lower-level equivalent.</p>
/// <p>The basic logic flow in <see cref="Ext.layout.Layout.calculate">calculate</see> consists of gathering
/// values by calling <see cref="Ext.layout.ContextItem.getProp">getProp</see> or
/// <see cref="Ext.layout.ContextItem.getDomProp">getDomProp</see>, calculating results and publishing
/// them by calling <see cref="Ext.layout.ContextItem.setProp">setProp</see>. It is important to realize
/// that <see cref="Ext.layout.ContextItem.getProp">getProp</see> will return <c>undefined</c> if the value
/// is not yet known. But the act of calling the method is enough to track the fact that the
/// calling layout depends (in some way) on this value. In other words, the calling layout is
/// "triggered" by the properties it requests.</p>
/// <p><strong>RULE 2</strong>: Avoid calling <see cref="Ext.layout.ContextItem.getProp">getProp</see> unless the value
/// is needed. Gratuitous calls cause inefficiency because the layout will appear to depend on
/// values that it never actually uses. This applies equally to
/// <see cref="Ext.layout.ContextItem.getDomProp">getDomProp</see> and the test-only methods
/// <see cref="Ext.layout.ContextItem.hasProp">hasProp</see> and <see cref="Ext.layout.ContextItem.hasDomProp">hasDomProp</see>.</p>
/// <p>Because <see cref="Ext.layout.ContextItem.getProp">getProp</see> can return <c>undefined</c>, it is often
/// the case that subsequent math will produce NaN's. This is usually not a problem as the
/// NaN's simply propagate along and result in final results that are NaN. Both <c>undefined</c>
/// and NaN are ignored by <see cref="Ext.layout.ContextItem.setProp">Ext.layout.ContextItem.setProp</see>, so it is often not necessary
/// to even know that this is happening. It does become important for determining if a layout
/// is not done or if it might lead to publishing an incorrect (but not NaN or <c>undefined</c>)
/// value.</p>
/// <p><strong>RULE 3</strong>: If a layout has not calculated all the values it is required to calculate, it
/// must set <see cref="Ext.layout.Layout.done">done</see> to <c>false</c> before returning from
/// <see cref="Ext.layout.Layout.calculate">calculate</see>. This value is always <c>true</c> on entry because
/// it is simpler to detect the incomplete state rather than the complete state (especially up
/// and down a class hierarchy).</p>
/// <p><strong>RULE 4</strong>: A layout must never publish an incomplete (wrong) result. Doing so would cause
/// dependent layouts to run their calculations on those wrong values, producing more wrong
/// values and some layouts may even incorrectly flag themselves as <see cref="Ext.layout.Layout.done">done</see>
/// before the correct values are determined and republished. Doing this will poison the
/// calculations.</p>
/// <p><strong>RULE 5</strong>: Each value should only be published by one layout. If multiple layouts attempt
/// to publish the same values, it would be nearly impossible to avoid breaking <strong>RULE 4</strong>. To
/// help detect this problem, the layout diagnostics will trap on an attempt to set a value
/// from different layouts.</p>
/// <p>Complex layouts can produce many results as part of their calculations. These values are
/// important for other layouts to proceed and need to be published by the earliest possible
/// call to <see cref="Ext.layout.Layout.calculate">Ext.layout.Layout.calculate</see> to avoid unnecessary cycles and poor performance. It is
/// also possible, however, for some results to be related in a way such that publishing them
/// may be an all-or-none proposition (typically to avoid breaking <em>RULE 4</em>).</p>
/// <p><strong>RULE 6</strong>: Publish results as soon as they are known to be correct rather than wait for
/// all values to be calculated. Waiting for everything to be complete can lead to deadlock.
/// The key here is not to forget <strong>RULE 4</strong> in the process.</p>
/// <p>Some layouts depend on certain critical values as part of their calculations. For example,
/// HBox depends on width and cannot do anything until the width is known. In these cases, it
/// is best to use <see cref="Ext.layout.ContextItem.block">block</see> or
/// <see cref="Ext.layout.ContextItem.domBlock">domBlock</see> and thereby avoid processing the layout
/// until the needed value is available.</p>
/// <p><strong>RULE 7</strong>: Use <see cref="Ext.layout.ContextItem.block">block</see> or
/// <see cref="Ext.layout.ContextItem.domBlock">domBlock</see> when values are required to make progress.
/// This will mimize wasted recalculations.</p>
/// <p><strong>RULE 8</strong>: Blocks should only be used when no forward progress can be made. If even one
/// value could still be calculated, a block could result in a deadlock.</p>
/// <p>Historically, layouts have been invoked directly by component code, sometimes in places
/// like an <c>afterLayout</c> method for a child component. With the flexibility now available
/// to solve complex, iterative issues, such things should be done in a responsible layout
/// (be it component or container).</p>
/// <p><strong>RULE 9</strong>: Use layouts to solve layout issues and don't wait for the layout to finish to
/// perform further layouts. This is especially important now that layouts process entire
/// component trees and not each layout in isolation.</p>
/// <h1>Sequence Diagram</h1>
/// <p>The simplest sequence diagram for a layout run looks roughly like this:</p>
/// <pre><code> Context Layout 1 Item 1 Layout 2 Item 2
/// | | | | |
/// ---->X-------------->X | | |
/// run X---------------|-----------|---------->X |
/// X beginLayout | | | |
/// X | | | |
/// A X-------------->X | | |
/// X calculate X---------->X | |
/// X C X getProp | | |
/// B X X---------->X | |
/// X | setProp | | |
/// X | | | |
/// D X---------------|-----------|---------->X |
/// X calculate | | X---------->X
/// X | | | setProp |
/// E X | | | |
/// X---------------|-----------|---------->X |
/// X completeLayout| | F | |
/// X | | | |
/// G X | | | |
/// H X-------------->X | | |
/// X calculate X---------->X | |
/// X I X getProp | | |
/// X X---------->X | |
/// X | setProp | | |
/// J X-------------->X | | |
/// X completeLayout| | | |
/// X | | | |
/// K X-------------->X | | |
/// X---------------|-----------|---------->X |
/// X finalizeLayout| | | |
/// X | | | |
/// L X-------------->X | | |
/// X---------------|-----------|---------->X |
/// X finishedLayout| | | |
/// X | | | |
/// M X-------------->X | | |
/// X---------------|-----------|---------->X |
/// X notifyOwner | | | |
/// N | | | | |
/// - - - - -
/// </code></pre>
/// <p>Notes:</p>
/// <p><strong>A.</strong> This is a call from the <see cref="Ext.layout.Context.run">run</see> method to the <see cref="Ext.layout.Context.runCycle">runCycle</see> method.
/// Each layout in the queue will have its <see cref="Ext.layout.Layout.calculate">calculate</see>
/// method called.</p>
/// <p><strong>B.</strong> After each <see cref="Ext.layout.Layout.calculate">calculate</see> method is called the
/// <see cref="Ext.layout.Layout.done">done</see> flag is checked to see if the Layout has completed.
/// If it has completed and that layout object implements a
/// <see cref="Ext.layout.Layout.completeLayout">completeLayout</see> method, this layout is queued to
/// receive its call. Otherwise, the layout will be queued again unless there are blocks or
/// triggers that govern its requeueing.</p>
/// <p><strong>C.</strong> The call to <see cref="Ext.layout.ContextItem.getProp">getProp</see> is made to the Item
/// and that will be tracked as a trigger (keyed by the name of the property being requested).
/// Changes to this property will cause this layout to be requeued. The call to
/// <see cref="Ext.layout.ContextItem.setProp">setProp</see> will place a value in the item and not
/// directly into the DOM.</p>
/// <p><strong>D.</strong> Call the other layouts now in the first cycle (repeat <strong>B</strong> and <strong>C</strong> for each
/// layout).</p>
/// <p><strong>E.</strong> After completing a cycle, if progress was made (new properties were written to
/// the context) and if the <see cref="Ext.layout.Context.layoutQueue">layoutQueue</see> is not empty, the next cycle is run. If no
/// progress was made or no layouts are ready to run, all buffered values are written to
/// the DOM (a flush).</p>
/// <p><strong>F.</strong> After flushing, any layouts that were marked as <see cref="Ext.layout.Layout.done">done</see>
/// that also have a <see cref="Ext.layout.Layout.completeLayout">completeLayout</see> method are called.
/// This can cause them to become no longer done (see <see cref="Ext.layout.Context.invalidate">invalidate</see>). As with
/// <see cref="Ext.layout.Layout.calculate">calculate</see>, this is considered a "read phase" and
/// direct DOM writes should be avoided.</p>
/// <p><strong>G.</strong> Flushing and calling any pending <see cref="Ext.layout.Layout.completeLayout">completeLayout</see>
/// methods will likely trigger layouts that called <see cref="Ext.layout.ContextItem.getDomProp">getDomProp</see>
/// and unblock layouts that have called <see cref="Ext.layout.ContextItem.domBlock">domBlock</see>.
/// These variants are used when a layout needs the value to be correct in the DOM and not
/// simply known. If this does not cause at least one layout to enter the queue, we have a
/// layout FAILURE. Otherwise, we continue with the next cycle.</p>
/// <p><strong>H.</strong> Call <see cref="Ext.layout.Layout.calculate">calculate</see> on any layouts in the queue
/// at the start of this cycle. Just a repeat of <strong>B</strong> through <strong>G</strong>.</p>
/// <p><strong>I.</strong> Once the layout has calculated all that it is resposible for, it can leave itself
/// in the <see cref="Ext.layout.Layout.done">done</see> state. This is the value on entry to
/// <see cref="Ext.layout.Layout.calculate">calculate</see> and must be cleared in that call if the
/// layout has more work to do.</p>
/// <p><strong>J.</strong> Now that all layouts are done, flush any DOM values and
/// <see cref="Ext.layout.Layout.completeLayout">completeLayout</see> calls. This can again cause
/// layouts to become not done, and so we will be back on another cycle if that happens.</p>
/// <p><strong>K.</strong> After all layouts are done, call the <see cref="Ext.layout.Layout.finalizeLayout">finalizeLayout</see>
/// method on any layouts that have one. As with <see cref="Ext.layout.Layout.completeLayout">completeLayout</see>,
/// this can cause layouts to become no longer done. This is less desirable than using
/// <see cref="Ext.layout.Layout.completeLayout">completeLayout</see> because it will cause all
/// <see cref="Ext.layout.Layout.finalizeLayout">finalizeLayout</see> methods to be called again
/// when we think things are all wrapped up.</p>
/// <p><strong>L.</strong> After finishing the last iteration, layouts that have a
/// <see cref="Ext.layout.Layout.finishedLayout">finishedLayout</see> method will be called. This
/// call will only happen once per run and cannot cause layouts to be run further.</p>
/// <p><strong>M.</strong> After calling finahedLayout, layouts that have a
/// <see cref="Ext.layout.Layout.notifyOwner">notifyOwner</see> method will be called. This
/// call will only happen once per run and cannot cause layouts to be run further.</p>
/// <p><strong>N.</strong> One last flush to make sure everything has been written to the DOM.</p>
/// <h1>Inter-Layout Collaboration</h1>
/// <p>Many layout problems require collaboration between multiple layouts. In some cases, this
/// is as simple as a component's container layout providing results used by its component
/// layout or vise-versa. A slightly more distant collaboration occurs in a box layout when
/// stretchmax is used: the child item's component layout provides results that are consumed
/// by the ownerCt's box layout to determine the size of the children.</p>
/// <p>The various forms of interdependence between a container and its children are described by
/// each components' <see cref="Ext.AbstractComponent.getSizeModel">size model</see>.</p>
/// <p>To facilitate this collaboration, the following pairs of properties are published to the
/// component's <see cref="Ext.layout.ContextItem">ContextItem</see>:</p>
/// <ul>
/// <li>width/height: These hold the final size of the component. The layout indicated by the
/// <see cref="Ext.AbstractComponent.getSizeModel">size model</see> is responsible for setting these.</li>
/// <li>contentWidth/contentHeight: These hold size information published by the container
/// layout or from DOM measurement. These describe the content only. These values are
/// used by the component layout to determine the outer width/height when that component
/// is <see cref="Ext.AbstractComponentConfig.shrinkWrap">shrink-wrapped</see>. They are also used to
/// determine overflow. All container layouts must publish these values for dimensions
/// that are shrink-wrapped. If a component has raw content (not container items), the
/// componentLayout must publish these values instead.</li>
/// </ul>
/// </summary>
[JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
public partial class Context : Ext.Base
{
/// <summary>
/// List of layouts to perform.
/// </summary>
public Ext.util.Queue layoutQueue{get;set;}
/// <summary>
/// One of these values:
/// <li>0 - Before run</li>
/// <li>1 - Running</li>
/// <li>2 - Run complete</li>
/// Defaults to: <c>0</c>
/// </summary>
public JsNumber state{get;set;}
/// <summary>
/// Flushes any pending writes to the DOM by calling each ContextItem in the flushQueue.
/// </summary>
public void flush(){}
/// <summary>
/// Returns the ContextItem for a component.
/// </summary>
/// <param name="cmp">
/// </param>
public void getCmp(Ext.Component cmp){}
/// <summary>
/// Returns the ContextItem for an element.
/// </summary>
/// <param name="parent">
/// </param>
/// <param name="el">
/// </param>
public void getEl(ContextItem parent, Ext.dom.Element el){}
/// <summary>
/// Invalidates one or more components' layouts (component and container). This can be
/// called before run to identify the components that need layout or during the run to
/// restart the layout of a component. This is called internally to flush any queued
/// invalidations at the start of a cycle. If called during a run, it is not expected
/// that new components will be introduced to the layout.
/// </summary>
/// <param name="components"><p>An array of Components or a single Component.</p>
/// </param>
/// <param name="ownerCtContext"><p>The ownerCt's ContextItem.</p>
/// </param>
/// <param name="full"><p>True if all properties should be invalidated, otherwise only
/// those calculated by the component should be invalidated.</p>
/// </param>
public void invalidate(object components, ContextItem ownerCtContext, bool full){}
/// <summary>
/// Queues a ContextItem to have its Ext.layout.ContextItem.flushAnimations method called.
/// </summary>
/// <param name="item">
/// </param>
private void queueAnimation(ContextItem item){}
/// <summary>
/// Queues a layout to have its Ext.layout.Layout.completeLayout method called.
/// </summary>
/// <param name="layout">
/// </param>
private void queueCompletion(Layout layout){}
/// <summary>
/// Queues a layout to have its Ext.layout.Layout.finalizeLayout method called.
/// </summary>
/// <param name="layout">
/// </param>
private void queueFinalize(Layout layout){}
/// <summary>
/// Queues a ContextItem for the next flush to the DOM. This should only be called by
/// the Ext.layout.ContextItem class.
/// </summary>
/// <param name="item">
/// </param>
private void queueFlush(ContextItem item){}
/// <summary>
/// Queue a component (and its tree) to be invalidated on the next cycle.
/// </summary>
/// <param name="item"><p>The component or ContextItem to invalidate.</p>
/// </param>
/// <param name="options"><p>An object describing how to handle the invalidation (see
/// <see cref="Ext.layout.ContextItem.invalidate">Ext.layout.ContextItem.invalidate</see> for details).</p>
/// </param>
private void queueInvalidate(object item, object options){}
/// <summary>
/// Queues a layout for the next calculation cycle. This should not be called if the
/// layout is done, blocked or already in the queue. The only classes that should call
/// this method are this class and Ext.layout.ContextItem.
/// </summary>
/// <param name="layout"><p>The layout to add to the queue.</p>
/// </param>
private void queueLayout(Layout layout){}
/// <summary>
/// Resets the given layout object. This is called at the start of the run and can also
/// be called during the run by calling invalidate.
/// </summary>
/// <param name="layout">
/// </param>
/// <param name="ownerContext">
/// </param>
/// <param name="firstTime">
/// </param>
public void resetLayout(object layout, object ownerContext, object firstTime){}
/// <summary>
/// Runs the layout calculations. This can be called only once on this object.
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if all layouts were completed, false if not.</p>
/// </div>
/// </returns>
public bool run(){return false;}
/// <summary>
/// Performs one layout cycle by calling each layout in the layout queue.
/// </summary>
/// <returns>
/// <span><see cref="bool">Boolean</see></span><div><p>True if some progress was made, false if not.</p>
/// </div>
/// </returns>
protected bool runCycle(){return false;}
/// <summary>
/// Runs one layout as part of a cycle.
/// </summary>
/// <param name="layout">
/// </param>
private void runLayout(object layout){}
/// <summary>
/// Set the size of a component, element or composite or an array of components or elements.
/// </summary>
/// <param name="item"><p>The item(s) to size.</p>
/// </param>
/// <param name="width"><p>The new width to set (ignored if undefined or NaN).</p>
/// </param>
/// <param name="height"><p>The new height to set (ignored if undefined or NaN).</p>
/// </param>
public void setItemSize(object item, JsNumber width, JsNumber height){}
public Context(ContextConfig config){}
public Context(){}
public Context(params object[] args){}
}
#endregion
#region ContextConfig
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class ContextConfig : Ext.BaseConfig
{
public ContextConfig(params object[] args){}
}
#endregion
#region ContextEvents
/// <inheritdocs />
[JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
public partial class ContextEvents : Ext.BaseEvents
{
public ContextEvents(params object[] args){}
}
#endregion
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.Build.Shared;
using System.Reflection;
using Xunit;
using Microsoft.Build.UnitTests.Shared;
namespace Microsoft.Build.UnitTests
{
public class TypeLoader_Tests
{
private static readonly string ProjectFileFolder = Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, "PortableTask");
private static readonly string ProjectFileName = "portableTaskTest.proj";
private static readonly string DLLFileName = "PortableTask.dll";
[Fact]
public void Basic()
{
Assert.True(TypeLoader.IsPartialTypeNameMatch("Csc", "csc")); // ==> exact match
Assert.True(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Microsoft.Build.Tasks.Csc")); // ==> exact match
Assert.True(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Csc")); // ==> partial match
Assert.True(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Tasks.Csc")); // ==> partial match
Assert.True(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask+NestedTask", "NestedTask")); // ==> partial match
Assert.True(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask\\\\+NestedTask", "NestedTask")); // ==> partial match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.CscTask", "Csc")); // ==> no match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.MyCsc", "Csc")); // ==> no match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask\\.Csc", "Csc")); // ==> no match
Assert.False(TypeLoader.IsPartialTypeNameMatch("MyTasks.ATask\\\\\\.Csc", "Csc")); // ==> no match
}
[Fact]
public void Regress_Mutation_TrailingPartMustMatch()
{
Assert.False(TypeLoader.IsPartialTypeNameMatch("Microsoft.Build.Tasks.Csc", "Vbc"));
}
[Fact]
public void Regress_Mutation_ParameterOrderDoesntMatter()
{
Assert.True(TypeLoader.IsPartialTypeNameMatch("Csc", "Microsoft.Build.Tasks.Csc"));
}
[Fact]
public void LoadNonExistingAssembly()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
string dllName = "NonExistent.dll";
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + dllName, out successfulExit);
Assert.False(successfulExit);
string dllPath = Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, dllName);
CheckIfCorrectAssemblyLoaded(output, dllPath, false);
}
}
[Fact]
public void LoadInsideAsssembly()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag", out successfulExit);
Assert.True(successfulExit);
string dllPath = Path.Combine(dir.Path, DLLFileName);
CheckIfCorrectAssemblyLoaded(output, dllPath);
}
}
[Fact]
public void LoadOutsideAssembly()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
string originalDLLPath = Path.Combine(dir.Path, DLLFileName);
string movedDLLPath = MoveOrCopyDllToTempDir(originalDLLPath, copy: false);
try
{
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + movedDLLPath, out successfulExit);
Assert.True(successfulExit);
CheckIfCorrectAssemblyLoaded(output, movedDLLPath);
}
finally
{
UndoDLLOperations(movedDLLPath);
}
}
}
[Fact (Skip = "https://github.com/Microsoft/msbuild/issues/325")]
public void LoadInsideAssemblyWhenGivenOutsideAssemblyWithSameName()
{
using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
{
string projectFilePath = Path.Combine(dir.Path, ProjectFileName);
string originalDLLPath = Path.Combine(dir.Path, DLLFileName);
string copiedDllPath = MoveOrCopyDllToTempDir(originalDLLPath, copy: true);
try
{
bool successfulExit;
string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + copiedDllPath, out successfulExit);
Assert.True(successfulExit);
CheckIfCorrectAssemblyLoaded(output, originalDLLPath);
}
finally
{
UndoDLLOperations(copiedDllPath);
}
}
}
/// <summary>
/// </summary>
/// <param name="copy"></param>
/// <returns>Path to new DLL</returns>
private string MoveOrCopyDllToTempDir(string originalDllPath, bool copy)
{
var temporaryDirectory = FileUtilities.GetTemporaryDirectory();
var newDllPath = Path.Combine(temporaryDirectory, DLLFileName);
Assert.True(File.Exists(originalDllPath));
if (copy)
{
File.Copy(originalDllPath, newDllPath);
Assert.True(File.Exists(newDllPath));
}
else
{
File.Move(originalDllPath, newDllPath);
Assert.True(File.Exists(newDllPath));
Assert.False(File.Exists(originalDllPath));
}
return newDllPath;
}
/// <summary>
/// Delete newDllPath and delete temp directory
/// </summary>
/// <param name="newDllPath"></param>
/// <param name="moveBack">If true, move newDllPath back to bin. If false, delete it</param>
private void UndoDLLOperations(string newDllPath)
{
var tempDirectoryPath = Path.GetDirectoryName(newDllPath);
File.Delete(newDllPath);
Assert.False(File.Exists(newDllPath));
Assert.Empty(Directory.EnumerateFiles(tempDirectoryPath));
Directory.Delete(tempDirectoryPath);
Assert.False(Directory.Exists(tempDirectoryPath));
}
private void CheckIfCorrectAssemblyLoaded(string scriptOutput, string expectedAssemblyPath, bool expectedSuccess = true)
{
var successfulMessage = @"Using ""ShowItems"" task from assembly """ + expectedAssemblyPath + @""".";
if (expectedSuccess)
{
Assert.Contains(successfulMessage, scriptOutput, StringComparison.OrdinalIgnoreCase);
}
else
{
Assert.DoesNotContain(successfulMessage, scriptOutput, StringComparison.OrdinalIgnoreCase);
}
}
#if FEATURE_ASSEMBLY_LOCATION
/// <summary>
/// Make sure that when we load multiple types out of the same assembly with different type filters that both the fullyqualified name matching and the
/// partial name matching still work.
/// </summary>
[Fact]
public void Regress640476PartialName()
{
string forwardingLoggerLocation = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger).Assembly.Location;
TypeLoader loader = new TypeLoader(IsForwardingLoggerClass);
LoadedType loadedType = loader.Load("ConfigurableForwardingLogger", AssemblyLoadInfo.Create(null, forwardingLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation);
string fileLoggerLocation = typeof(Microsoft.Build.Logging.FileLogger).Assembly.Location;
loader = new TypeLoader(IsLoggerClass);
loadedType = loader.Load("FileLogger", AssemblyLoadInfo.Create(null, fileLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation);
}
/// <summary>
/// Make sure that when we load multiple types out of the same assembly with different type filters that both the fullyqualified name matching and the
/// partial name matching still work.
/// </summary>
[Fact]
public void Regress640476FullyQualifiedName()
{
Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger);
string forwardingLoggerLocation = forwardingLoggerType.Assembly.Location;
TypeLoader loader = new TypeLoader(IsForwardingLoggerClass);
LoadedType loadedType = loader.Load(forwardingLoggerType.FullName, AssemblyLoadInfo.Create(null, forwardingLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(forwardingLoggerLocation, loadedType.Assembly.AssemblyLocation);
Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger);
string fileLoggerLocation = fileLoggerType.Assembly.Location;
loader = new TypeLoader(IsLoggerClass);
loadedType = loader.Load(fileLoggerType.FullName, AssemblyLoadInfo.Create(null, fileLoggerLocation));
Assert.NotNull(loadedType);
Assert.Equal(fileLoggerLocation, loadedType.Assembly.AssemblyLocation);
}
/// <summary>
/// Make sure if no typeName is passed in then pick the first type which matches the desired type filter.
/// This has been in since whidbey but there has been no test for it and it was broken in the last refactoring of TypeLoader.
/// This test is to prevent that from happening again.
/// </summary>
[Fact]
public void NoTypeNamePicksFirstType()
{
Type forwardingLoggerType = typeof(Microsoft.Build.Logging.ConfigurableForwardingLogger);
string forwardingLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location;
Func<Type, object, bool> forwardingLoggerfilter = IsForwardingLoggerClass;
Type firstPublicType = FirstPublicDesiredType(forwardingLoggerfilter, forwardingLoggerAssemblyLocation);
TypeLoader loader = new TypeLoader(forwardingLoggerfilter);
LoadedType loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, forwardingLoggerAssemblyLocation));
Assert.NotNull(loadedType);
Assert.Equal(forwardingLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation);
Assert.Equal(firstPublicType, loadedType.Type);
Type fileLoggerType = typeof(Microsoft.Build.Logging.FileLogger);
string fileLoggerAssemblyLocation = forwardingLoggerType.Assembly.Location;
Func<Type, object, bool> fileLoggerfilter = IsLoggerClass;
firstPublicType = FirstPublicDesiredType(fileLoggerfilter, fileLoggerAssemblyLocation);
loader = new TypeLoader(fileLoggerfilter);
loadedType = loader.Load(String.Empty, AssemblyLoadInfo.Create(null, fileLoggerAssemblyLocation));
Assert.NotNull(loadedType);
Assert.Equal(fileLoggerAssemblyLocation, loadedType.Assembly.AssemblyLocation);
Assert.Equal(firstPublicType, loadedType.Type);
}
private static Type FirstPublicDesiredType(Func<Type, object, bool> filter, string assemblyLocation)
{
Assembly loadedAssembly = Assembly.UnsafeLoadFrom(assemblyLocation);
// only look at public types
Type[] allPublicTypesInAssembly = loadedAssembly.GetExportedTypes();
foreach (Type publicType in allPublicTypesInAssembly)
{
if (filter(publicType, null))
{
return publicType;
}
}
return null;
}
private static bool IsLoggerClass(Type type, object unused)
{
return type.IsClass &&
!type.IsAbstract &&
(type.GetInterface("ILogger") != null);
}
private static bool IsForwardingLoggerClass(Type type, object unused)
{
return type.IsClass &&
!type.IsAbstract &&
(type.GetInterface("IForwardingLogger") != null);
}
#endif
}
}
| |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
using Xunit;
using Microsoft.Rest.Azure.OData;
namespace ResourceGroups.Tests
{
public class InMemoryResourceLinkTests
{
public ManagementLinkClient GetManagementLinkClient(RecordedDelegatingHandler handler)
{
var subscriptionId = Guid.NewGuid().ToString();
var token = new TokenCredentials(subscriptionId, "abc123");
handler.IsPassThrough = false;
var client = new ManagementLinkClient(token, handler);
client.SubscriptionId = subscriptionId;
return client;
}
[Fact]
public void ResourceLinkCRUD()
{
var response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.Created };
var client = GetManagementLinkClient(handler);
var result = client.ResourceLinks.CreateOrUpdate(
linkId: "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink",
parameters: new ResourceLink
{
Properties = new ResourceLinkProperties
{
TargetId = "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2",
Notes = "myLinkNotes"
}
});
JObject json = JObject.Parse(handler.Request);
// Validate headers
Assert.Equal("application/json; charset=utf-8", handler.ContentHeaders.GetValues("Content-Type").First());
Assert.Equal(HttpMethod.Put, handler.Method);
Assert.NotNull(handler.RequestHeaders.GetValues("Authorization"));
// Validate payload
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", json["properties"]["targetId"].Value<string>());
Assert.Equal("myLinkNotes", json["properties"]["notes"].Value<string>());
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.Properties.TargetId);
Assert.Equal("myLinkNotes", result.Properties.Notes);
Assert.Equal("myLink", result.Name);
//Get resource link and validate properties
var getResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}")
};
var getHandler = new RecordedDelegatingHandler(getResponse) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetManagementLinkClient(getHandler);
var getResult = client.ResourceLinks.Get("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink");
// Validate response
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", getResult.Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", getResult.Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", getResult.Properties.TargetId);
Assert.Equal("myLinkNotes", getResult.Properties.Notes);
Assert.Equal("myLink", getResult.Name);
//Delete resource link
var deleteResponse = new HttpResponseMessage(HttpStatusCode.OK);
deleteResponse.Headers.Add("x-ms-request-id", "1");
var deleteHandler = new RecordedDelegatingHandler(deleteResponse) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetManagementLinkClient(deleteHandler);
client.ResourceLinks.Delete("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink");
// Validate headers
Assert.Equal(HttpMethod.Delete, deleteHandler.Method);
// Get a deleted link throws exception
Assert.Throws<CloudException>(() => client.ResourceLinks.Get("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink"));
}
[Fact]
public void ResourceLinkList()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
},
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount/providers/Microsoft.Resources/links/myLink2',
'name': 'myLink2',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Storage/storageAccounts/myAccount2',
'notes': 'myLinkNotes2'
}
}],
'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetManagementLinkClient(handler);
var result = client.ResourceLinks.ListAtSubscription();
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
// Validate result
Assert.Equal(2, result.Count());
Assert.Equal("myLink", result.First().Name);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.First().Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.First().Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.First().Properties.TargetId);
Assert.Equal("myLinkNotes", result.First().Properties.Notes);
Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
// Filter by targetId
var filteredResponse = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}],
'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
}")
};
var filteredHandler = new RecordedDelegatingHandler(filteredResponse) { StatusCodeToReturn = HttpStatusCode.OK };
client = GetManagementLinkClient(filteredHandler);
var filteredResult = client.ResourceLinks.ListAtSubscription(new ODataQuery<ResourceLinkFilter>(f => f.TargetId == "/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2"));
// Validate result
Assert.Equal(1, filteredResult.Count());
Assert.Equal("myLink", filteredResult.First().Name);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", filteredResult.First().Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", filteredResult.First().Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", filteredResult.First().Properties.TargetId);
Assert.Equal("myLinkNotes", filteredResult.First().Properties.Notes);
Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", filteredResult.NextPageLink);
}
[Fact]
public void ResourceLinkListAtSourceScope()
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(@"{
'value': [
{
'id': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink',
'name': 'myLink',
'properties': {
'sourceId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm',
'targetId': '/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2',
'notes': 'myLinkNotes'
}
}],
'nextLink': 'https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk',
}")
};
var handler = new RecordedDelegatingHandler(response) { StatusCodeToReturn = HttpStatusCode.OK };
var client = GetManagementLinkClient(handler);
var result = client.ResourceLinks.ListAtSourceScope("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm");
// Validate headers
Assert.Equal(HttpMethod.Get, handler.Method);
// Validate result
Assert.Equal(1, result.Count());
Assert.Equal("myLink", result.First().Name);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm/providers/Microsoft.Resources/links/myLink", result.First().Id);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm", result.First().Properties.SourceId);
Assert.Equal("/subscriptions/abc123/resourcegroups/myGroup/providers/Microsoft.Web/serverFarms/myFarm2", result.First().Properties.TargetId);
Assert.Equal("myLinkNotes", result.First().Properties.Notes);
Assert.Equal("https://wa/subscriptions/subId/links?api-version=1.0&$skiptoken=662idk", result.NextPageLink);
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using SquabPie.Mono.Cecil.Cil;
using SquabPie.Mono.Collections.Generic;
using RVA = System.UInt32;
namespace SquabPie.Mono.Cecil {
public sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider {
ushort attributes;
ushort impl_attributes;
internal volatile bool sem_attrs_ready;
internal MethodSemanticsAttributes sem_attrs;
Collection<CustomAttribute> custom_attributes;
Collection<SecurityDeclaration> security_declarations;
internal RVA rva;
internal PInvokeInfo pinvoke;
Collection<MethodReference> overrides;
internal MethodBody body;
public MethodAttributes Attributes {
get { return (MethodAttributes) attributes; }
set { attributes = (ushort) value; }
}
public MethodImplAttributes ImplAttributes {
get { return (MethodImplAttributes) impl_attributes; }
set { impl_attributes = (ushort) value; }
}
public MethodSemanticsAttributes SemanticsAttributes {
get {
if (sem_attrs_ready)
return sem_attrs;
if (HasImage) {
ReadSemantics ();
return sem_attrs;
}
sem_attrs = MethodSemanticsAttributes.None;
sem_attrs_ready = true;
return sem_attrs;
}
set { sem_attrs = value; }
}
internal void ReadSemantics ()
{
if (sem_attrs_ready)
return;
var module = this.Module;
if (module == null)
return;
if (!module.HasImage)
return;
module.Read (this, (method, reader) => reader.ReadAllSemantics (method));
}
public bool HasSecurityDeclarations {
get {
if (security_declarations != null)
return security_declarations.Count > 0;
return this.GetHasSecurityDeclarations (Module);
}
}
public Collection<SecurityDeclaration> SecurityDeclarations {
get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); }
}
public bool HasCustomAttributes {
get {
if (custom_attributes != null)
return custom_attributes.Count > 0;
return this.GetHasCustomAttributes (Module);
}
}
public Collection<CustomAttribute> CustomAttributes {
get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); }
}
public int RVA {
get { return (int) rva; }
}
public bool HasBody {
get {
return (attributes & (ushort) MethodAttributes.Abstract) == 0 &&
(attributes & (ushort) MethodAttributes.PInvokeImpl) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.InternalCall) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.Native) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.Unmanaged) == 0 &&
(impl_attributes & (ushort) MethodImplAttributes.Runtime) == 0;
}
}
public MethodBody Body {
get {
MethodBody localBody = this.body;
if (localBody != null)
return localBody;
if (!HasBody)
return null;
if (HasImage && rva != 0)
return Module.Read (ref body, this, (method, reader) => reader.ReadMethodBody (method));
return body = new MethodBody (this);
}
set {
var module = this.Module;
if (module == null) {
body = value;
return;
}
// we reset Body to null in ILSpy to save memory; so we need that operation to be thread-safe
lock (module.SyncRoot) {
body = value;
}
}
}
public bool HasPInvokeInfo {
get {
if (pinvoke != null)
return true;
return IsPInvokeImpl;
}
}
public PInvokeInfo PInvokeInfo {
get {
if (pinvoke != null)
return pinvoke;
if (HasImage && IsPInvokeImpl)
return Module.Read (ref pinvoke, this, (method, reader) => reader.ReadPInvokeInfo (method));
return null;
}
set {
IsPInvokeImpl = true;
pinvoke = value;
}
}
public bool HasOverrides {
get {
if (overrides != null)
return overrides.Count > 0;
return HasImage && Module.Read (this, (method, reader) => reader.HasOverrides (method));
}
}
public Collection<MethodReference> Overrides {
get {
if (overrides != null)
return overrides;
if (HasImage)
return Module.Read (ref overrides, this, (method, reader) => reader.ReadOverrides (method));
return overrides = new Collection<MethodReference> ();
}
}
public override bool HasGenericParameters {
get {
if (generic_parameters != null)
return generic_parameters.Count > 0;
return this.GetHasGenericParameters (Module);
}
}
public override Collection<GenericParameter> GenericParameters {
get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); }
}
#region MethodAttributes
public bool IsCompilerControlled {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled, value); }
}
public bool IsPrivate {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private, value); }
}
public bool IsFamilyAndAssembly {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem, value); }
}
public bool IsAssembly {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly, value); }
}
public bool IsFamily {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family, value); }
}
public bool IsFamilyOrAssembly {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem, value); }
}
public bool IsPublic {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public, value); }
}
public bool IsStatic {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Static); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Static, value); }
}
public bool IsFinal {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Final); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Final, value); }
}
public bool IsVirtual {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Virtual); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Virtual, value); }
}
public bool IsHideBySig {
get { return attributes.GetAttributes ((ushort) MethodAttributes.HideBySig); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HideBySig, value); }
}
public bool IsReuseSlot {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot, value); }
}
public bool IsNewSlot {
get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot); }
set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot, value); }
}
public bool IsCheckAccessOnOverride {
get { return attributes.GetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride, value); }
}
public bool IsAbstract {
get { return attributes.GetAttributes ((ushort) MethodAttributes.Abstract); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Abstract, value); }
}
public bool IsSpecialName {
get { return attributes.GetAttributes ((ushort) MethodAttributes.SpecialName); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.SpecialName, value); }
}
public bool IsPInvokeImpl {
get { return attributes.GetAttributes ((ushort) MethodAttributes.PInvokeImpl); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.PInvokeImpl, value); }
}
public bool IsUnmanagedExport {
get { return attributes.GetAttributes ((ushort) MethodAttributes.UnmanagedExport); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.UnmanagedExport, value); }
}
public bool IsRuntimeSpecialName {
get { return attributes.GetAttributes ((ushort) MethodAttributes.RTSpecialName); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.RTSpecialName, value); }
}
public bool HasSecurity {
get { return attributes.GetAttributes ((ushort) MethodAttributes.HasSecurity); }
set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HasSecurity, value); }
}
#endregion
#region MethodImplAttributes
public bool IsIL {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL, value); }
}
public bool IsNative {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native, value); }
}
public bool IsRuntime {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime, value); }
}
public bool IsUnmanaged {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged, value); }
}
public bool IsManaged {
get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed); }
set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed, value); }
}
public bool IsForwardRef {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.ForwardRef); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.ForwardRef, value); }
}
public bool IsPreserveSig {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.PreserveSig); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.PreserveSig, value); }
}
public bool IsInternalCall {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.InternalCall); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.InternalCall, value); }
}
public bool IsSynchronized {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.Synchronized); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.Synchronized, value); }
}
public bool NoInlining {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoInlining); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoInlining, value); }
}
public bool NoOptimization {
get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoOptimization); }
set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoOptimization, value); }
}
#endregion
#region MethodSemanticsAttributes
public bool IsSetter {
get { return this.GetSemantics (MethodSemanticsAttributes.Setter); }
set { this.SetSemantics (MethodSemanticsAttributes.Setter, value); }
}
public bool IsGetter {
get { return this.GetSemantics (MethodSemanticsAttributes.Getter); }
set { this.SetSemantics (MethodSemanticsAttributes.Getter, value); }
}
public bool IsOther {
get { return this.GetSemantics (MethodSemanticsAttributes.Other); }
set { this.SetSemantics (MethodSemanticsAttributes.Other, value); }
}
public bool IsAddOn {
get { return this.GetSemantics (MethodSemanticsAttributes.AddOn); }
set { this.SetSemantics (MethodSemanticsAttributes.AddOn, value); }
}
public bool IsRemoveOn {
get { return this.GetSemantics (MethodSemanticsAttributes.RemoveOn); }
set { this.SetSemantics (MethodSemanticsAttributes.RemoveOn, value); }
}
public bool IsFire {
get { return this.GetSemantics (MethodSemanticsAttributes.Fire); }
set { this.SetSemantics (MethodSemanticsAttributes.Fire, value); }
}
#endregion
public new TypeDefinition DeclaringType {
get { return (TypeDefinition) base.DeclaringType; }
set { base.DeclaringType = value; }
}
public bool IsConstructor {
get {
return this.IsRuntimeSpecialName
&& this.IsSpecialName
&& (this.Name == ".cctor" || this.Name == ".ctor");
}
}
public override bool IsDefinition {
get { return true; }
}
internal MethodDefinition ()
{
this.token = new MetadataToken (TokenType.Method);
}
public MethodDefinition (string name, MethodAttributes attributes, TypeReference returnType)
: base (name, returnType)
{
this.attributes = (ushort) attributes;
this.HasThis = !this.IsStatic;
this.token = new MetadataToken (TokenType.Method);
}
public override MethodDefinition Resolve ()
{
return this;
}
}
static partial class Mixin {
public static ParameterDefinition GetParameter (this MethodBody self, int index)
{
var method = self.method;
if (method.HasThis) {
if (index == 0)
return self.ThisParameter;
index--;
}
var parameters = method.Parameters;
if (index < 0 || index >= parameters.size)
return null;
return parameters [index];
}
public static VariableDefinition GetVariable (this MethodBody self, int index)
{
var variables = self.Variables;
if (index < 0 || index >= variables.size)
return null;
return variables [index];
}
public static bool GetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics)
{
return (self.SemanticsAttributes & semantics) != 0;
}
public static void SetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics, bool value)
{
if (value)
self.SemanticsAttributes |= semantics;
else
self.SemanticsAttributes &= ~semantics;
}
}
}
| |
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 CodeFighter.Service.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 (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using UnityEngine.EventSystems;
using System.Collections.Generic;
using HoloToolkit.Unity.InputModule;
namespace HoloToolkit.Unity.Receivers
{
/// <summary>
/// An interaction receiver is simply a component that attached to a list of interactable objects and does something
/// based on events from those interactable objects. This is the base abstract class to extend from.
/// </summary>
public abstract class InteractionReceiver : MonoBehaviour, IInputHandler, IHoldHandler, IInputClickHandler, IManipulationHandler
{
#region Public Members
/// <summary>
/// List of linked interactable objects to receive events for
/// </summary>
[Tooltip("Target interactable Object to receive events for")]
public List<GameObject> interactables = new List<GameObject>();
/// <summary>
/// List of linked targets that the receiver affects
/// </summary>
[Tooltip("Targets for the receiver to ")]
public List<GameObject> Targets = new List<GameObject>();
/// <summary>
/// Flag for locking focus while selected
/// </summary>
public bool LockFocus
{
get
{
return lockFocus;
}
set
{
lockFocus = value;
CheckLockFocus(_selectingFocuser);
}
}
#endregion
#region Private and Protected Members
[Tooltip("If true, this object will remain the prime focus while select is held")]
[SerializeField]
private bool lockFocus = false;
/// <summary>
/// Protected focuser for the current selecting focuser
/// </summary>
protected IPointingSource _selectingFocuser;
#endregion
/// <summary>
/// On start subscribe to all interaction events on elements in the interactables list.
/// </summary>
public virtual void OnEnable()
{
InputManager.Instance.AddGlobalListener(gameObject);
FocusManager.Instance.PointerSpecificFocusChanged += OnPointerSpecificFocusChanged;
}
/// <summary>
/// On disable remove all linked interacibles from the delegate functions
/// </summary>
public virtual void OnDisable()
{
InputManager.Instance.RemoveGlobalListener(gameObject);
FocusManager.Instance.PointerSpecificFocusChanged += OnPointerSpecificFocusChanged;
}
/// <summary>
/// Register an interactable with this receiver.
/// </summary>
/// <param name="interactable">takes a GameObject as the interactable to register.</param>
public virtual void Registerinteractable(GameObject interactable)
{
if (interactable == null || interactables.Contains(interactable))
{
return;
}
interactables.Add(interactable);
}
#if UNITY_EDITOR
/// <summary>
/// When selected draw lines to all linked interactables
/// </summary>
protected virtual void OnDrawGizmosSelected()
{
if (this.interactables.Count > 0)
{
GameObject[] bioList = this.interactables.ToArray();
for (int i = 0; i < bioList.Length; i++)
{
if (bioList[i] != null)
{
Gizmos.color = Color.green;
Gizmos.DrawLine(this.transform.position, bioList[i].transform.position);
}
}
}
if (this.Targets.Count > 0)
{
GameObject[] targetList = this.Targets.ToArray();
for (int i = 0; i < targetList.Length; i++)
{
if (targetList[i] != null)
{
Gizmos.color = Color.red;
Gizmos.DrawLine(this.transform.position, targetList[i].transform.position);
}
}
}
}
#endif
/// <summary>
/// Function to remove an interactable from the linked list.
/// </summary>
/// <param name="interactable"></param>
public virtual void Removeinteractable(GameObject interactable)
{
if (interactable != null && interactables.Contains(interactable))
{
interactables.Remove(interactable);
}
}
/// <summary>
/// Clear the interactables list and unregister them
/// </summary>
public virtual void Clearinteractables()
{
GameObject[] _intList = interactables.ToArray();
for (int i = 0; i < _intList.Length; i++)
{
this.Removeinteractable(_intList[i]);
}
}
/// <summary>
/// Is the game object interactable in our list of interactables
/// </summary>
/// <param name="interactable"></param>
/// <returns></returns>
protected bool Isinteractable(GameObject interactable)
{
return (interactables != null && interactables.Contains(interactable));
}
private void CheckLockFocus(IPointingSource focuser)
{
// If our previous selecting focuser isn't the same
if (_selectingFocuser != null && _selectingFocuser != focuser)
{
// If our focus is currently locked, unlock it before moving on
if (LockFocus)
{
_selectingFocuser.FocusLocked = false;
}
}
// Set to the new focuser
_selectingFocuser = focuser;
if (_selectingFocuser != null)
{
_selectingFocuser.FocusLocked = LockFocus;
}
}
private void LockFocuser(IPointingSource focuser)
{
if (focuser != null)
{
ReleaseFocuser();
_selectingFocuser = focuser;
_selectingFocuser.FocusLocked = true;
}
}
private void ReleaseFocuser()
{
if (_selectingFocuser != null)
{
_selectingFocuser.FocusLocked = false;
_selectingFocuser = null;
}
}
/// <summary>
/// Handle the pointer specific changes to fire focus enter and exit events
/// </summary>
/// <param name="pointer">The pointer associated with this focus change.</param>
/// <param name="oldFocusedObject">Object that was previously being focused.</param>
/// <param name="newFocusedObject">New object being focused.</param>
private void OnPointerSpecificFocusChanged(IPointingSource pointer, GameObject oldFocusedObject, GameObject newFocusedObject)
{
PointerSpecificEventData eventData = new PointerSpecificEventData(EventSystem.current);
eventData.Initialize(pointer);
if (newFocusedObject != null && Isinteractable(newFocusedObject))
{
FocusEnter(newFocusedObject, eventData);
}
if (oldFocusedObject != null && Isinteractable(oldFocusedObject))
{
FocusExit(oldFocusedObject, eventData);
}
CheckLockFocus(pointer);
}
#region Global Listener Callbacks
public void OnInputDown(InputEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
InputDown(eventData.selectedObject, eventData);
}
}
public void OnInputUp(InputEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
InputUp(eventData.selectedObject, eventData);
}
}
public void OnInputClicked(InputClickedEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
InputClicked(eventData.selectedObject, eventData);
}
}
public void OnHoldStarted(HoldEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
HoldStarted(eventData.selectedObject, eventData);
}
}
public void OnHoldCompleted(HoldEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
HoldCompleted(eventData.selectedObject, eventData);
}
}
public void OnHoldCanceled(HoldEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
HoldCanceled(eventData.selectedObject, eventData);
}
}
public void OnManipulationStarted(ManipulationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
ManipulationStarted(eventData.selectedObject, eventData);
}
}
public void OnManipulationUpdated(ManipulationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
ManipulationUpdated(eventData.selectedObject, eventData);
}
}
public void OnManipulationCompleted(ManipulationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
ManipulationCompleted(eventData.selectedObject, eventData);
}
}
public void OnManipulationCanceled(ManipulationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
ManipulationCanceled(eventData.selectedObject, eventData);
}
}
public void OnNavigationStarted(NavigationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
NavigationStarted(eventData.selectedObject, eventData);
}
}
public void OnNavigationUpdated(NavigationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
NavigationUpdated(eventData.selectedObject, eventData);
}
}
public void OnNavigationCompleted(NavigationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
NavigationCompleted(eventData.selectedObject, eventData);
}
}
public void OnNavigationCanceled(NavigationEventData eventData)
{
if (Isinteractable(eventData.selectedObject))
{
NavigationCanceled(eventData.selectedObject, eventData);
}
}
#endregion
#region Protected Virtual Callback Functions
protected virtual void FocusEnter(GameObject obj, PointerSpecificEventData eventData) { }
protected virtual void FocusExit(GameObject obj, PointerSpecificEventData eventData) { }
protected virtual void InputDown(GameObject obj, InputEventData eventData) { }
protected virtual void InputUp(GameObject obj, InputEventData eventData) { }
protected virtual void InputClicked(GameObject obj, InputClickedEventData eventData) { }
protected virtual void HoldStarted(GameObject obj, HoldEventData eventData) { }
protected virtual void HoldCompleted(GameObject obj, HoldEventData eventData) { }
protected virtual void HoldCanceled(GameObject obj, HoldEventData eventData) { }
protected virtual void ManipulationStarted(GameObject obj, ManipulationEventData eventData) { }
protected virtual void ManipulationUpdated(GameObject obj, ManipulationEventData eventData) { }
protected virtual void ManipulationCompleted(GameObject obj, ManipulationEventData eventData) { }
protected virtual void ManipulationCanceled(GameObject obj, ManipulationEventData eventData) { }
protected virtual void NavigationStarted(GameObject obj, NavigationEventData eventData) { }
protected virtual void NavigationUpdated(GameObject obj, NavigationEventData eventData) { }
protected virtual void NavigationCompleted(GameObject obj, NavigationEventData eventData) { }
protected virtual void NavigationCanceled(GameObject obj, NavigationEventData eventData) { }
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using System.Collections.Specialized;
// The data model defined by this file serves as a representative example of a strongly-typed
// model that supports notification when members are added, removed, or modified. The property
// names chosen coincide with data bindings in the standard item templates.
//
// Applications may use this model as a starting point and build on it, or discard it entirely and
// replace it with something appropriate to their needs.
namespace ParsePushSample.Data
{
/// <summary>
/// Base class for <see cref="SampleDataItem"/> and <see cref="SampleDataGroup"/> that
/// defines properties common to both.
/// </summary>
[Windows.Foundation.Metadata.WebHostHidden]
public abstract class SampleDataCommon : ParsePushSample.Common.BindableBase
{
private static Uri _baseUri = new Uri("ms-appx:///");
public SampleDataCommon(String uniqueId, String title, String subtitle, String imagePath, String description)
{
this._uniqueId = uniqueId;
this._title = title;
this._subtitle = subtitle;
this._description = description;
this._imagePath = imagePath;
}
private string _uniqueId = string.Empty;
public string UniqueId
{
get { return this._uniqueId; }
set { this.SetProperty(ref this._uniqueId, value); }
}
private string _title = string.Empty;
public string Title
{
get { return this._title; }
set { this.SetProperty(ref this._title, value); }
}
private string _subtitle = string.Empty;
public string Subtitle
{
get { return this._subtitle; }
set { this.SetProperty(ref this._subtitle, value); }
}
private string _description = string.Empty;
public string Description
{
get { return this._description; }
set { this.SetProperty(ref this._description, value); }
}
private ImageSource _image = null;
private String _imagePath = null;
public ImageSource Image
{
get
{
if (this._image == null && this._imagePath != null)
{
this._image = new BitmapImage(new Uri(SampleDataCommon._baseUri, this._imagePath));
}
return this._image;
}
set
{
this._imagePath = null;
this.SetProperty(ref this._image, value);
}
}
public void SetImage(String path)
{
this._image = null;
this._imagePath = path;
this.OnPropertyChanged("Image");
}
public override string ToString()
{
return this.Title;
}
}
/// <summary>
/// Generic item data model.
/// </summary>
public class SampleDataItem : SampleDataCommon
{
public SampleDataItem(String uniqueId, String title, String subtitle, String imagePath, String description, String content, SampleDataGroup group)
: base(uniqueId, title, subtitle, imagePath, description)
{
this._content = content;
this._group = group;
}
private string _content = string.Empty;
public string Content
{
get { return this._content; }
set { this.SetProperty(ref this._content, value); }
}
private SampleDataGroup _group;
public SampleDataGroup Group
{
get { return this._group; }
set { this.SetProperty(ref this._group, value); }
}
}
/// <summary>
/// Generic group data model.
/// </summary>
public class SampleDataGroup : SampleDataCommon
{
public SampleDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description)
: base(uniqueId, title, subtitle, imagePath, description)
{
Items.CollectionChanged += ItemsCollectionChanged;
}
private void ItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Provides a subset of the full items collection to bind to from a GroupedItemsPage
// for two reasons: GridView will not virtualize large items collections, and it
// improves the user experience when browsing through groups with large numbers of
// items.
//
// A maximum of 12 items are displayed because it results in filled grid columns
// whether there are 1, 2, 3, 4, or 6 rows displayed
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
if (e.NewStartingIndex < 12)
{
TopItems.Insert(e.NewStartingIndex,Items[e.NewStartingIndex]);
if (TopItems.Count > 12)
{
TopItems.RemoveAt(12);
}
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldStartingIndex < 12 && e.NewStartingIndex < 12)
{
TopItems.Move(e.OldStartingIndex, e.NewStartingIndex);
}
else if (e.OldStartingIndex < 12)
{
TopItems.RemoveAt(e.OldStartingIndex);
TopItems.Add(Items[11]);
}
else if (e.NewStartingIndex < 12)
{
TopItems.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]);
TopItems.RemoveAt(12);
}
break;
case NotifyCollectionChangedAction.Remove:
if (e.OldStartingIndex < 12)
{
TopItems.RemoveAt(e.OldStartingIndex);
if (Items.Count >= 12)
{
TopItems.Add(Items[11]);
}
}
break;
case NotifyCollectionChangedAction.Replace:
if (e.OldStartingIndex < 12)
{
TopItems[e.OldStartingIndex] = Items[e.OldStartingIndex];
}
break;
case NotifyCollectionChangedAction.Reset:
TopItems.Clear();
while (TopItems.Count < Items.Count && TopItems.Count < 12)
{
TopItems.Add(Items[TopItems.Count]);
}
break;
}
}
private ObservableCollection<SampleDataItem> _items = new ObservableCollection<SampleDataItem>();
public ObservableCollection<SampleDataItem> Items
{
get { return this._items; }
}
private ObservableCollection<SampleDataItem> _topItem = new ObservableCollection<SampleDataItem>();
public ObservableCollection<SampleDataItem> TopItems
{
get {return this._topItem; }
}
}
/// <summary>
/// Creates a collection of groups and items with hard-coded content.
///
/// SampleDataSource initializes with placeholder data rather than live production
/// data so that sample data is provided at both design-time and run-time.
/// </summary>
public sealed class SampleDataSource
{
private static SampleDataSource _sampleDataSource = new SampleDataSource();
private ObservableCollection<SampleDataGroup> _allGroups = new ObservableCollection<SampleDataGroup>();
public ObservableCollection<SampleDataGroup> AllGroups
{
get { return this._allGroups; }
}
public static IEnumerable<SampleDataGroup> GetGroups(string uniqueId)
{
if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");
return _sampleDataSource.AllGroups;
}
public static SampleDataGroup GetGroup(string uniqueId)
{
// Simple linear search is acceptable for small data sets
var matches = _sampleDataSource.AllGroups.Where((group) => group.UniqueId.Equals(uniqueId));
if (matches.Count() == 1) return matches.First();
return null;
}
public static SampleDataItem GetItem(string uniqueId)
{
// Simple linear search is acceptable for small data sets
var matches = _sampleDataSource.AllGroups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
if (matches.Count() == 1) return matches.First();
return null;
}
public SampleDataSource()
{
String ITEM_CONTENT = String.Format("Item Content: {0}\n\n{0}\n\n{0}\n\n{0}\n\n{0}\n\n{0}\n\n{0}",
"Curabitur class aliquam vestibulum nam curae maecenas sed integer cras phasellus suspendisse quisque donec dis praesent accumsan bibendum pellentesque condimentum adipiscing etiam consequat vivamus dictumst aliquam duis convallis scelerisque est parturient ullamcorper aliquet fusce suspendisse nunc hac eleifend amet blandit facilisi condimentum commodo scelerisque faucibus aenean ullamcorper ante mauris dignissim consectetuer nullam lorem vestibulum habitant conubia elementum pellentesque morbi facilisis arcu sollicitudin diam cubilia aptent vestibulum auctor eget dapibus pellentesque inceptos leo egestas interdum nulla consectetuer suspendisse adipiscing pellentesque proin lobortis sollicitudin augue elit mus congue fermentum parturient fringilla euismod feugiat");
var group1 = new SampleDataGroup("Group-1",
"Group Title: 1",
"Group Subtitle: 1",
"Assets/DarkGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group1.Items.Add(new SampleDataItem("Group-1-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group1));
this.AllGroups.Add(group1);
var group2 = new SampleDataGroup("Group-2",
"Group Title: 2",
"Group Subtitle: 2",
"Assets/LightGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group2.Items.Add(new SampleDataItem("Group-2-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-2-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-2-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group2));
this.AllGroups.Add(group2);
var group3 = new SampleDataGroup("Group-3",
"Group Title: 3",
"Group Subtitle: 3",
"Assets/MediumGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group3.Items.Add(new SampleDataItem("Group-3-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-6",
"Item Title: 6",
"Item Subtitle: 6",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-7",
"Item Title: 7",
"Item Subtitle: 7",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
this.AllGroups.Add(group3);
var group4 = new SampleDataGroup("Group-4",
"Group Title: 4",
"Group Subtitle: 4",
"Assets/LightGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group4.Items.Add(new SampleDataItem("Group-4-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-6",
"Item Title: 6",
"Item Subtitle: 6",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
this.AllGroups.Add(group4);
var group5 = new SampleDataGroup("Group-5",
"Group Title: 5",
"Group Subtitle: 5",
"Assets/MediumGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group5.Items.Add(new SampleDataItem("Group-5-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
group5.Items.Add(new SampleDataItem("Group-5-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
group5.Items.Add(new SampleDataItem("Group-5-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
group5.Items.Add(new SampleDataItem("Group-5-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
this.AllGroups.Add(group5);
var group6 = new SampleDataGroup("Group-6",
"Group Title: 6",
"Group Subtitle: 6",
"Assets/DarkGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group6.Items.Add(new SampleDataItem("Group-6-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-6",
"Item Title: 6",
"Item Subtitle: 6",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-7",
"Item Title: 7",
"Item Subtitle: 7",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-8",
"Item Title: 8",
"Item Subtitle: 8",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
this.AllGroups.Add(group6);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipelines;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using HtcSharp.HttpModule.Connections.Abstractions;
using HtcSharp.HttpModule.Connections.Abstractions.Features;
using HtcSharp.HttpModule.Core.Features;
using HtcSharp.HttpModule.Core.Internal;
using HtcSharp.HttpModule.Core.Middleware.Internal;
using HtcSharp.HttpModule.Http.Features;
using HtcSharp.HttpModule.Shared.CertificateGeneration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using TlsConnectionFeature = HtcSharp.HttpModule.Core.Internal.TlsConnectionFeature;
namespace HtcSharp.HttpModule.Core.Middleware {
// SourceTools-Start
// Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Middleware\HttpsConnectionMiddleware.cs
// Start-At-Remote-Line 25
// SourceTools-End
internal class HttpsConnectionMiddleware {
private readonly ConnectionDelegate _next;
private readonly HttpsConnectionAdapterOptions _options;
private readonly ILogger _logger;
private readonly X509Certificate2 _serverCertificate;
private readonly Func<ConnectionContext, string, X509Certificate2> _serverCertificateSelector;
public HttpsConnectionMiddleware(ConnectionDelegate next, HttpsConnectionAdapterOptions options)
: this(next, options, loggerFactory: NullLoggerFactory.Instance) {
}
public HttpsConnectionMiddleware(ConnectionDelegate next, HttpsConnectionAdapterOptions options, ILoggerFactory loggerFactory) {
if (options == null) {
throw new ArgumentNullException(nameof(options));
}
// This configuration will always fail per-request, preemptively fail it here. See HttpConnection.SelectProtocol().
if (options.HttpProtocols == HttpProtocols.Http2) {
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
throw new NotSupportedException(CoreStrings.HTTP2NoTlsOsx);
} else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && Environment.OSVersion.Version < new Version(6, 2)) {
throw new NotSupportedException(CoreStrings.HTTP2NoTlsWin7);
}
}
_next = next;
// capture the certificate now so it can't be switched after validation
_serverCertificate = options.ServerCertificate;
_serverCertificateSelector = options.ServerCertificateSelector;
if (_serverCertificate == null && _serverCertificateSelector == null) {
throw new ArgumentException(CoreStrings.ServerCertificateRequired, nameof(options));
}
// If a selector is provided then ignore the cert, it may be a default cert.
if (_serverCertificateSelector != null) {
// SslStream doesn't allow both.
_serverCertificate = null;
} else {
EnsureCertificateIsAllowedForServerAuth(_serverCertificate);
}
_options = options;
_logger = loggerFactory?.CreateLogger<HttpsConnectionMiddleware>();
}
public Task OnConnectionAsync(ConnectionContext context) {
return Task.Run(() => InnerOnConnectionAsync(context));
}
private async Task InnerOnConnectionAsync(ConnectionContext context) {
bool certificateRequired;
var feature = new Core.Internal.TlsConnectionFeature();
context.Features.Set<ITlsConnectionFeature>(feature);
context.Features.Set<ITlsHandshakeFeature>(feature);
var memoryPool = context.Features.Get<IMemoryPoolFeature>()?.MemoryPool;
var inputPipeOptions = new StreamPipeReaderOptions
(
pool: memoryPool,
bufferSize: memoryPool.GetMinimumSegmentSize(),
minimumReadSize: memoryPool.GetMinimumAllocSize(),
leaveOpen: true
);
var outputPipeOptions = new StreamPipeWriterOptions
(
pool: memoryPool,
leaveOpen: true
);
SslDuplexPipe sslDuplexPipe = null;
if (_options.ClientCertificateMode == ClientCertificateMode.NoCertificate) {
sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions);
certificateRequired = false;
} else {
sslDuplexPipe = new SslDuplexPipe(context.Transport, inputPipeOptions, outputPipeOptions, s => new SslStream(s,
leaveInnerStreamOpen: false,
userCertificateValidationCallback: (sender, certificate, chain, sslPolicyErrors) => {
if (certificate == null) {
return _options.ClientCertificateMode != ClientCertificateMode.RequireCertificate;
}
if (_options.ClientCertificateValidation == null) {
if (sslPolicyErrors != SslPolicyErrors.None) {
return false;
}
}
var certificate2 = ConvertToX509Certificate2(certificate);
if (certificate2 == null) {
return false;
}
if (_options.ClientCertificateValidation != null) {
if (!_options.ClientCertificateValidation(certificate2, chain, sslPolicyErrors)) {
return false;
}
}
return true;
}));
certificateRequired = true;
}
var sslStream = sslDuplexPipe.Stream;
using (var cancellationTokeSource = new CancellationTokenSource(_options.HandshakeTimeout))
using (cancellationTokeSource.Token.UnsafeRegister(state => ((ConnectionContext)state).Abort(), context)) {
try {
// Adapt to the SslStream signature
ServerCertificateSelectionCallback selector = null;
if (_serverCertificateSelector != null) {
selector = (sender, name) => {
context.Features.Set(sslStream);
var cert = _serverCertificateSelector(context, name);
if (cert != null) {
EnsureCertificateIsAllowedForServerAuth(cert);
}
return cert;
};
}
var sslOptions = new SslServerAuthenticationOptions {
ServerCertificate = _serverCertificate,
ServerCertificateSelectionCallback = selector,
ClientCertificateRequired = certificateRequired,
EnabledSslProtocols = _options.SslProtocols,
CertificateRevocationCheckMode = _options.CheckCertificateRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
ApplicationProtocols = new List<SslApplicationProtocol>()
};
// This is order sensitive
if ((_options.HttpProtocols & HttpProtocols.Http2) != 0) {
sslOptions.ApplicationProtocols.Add(SslApplicationProtocol.Http2);
// https://tools.ietf.org/html/rfc7540#section-9.2.1
sslOptions.AllowRenegotiation = false;
}
if ((_options.HttpProtocols & HttpProtocols.Http1) != 0) {
sslOptions.ApplicationProtocols.Add(SslApplicationProtocol.Http11);
}
_options.OnAuthenticate?.Invoke(context, sslOptions);
await sslStream.AuthenticateAsServerAsync(sslOptions, CancellationToken.None);
} catch (OperationCanceledException) {
_logger?.LogDebug(2, CoreStrings.AuthenticationTimedOut);
await sslStream.DisposeAsync();
return;
} catch (IOException ex) {
_logger?.LogDebug(1, ex, CoreStrings.AuthenticationFailed);
await sslStream.DisposeAsync();
return;
} catch (AuthenticationException ex) {
if (_serverCertificate == null ||
!CertificateManager.IsHttpsDevelopmentCertificate(_serverCertificate) ||
CertificateManager.CheckDeveloperCertificateKey(_serverCertificate)) {
_logger?.LogDebug(1, ex, CoreStrings.AuthenticationFailed);
} else {
_logger?.LogError(3, ex, CoreStrings.BadDeveloperCertificateState);
}
await sslStream.DisposeAsync();
return;
}
}
feature.ApplicationProtocol = sslStream.NegotiatedApplicationProtocol.Protocol;
context.Features.Set<ITlsApplicationProtocolFeature>(feature);
feature.ClientCertificate = ConvertToX509Certificate2(sslStream.RemoteCertificate);
feature.CipherAlgorithm = sslStream.CipherAlgorithm;
feature.CipherStrength = sslStream.CipherStrength;
feature.HashAlgorithm = sslStream.HashAlgorithm;
feature.HashStrength = sslStream.HashStrength;
feature.KeyExchangeAlgorithm = sslStream.KeyExchangeAlgorithm;
feature.KeyExchangeStrength = sslStream.KeyExchangeStrength;
feature.Protocol = sslStream.SslProtocol;
var originalTransport = context.Transport;
try {
context.Transport = sslDuplexPipe;
// Disposing the stream will dispose the sslDuplexPipe
await using (sslStream)
await using (sslDuplexPipe) {
await _next(context);
// Dispose the inner stream (SslDuplexPipe) before disposing the SslStream
// as the duplex pipe can hit an ODE as it still may be writing.
}
} finally {
// Restore the original so that it gets closed appropriately
context.Transport = originalTransport;
}
}
private static void EnsureCertificateIsAllowedForServerAuth(X509Certificate2 certificate) {
if (!CertificateLoader.IsCertificateAllowedForServerAuth(certificate)) {
throw new InvalidOperationException(CoreStrings.FormatInvalidServerCertificateEku(certificate.Thumbprint));
}
}
private static X509Certificate2 ConvertToX509Certificate2(X509Certificate certificate) {
if (certificate == null) {
return null;
}
if (certificate is X509Certificate2 cert2) {
return cert2;
}
return new X509Certificate2(certificate);
}
private class SslDuplexPipe : DuplexPipeStreamAdapter<SslStream> {
public SslDuplexPipe(IDuplexPipe transport, StreamPipeReaderOptions readerOptions, StreamPipeWriterOptions writerOptions)
: this(transport, readerOptions, writerOptions, s => new SslStream(s)) {
}
public SslDuplexPipe(IDuplexPipe transport, StreamPipeReaderOptions readerOptions, StreamPipeWriterOptions writerOptions, Func<Stream, SslStream> factory) :
base(transport, readerOptions, writerOptions, factory) {
}
}
}
}
| |
#region License
//
// Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com>
//
// 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.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using FluentMigrator.Builders.Alter.Table;
using FluentMigrator.Expressions;
using FluentMigrator.Infrastructure;
using FluentMigrator.Model;
using FluentMigrator.Runner.Extensions;
using Moq;
using NUnit.Framework;
using NUnit.Should;
using FluentMigrator.Builders;
namespace FluentMigrator.Tests.Unit.Builders.Alter
{
[TestFixture]
public class AlterTableExpressionBuilderTests
{
[Test]
public void CallingAsAnsiStringSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString());
}
[Test]
public void CallingAsAnsiStringWithSizeSetsColumnDbTypeToAnsiString()
{
VerifyColumnDbType(DbType.AnsiString, b => b.AsAnsiString(255));
}
[Test]
public void CallingAsAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsAnsiString(255));
}
[Test]
public void CallingAsBinarySetsColumnDbTypeToBinary()
{
VerifyColumnDbType(DbType.Binary, b => b.AsBinary(255));
}
[Test]
public void CallingAsBinarySetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsBinary(255));
}
[Test]
public void CallingAsBooleanSetsColumnDbTypeToBoolean()
{
VerifyColumnDbType(DbType.Boolean, b => b.AsBoolean());
}
[Test]
public void CallingAsByteSetsColumnDbTypeToByte()
{
VerifyColumnDbType(DbType.Byte, b => b.AsByte());
}
[Test]
public void CallingAsCurrencySetsColumnDbTypeToCurrency()
{
VerifyColumnDbType(DbType.Currency, b => b.AsCurrency());
}
[Test]
public void CallingAsDateSetsColumnDbTypeToDate()
{
VerifyColumnDbType(DbType.Date, b => b.AsDate());
}
[Test]
public void CallingAsDateTimeSetsColumnDbTypeToDateTime()
{
VerifyColumnDbType(DbType.DateTime, b => b.AsDateTime());
}
[Test]
public void CallingAsDateTimeOffsetSetsColumnDbTypeToDateTimeOffset()
{
VerifyColumnDbType(DbType.DateTimeOffset, b => b.AsDateTimeOffset());
}
[Test]
public void CallingAsDecimalSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal());
}
[Test]
public void CallingAsDecimalWithSizeSetsColumnDbTypeToDecimal()
{
VerifyColumnDbType(DbType.Decimal, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(1, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDecimalStringSetsColumnPrecisionToSpecifiedValue()
{
VerifyColumnPrecision(2, b => b.AsDecimal(1, 2));
}
[Test]
public void CallingAsDoubleSetsColumnDbTypeToDouble()
{
VerifyColumnDbType(DbType.Double, b => b.AsDouble());
}
[Test]
public void CallingAsGuidSetsColumnDbTypeToGuid()
{
VerifyColumnDbType(DbType.Guid, b => b.AsGuid());
}
[Test]
public void CallingAsFixedLengthStringSetsColumnDbTypeToStringFixedLength()
{
VerifyColumnDbType(DbType.StringFixedLength, e => e.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnDbTypeToAnsiStringFixedLength()
{
VerifyColumnDbType(DbType.AnsiStringFixedLength, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFixedLengthAnsiStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsFloatSetsColumnDbTypeToSingle()
{
VerifyColumnDbType(DbType.Single, b => b.AsFloat());
}
[Test]
public void CallingAsInt16SetsColumnDbTypeToInt16()
{
VerifyColumnDbType(DbType.Int16, b => b.AsInt16());
}
[Test]
public void CallingAsInt32SetsColumnDbTypeToInt32()
{
VerifyColumnDbType(DbType.Int32, b => b.AsInt32());
}
[Test]
public void CallingAsInt64SetsColumnDbTypeToInt64()
{
VerifyColumnDbType(DbType.Int64, b => b.AsInt64());
}
[Test]
public void CallingAsStringSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString());
}
[Test]
public void CallingAsStringWithSizeSetsColumnDbTypeToString()
{
VerifyColumnDbType(DbType.String, b => b.AsString(255));
}
[Test]
public void CallingAsStringSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsFixedLengthAnsiString(255));
}
[Test]
public void CallingAsTimeSetsColumnDbTypeToTime()
{
VerifyColumnDbType(DbType.Time, b => b.AsTime());
}
[Test]
public void CallingAsXmlSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml());
}
[Test]
public void CallingAsXmlWithSizeSetsColumnDbTypeToXml()
{
VerifyColumnDbType(DbType.Xml, b => b.AsXml(255));
}
[Test]
public void CallingAsXmlSetsColumnSizeToSpecifiedValue()
{
VerifyColumnSize(255, b => b.AsXml(255));
}
[Test]
public void CallingAsCustomSetsTypeToNullAndSetsCustomType()
{
VerifyColumnProperty(c => c.Type = null, b => b.AsCustom("Test"));
VerifyColumnProperty(c => c.CustomType = "Test", b => b.AsCustom("Test"));
}
[Test]
public void CallingWithDefaultValueSetsDefaultValue()
{
const int value = 42;
var expressions = new List<IMigrationExpression>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(expressions);
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefaultValue(42);
columnMock.VerifySet(c => c.DefaultValue = value);
}
[Test]
public void CallingWithDefaultValueOnNewColumnDoesNotAddDefaultConstraintExpression() {
var expressions = new List<IMigrationExpression>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(expressions);
var columnMock = new Mock<ColumnDefinition>();
columnMock.Setup(x => x.ModificationType).Returns(ColumnModificationType.Create);
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefaultValue(42);
Assert.That(expressions.Count(), Is.EqualTo(0));
}
[Test]
public void CallingWithDefaultValueOnAlterColumnAddsDefaultConstraintExpression() {
var expressions = new List<IMigrationExpression>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(expressions);
var columnMock = new Mock<ColumnDefinition>();
columnMock.Setup(x => x.ModificationType).Returns(ColumnModificationType.Alter);
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefaultValue(42);
Assert.That(expressions.Count(), Is.EqualTo(1));
}
[Test]
public void CallingWithDefaultSetsDefaultValue()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefault(SystemMethods.CurrentDateTime);
columnMock.VerifySet(c => c.DefaultValue = SystemMethods.CurrentDateTime);
}
[Test]
public void CallingWithDefaultOnNewColumnDoesNotAddDefaultConstraintExpression()
{
var expressions = new List<IMigrationExpression>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(expressions);
var columnMock = new Mock<ColumnDefinition>();
columnMock.Setup(x => x.ModificationType).Returns(ColumnModificationType.Create);
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefault(SystemMethods.CurrentDateTime);
Assert.That(expressions.Count(), Is.EqualTo(0));
}
[Test]
public void CallingWithDefaultOnAlterColumnAddsDefaultConstraintExpression()
{
var expressions = new List<IMigrationExpression>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(expressions);
var columnMock = new Mock<ColumnDefinition>();
columnMock.Setup(x => x.ModificationType).Returns(ColumnModificationType.Alter);
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.WithDefault(SystemMethods.CurrentDateTime);
Assert.That(expressions.Count(), Is.EqualTo(1));
}
[Test]
public void CallingForeignKeySetsIsForeignKeyToTrue()
{
VerifyColumnProperty(c => c.IsForeignKey = true, b => b.ForeignKey());
}
[Test]
public void CallingReferencedByAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<AlterTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.ReferencedBy("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.ForeignTable == "FooTable" &&
fk.ForeignKey.ForeignColumns.Contains("BarColumn") &&
fk.ForeignKey.ForeignColumns.Count == 1 &&
fk.ForeignKey.PrimaryTable == "Bacon" &&
fk.ForeignKey.PrimaryColumns.Contains("BaconId") &&
fk.ForeignKey.PrimaryColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[Test]
public void CallingForeignKeyAddsNewForeignKeyExpressionToContext()
{
var collectionMock = new Mock<ICollection<IMigrationExpression>>();
var contextMock = new Mock<IMigrationContext>();
contextMock.Setup(x => x.Expressions).Returns(collectionMock.Object);
var columnMock = new Mock<ColumnDefinition>();
columnMock.SetupGet(x => x.Name).Returns("BaconId");
var expressionMock = new Mock<AlterTableExpression>();
expressionMock.SetupGet(x => x.TableName).Returns("Bacon");
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object)
{
CurrentColumn = columnMock.Object
};
builder.ForeignKey("fk_foo", "FooTable", "BarColumn");
collectionMock.Verify(x => x.Add(It.Is<CreateForeignKeyExpression>(
fk => fk.ForeignKey.Name == "fk_foo" &&
fk.ForeignKey.PrimaryTable == "FooTable" &&
fk.ForeignKey.PrimaryColumns.Contains("BarColumn") &&
fk.ForeignKey.PrimaryColumns.Count == 1 &&
fk.ForeignKey.ForeignTable == "Bacon" &&
fk.ForeignKey.ForeignColumns.Contains("BaconId") &&
fk.ForeignKey.ForeignColumns.Count == 1
)));
contextMock.VerifyGet(x => x.Expressions);
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnUpdateSetsOnUpdateOnForeignKeyExpression(Rule rule)
{
var builder = new AlterTableExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnUpdate(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(Rule.None));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnDeleteSetsOnDeleteOnForeignKeyExpression(Rule rule)
{
var builder = new AlterTableExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnDelete(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(Rule.None));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
}
[TestCase(Rule.Cascade), TestCase(Rule.SetDefault), TestCase(Rule.SetNull), TestCase(Rule.None)]
public void CallingOnDeleteOrUpdateSetsOnUpdateAndOnDeleteOnForeignKeyExpression(Rule rule)
{
var builder = new AlterTableExpressionBuilder(null, null) { CurrentForeignKey = new ForeignKeyDefinition() };
builder.OnDeleteOrUpdate(rule);
Assert.That(builder.CurrentForeignKey.OnUpdate, Is.EqualTo(rule));
Assert.That(builder.CurrentForeignKey.OnDelete, Is.EqualTo(rule));
}
[Test]
public void CallingIdentitySetsIsIdentityToTrue()
{
VerifyColumnProperty(c => c.IsIdentity = true, b => b.Identity());
}
[Test]
public void CallingIdentityWithSeededIdentitySetsAdditionalProperties()
{
var contextMock = new Mock<IMigrationContext>();
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
builder.Identity(12, 44);
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentitySeed, 12));
columnMock.Object.AdditionalFeatures.ShouldContain(
new KeyValuePair<string, object>(SqlServerExtensions.IdentityIncrement, 44));
}
[Test]
public void CallingIndexedCallsHelperWithNullIndexName()
{
VerifyColumnHelperCall(c => c.Indexed(), h => h.Indexed(null));
}
[Test]
public void CallingIndexedNamedCallsHelperWithName()
{
VerifyColumnHelperCall(c => c.Indexed("MyIndexName"), h => h.Indexed("MyIndexName"));
}
[Test]
public void CallingPrimaryKeySetsIsPrimaryKeyToTrue()
{
VerifyColumnProperty(c => c.IsPrimaryKey = true, b => b.PrimaryKey());
}
[Test]
public void ColumnHelperSetOnCreation()
{
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
Assert.IsNotNull(builder.ColumnHelper);
}
[Test]
public void IColumnExpressionBuilder_UsesExpressionSchemaAndTableName()
{
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
expressionMock.SetupGet(n => n.SchemaName).Returns("Fred");
expressionMock.SetupGet(n => n.TableName).Returns("Flinstone");
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
var builderAsInterface = (IColumnExpressionBuilder)builder;
Assert.AreEqual("Fred", builderAsInterface.SchemaName);
Assert.AreEqual("Flinstone", builderAsInterface.TableName);
}
[Test]
public void IColumnExpressionBuilder_UsesCurrentColumn()
{
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
var curColumn = new Mock<ColumnDefinition>().Object;
builder.CurrentColumn = curColumn;
var builderAsInterface = (IColumnExpressionBuilder)builder;
Assert.AreSame(curColumn, builderAsInterface.Column);
}
[Test]
public void NullableUsesHelper()
{
VerifyColumnHelperCall(c => c.Nullable(), h => h.SetNullable(true));
}
[Test]
public void NotNullableUsesHelper()
{
VerifyColumnHelperCall(c => c.NotNullable(), h => h.SetNullable(false));
}
[Test]
public void UniqueUsesHelper()
{
VerifyColumnHelperCall(c => c.Unique(), h => h.Unique(null));
}
[Test]
public void NamedUniqueUsesHelper()
{
VerifyColumnHelperCall(c => c.Unique("asdf"), h => h.Unique("asdf"));
}
[Test]
public void SetExistingRowsUsesHelper()
{
VerifyColumnHelperCall(c => c.SetExistingRowsTo("test"), h => h.SetExistingRowsTo("test"));
}
private void VerifyColumnHelperCall(Action<AlterTableExpressionBuilder> callToTest, System.Linq.Expressions.Expression<Action<ColumnExpressionBuilderHelper>> expectedHelperAction)
{
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var helperMock = new Mock<ColumnExpressionBuilderHelper>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.ColumnHelper = helperMock.Object;
callToTest(builder);
helperMock.Verify(expectedHelperAction);
}
private void VerifyColumnProperty(Action<ColumnDefinition> columnExpression, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
contextMock.SetupGet(mc => mc.Expressions).Returns(new Collection<IMigrationExpression>());
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(columnExpression);
}
private void VerifyColumnDbType(DbType expected, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Type = expected);
}
private void VerifyColumnSize(int expected, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Size = expected);
}
private void VerifyColumnPrecision(int expected, Action<AlterTableExpressionBuilder> callToTest)
{
var columnMock = new Mock<ColumnDefinition>();
var expressionMock = new Mock<AlterTableExpression>();
var contextMock = new Mock<IMigrationContext>();
var builder = new AlterTableExpressionBuilder(expressionMock.Object, contextMock.Object);
builder.CurrentColumn = columnMock.Object;
callToTest(builder);
columnMock.VerifySet(c => c.Precision = expected);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="GvrControllerInputDevice.cs" company="Google Inc.">
// Copyright 2018 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using UnityEngine;
using System;
using System.Collections;
using Gvr.Internal;
/// Device instance of the Daydream controller API.
public class GvrControllerInputDevice
{
private IControllerProvider controllerProvider;
private int controllerId;
private ControllerState controllerState = new ControllerState();
private Vector2 touchPosCentered = Vector2.zero;
private int lastUpdatedFrameCount = -1;
private bool valid;
/// Event handler for when the connection state of the controller changes.
public event GvrControllerInput.OnStateChangedEvent OnStateChanged;
internal GvrControllerInputDevice(IControllerProvider provider, int controller_id)
{
controllerProvider = provider;
controllerId = controller_id;
valid = true;
}
internal void Invalidate()
{
valid = false;
}
/// <summary>Returns true if this is the dominant controller hand.</summary>
public bool IsDominantHand
{
get { return controllerId == 0; }
}
/// <summary>Returns true if the controller is configured as being in the
/// right hand.</summary>
public bool IsRightHand
{
[SuppressMemoryAllocationError(IsWarning = true)]
get
{
if (controllerId == 0)
{
return GvrSettings.Handedness == GvrSettings.UserPrefsHandedness.Right;
}
else
{
return GvrSettings.Handedness == GvrSettings.UserPrefsHandedness.Left;
}
}
}
/// Returns the controller's current connection state.
public GvrConnectionState State
{
[SuppressMemoryAllocationError(IsWarning = true)]
get
{
Update();
return controllerState.connectionState;
}
}
/// Returns the API status of the current controller state.
public GvrControllerApiStatus ApiStatus
{
get
{
Update();
return controllerState.apiStatus;
}
}
// Returns true if the controller can be positionally tracked.
internal bool SupportsPositionalTracking
{
get { return controllerState.is6DoF; }
}
/// Returns the controller's current orientation in space, as a quaternion.
/// The rotation is provided in 'orientation space' which means the rotation is given relative
/// to the last time the user recentered their controller. To make a game object in your scene
/// have the same orientation as the controller, simply assign this quaternion to the object's
/// `transform.rotation`. To match the relative rotation, use `transform.localRotation` instead.
public Quaternion Orientation
{
get
{
Update();
return controllerState.orientation;
}
}
/// <summary>Returns the controller's current position in world space.</summary>
public Vector3 Position
{
get
{
Update();
return controllerState.position;
}
}
/// Returns the controller's current angular speed in radians per second, using the right-hand
/// rule (positive means a right-hand rotation about the given axis), as measured by the
/// controller's gyroscope.
/// The controller's axes are:
/// - X points to the right,
/// - Y points perpendicularly up from the controller's top surface
/// - Z lies along the controller's body, pointing towards the front
public Vector3 Gyro
{
get
{
Update();
return controllerState.gyro;
}
}
/// Returns the controller's current acceleration in meters per second squared.
/// The controller's axes are:
/// - X points to the right,
/// - Y points perpendicularly up from the controller's top surface
/// - Z lies along the controller's body, pointing towards the front
/// Note that gravity is indistinguishable from acceleration, so when the controller is resting
/// on a surface, expect to measure an acceleration of 9.8 m/s^2 on the Y axis. The accelerometer
/// reading will be zero on all three axes only if the controller is in free fall, or if the user
/// is in a zero gravity environment like a space station.
public Vector3 Accel
{
get
{
Update();
return controllerState.accel;
}
}
/// Position of the current touch, if touching the touchpad.
/// If not touching, this is the position of the last touch (when the finger left the touchpad).
/// The X and Y range is from -1.0 to 1.0. (0, 0) is the center of the touchpad.
/// (-.707, -.707) is bottom left, (.707, .707) is upper right.
/// The magnitude of the touch vector is guaranteed to be <= 1.0.
public Vector2 TouchPos
{
get
{
Update();
return touchPosCentered;
}
}
/// Returns true if the user just completed the recenter gesture. The headset and
/// the controller's orientation are now being reported in the new recentered
/// coordinate system. This is an event flag (it is true for only one frame
/// after the event happens, then reverts to false).
public bool Recentered
{
get
{
Update();
return controllerState.recentered;
}
}
/// Returns true if the user is holding down any of the buttons specified in `buttons`.
/// GvrControllerButton types can be OR-ed together to check for multiple buttons at once.
public bool GetButton(GvrControllerButton buttons)
{
Update();
return (controllerState.buttonsState & buttons) != 0;
}
/// Returns true in the frame the user starts pressing down any of the buttons specified
/// in `buttons`. For an individual button enum, every ButtonDown event is guaranteed to be
/// followed by exactly one ButtonUp event in a later frame. Also, ButtonDown and ButtonUp
/// will never both be true in the same frame for an individual button. Using multiple button
/// enums OR'ed together can result in multiple ButtonDowns before a ButtonUp.
public bool GetButtonDown(GvrControllerButton buttons)
{
Update();
return (controllerState.buttonsDown & buttons) != 0;
}
/// Returns true the frame after the user stops pressing down any of the buttons specified
/// in `buttons`. For an individual button enum, every ButtonUp event is guaranteed to be
/// preceded by exactly one ButtonDown event in an earlier frame. Also, ButtonDown and
/// ButtonUp will never both be true in the same frame for an individual button. Using
/// multiple button enums OR'ed together can result in multiple ButtonUps after multiple
/// ButtonDowns.
public bool GetButtonUp(GvrControllerButton buttons)
{
Update();
return (controllerState.buttonsUp & buttons) != 0;
}
/// Returns the bitmask of the buttons that are down in the current frame.
public GvrControllerButton Buttons
{
get { return controllerState.buttonsState; }
}
/// Returns the bitmask of the buttons that began being pressed in the current frame.
/// Each individual button enum is guaranteed to be followed by exactly one ButtonsUp
/// event in a later frame. Also, ButtonsDown and ButtonsUp will never both be true
/// in the same frame for an individual button.
public GvrControllerButton ButtonsDown
{
get { return controllerState.buttonsDown; }
}
/// Returns the bitmask of the buttons that ended being pressed in the current frame.
/// Each individual button enum is guaranteed to be preceded by exactly one ButtonsDown
/// event in an earlier frame. Also, ButtonsDown and ButtonsUp will never both be true
/// in the same frame for an individual button.
public GvrControllerButton ButtonsUp
{
get { return controllerState.buttonsUp; }
}
/// If State == GvrConnectionState.Error, this contains details about the error.
public string ErrorDetails
{
get
{
Update();
return controllerState.connectionState == GvrConnectionState.Error ?
controllerState.errorDetails : "";
}
}
/// Returns the GVR C library controller state pointer (gvr_controller_state*).
public IntPtr StatePtr
{
get
{
Update();
return controllerState.gvrPtr;
}
}
/// Returns true if the controller is currently being charged.
public bool IsCharging
{
get
{
Update();
return controllerState.isCharging;
}
}
/// Returns the controller's current battery charge level.
public GvrControllerBatteryLevel BatteryLevel
{
get
{
Update();
return controllerState.batteryLevel;
}
}
internal void Update()
{
if (lastUpdatedFrameCount != Time.frameCount)
{
if (!valid)
{
Debug.LogError("Using an invalid GvrControllerInputDevice. Please acquire a new one from GvrControllerInput.GetDevice().");
return;
}
// The controller state must be updated prior to any function using the
// controller API to ensure the state is consistent throughout a frame.
lastUpdatedFrameCount = Time.frameCount;
GvrConnectionState oldState = State;
controllerProvider.ReadState(controllerState, controllerId);
UpdateTouchPosCentered();
#if UNITY_EDITOR
if (IsDominantHand)
{
// Make sure the EditorEmulator is updated immediately.
if (GvrEditorEmulator.Instance != null)
{
GvrEditorEmulator.Instance.UpdateEditorEmulation();
}
}
#endif // UNITY_EDITOR
if (OnStateChanged != null && State != oldState)
{
OnStateChanged(State, oldState);
}
}
}
private void UpdateTouchPosCentered()
{
touchPosCentered.x = (controllerState.touchPos.x - 0.5f) * 2.0f;
touchPosCentered.y = -(controllerState.touchPos.y - 0.5f) * 2.0f;
float magnitude = touchPosCentered.magnitude;
if (magnitude > 1)
{
touchPosCentered.x /= magnitude;
touchPosCentered.y /= magnitude;
}
}
}
| |
// Camera Path 3
// Available on the Unity Asset Store
// Copyright (c) 2013 Jasper Stocker http://support.jasperstocker.com/camera-path/
// For support contact email@jasperstocker.com
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
using System;
using System.IO;
using UnityEngine;
using UnityEditor;
using Object = UnityEngine.Object;
public class CameraPathEditorInspectorGUI
{
private static GUIContent[] _toolBarGUIContentA;
private static GUIContent[] _toolBarGUIContentB;
private static CameraPathAnimator.orientationModes _orientationmode = CameraPathAnimator.orientationModes.custom;
public static CameraPath _cameraPath;
public static CameraPathAnimator _animator;
public static int selectedPointIndex
{
get { return _cameraPath.selectedPoint; }
set { _cameraPath.selectedPoint = value; }
}
public static CameraPath.PointModes _pointMode
{
get { return _cameraPath.pointMode; }
set { _cameraPath.pointMode = value; }
}
// private static Vector3 cpPosition;
//Preview Camera
private static float aspect = 1.7777f;
private static int previewResolution = 800;
//GUI Styles
private static GUIStyle unselectedBox;
private static GUIStyle selectedBox;
private static GUIStyle redText;
private static Texture2D unselectedBoxColour;
private static Texture2D selectedBoxColour;
public static void Setup()
{
if(_cameraPath == null)
return;
SetupToolbar();
unselectedBox = new GUIStyle();
if (unselectedBoxColour!=null)
Object.DestroyImmediate(unselectedBoxColour);
unselectedBoxColour = new Texture2D(1, 1);
unselectedBoxColour.SetPixel(0, 0, CameraPathColours.DARKGREY);
unselectedBoxColour.Apply();
unselectedBox.normal.background = unselectedBoxColour;
selectedBox = new GUIStyle();
if (selectedBoxColour != null)
Object.DestroyImmediate(selectedBoxColour);
selectedBoxColour = new Texture2D(1, 1);
selectedBoxColour.SetPixel(0, 0, CameraPathColours.DARKGREEN);
selectedBoxColour.Apply();
selectedBox.normal.background = selectedBoxColour;
redText = new GUIStyle();
redText.normal.textColor = CameraPathColours.RED;
//Preview Camera
if (_cameraPath.editorPreview != null)
Object.DestroyImmediate(_cameraPath.editorPreview);
if (CameraPathPreviewSupport.previewSupported)
{
_cameraPath.editorPreview = new GameObject("Path Point Preview Cam");
_cameraPath.editorPreview.hideFlags = HideFlags.HideAndDontSave;
_cameraPath.editorPreview.AddComponent<Camera>();
_cameraPath.editorPreview.camera.fieldOfView = 60;
_cameraPath.editorPreview.camera.depth = -1;
//Retreive camera settings from the main camera
Camera[] cams = Camera.allCameras;
bool sceneHasCamera = cams.Length > 0;
Camera sceneCamera = null;
Skybox sceneCameraSkybox = null;
if (Camera.main)
{
sceneCamera = Camera.main;
}
else if (sceneHasCamera)
{
sceneCamera = cams[0];
}
if (sceneCamera != null)
{
_cameraPath.editorPreview.camera.clearFlags = sceneCamera.clearFlags;
_cameraPath.editorPreview.camera.cullingMask = sceneCamera.cullingMask;
sceneCameraSkybox = sceneCamera.GetComponent<Skybox>();
_cameraPath.editorPreview.camera.backgroundColor = sceneCamera.backgroundColor;
if (sceneCameraSkybox != null)
_cameraPath.editorPreview.AddComponent<Skybox>().material = sceneCameraSkybox.material;
else if (RenderSettings.skybox != null)
_cameraPath.editorPreview.AddComponent<Skybox>().material = RenderSettings.skybox;
_cameraPath.editorPreview.camera.orthographic = sceneCamera.isOrthoGraphic;
}
_cameraPath.editorPreview.camera.enabled = false;
}
if (EditorApplication.isPlaying && _cameraPath.editorPreview != null)
_cameraPath.editorPreview.SetActive(false);
}
public static void OnInspectorGUI()
{
_pointMode = _cameraPath.pointMode;
if(_cameraPath.transform.rotation != Quaternion.identity)
{
EditorGUILayout.HelpBox("Camera Path does not support rotations of the main game object.", MessageType.Error);
if (GUILayout.Button("Reset Rotation"))
_cameraPath.transform.rotation = Quaternion.identity;
return;
}
GUILayout.BeginVertical(GUILayout.Width(400));
if (_cameraPath.realNumberOfPoints < 2)
{
EditorGUILayout.HelpBox("There are no track points defined, add a path point to begin", MessageType.Warning);
return;
}
EditorGUILayout.LabelField("Path Length approx. " + (_cameraPath.pathLength).ToString("F2") + " units");
bool trackloop = EditorGUILayout.Toggle("Is Looped", _cameraPath.loop);
_cameraPath.loop = trackloop;
EditorGUILayout.HelpBox("Set a Camera Path to trigger once this one has complete.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Link Camera Path", GUILayout.Width(110));
CameraPath nextPath = (CameraPath)EditorGUILayout.ObjectField(_cameraPath.nextPath, typeof(CameraPath), true);
if (_cameraPath.nextPath != nextPath)
_cameraPath.nextPath = nextPath;
EditorGUI.BeginDisabledGroup(nextPath == null);
EditorGUILayout.LabelField("Interpolate", GUILayout.Width(70));
bool interpolateNextPath = EditorGUILayout.Toggle(_cameraPath.interpolateNextPath, GUILayout.Width(30));
_cameraPath.interpolateNextPath = interpolateNextPath;
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
if (_animator != null && _orientationmode != _animator.orientationMode)
SetupToolbar();
ToolbarMenuGUI();
switch (_pointMode)
{
case CameraPath.PointModes.Transform:
ModifyPointsInspectorGUI();
break;
case CameraPath.PointModes.ControlPoints:
ModifyControlPointsInspector();
break;
case CameraPath.PointModes.FOV:
ModifyFOVInspector();
break;
case CameraPath.PointModes.Speed:
ModifySpeedInspector();
break;
case CameraPath.PointModes.Orientations:
ModifyOrientaionInspector();
break;
case CameraPath.PointModes.Tilt:
ModifyTiltsInspector();
break;
case CameraPath.PointModes.Events:
ModifyEventsInspector();
break;
case CameraPath.PointModes.Delay:
ModifyDelayInspector();
break;
case CameraPath.PointModes.Ease:
ModifyEaseInspector();
break;
case CameraPath.PointModes.AddPathPoints:
ModifyPointsInspectorGUI();
break;
case CameraPath.PointModes.RemovePathPoints:
ModifyPointsInspectorGUI();
break;
case CameraPath.PointModes.AddOrientations:
ModifyOrientaionInspector();
break;
case CameraPath.PointModes.AddTilts:
ModifyTiltsInspector();
break;
case CameraPath.PointModes.AddEvents:
ModifyEventsInspector();
break;
case CameraPath.PointModes.AddSpeeds:
ModifySpeedInspector();
break;
case CameraPath.PointModes.AddFovs:
ModifyFOVInspector();
break;
case CameraPath.PointModes.AddDelays:
ModifyDelayInspector();
break;
case CameraPath.PointModes.RemoveOrientations:
ModifyOrientaionInspector();
break;
case CameraPath.PointModes.RemoveTilts:
ModifyTiltsInspector();
break;
case CameraPath.PointModes.RemoveEvents:
ModifyEventsInspector();
break;
case CameraPath.PointModes.RemoveSpeeds:
ModifySpeedInspector();
break;
case CameraPath.PointModes.RemoveFovs:
ModifyFOVInspector();
break;
case CameraPath.PointModes.RemoveDelays:
ModifyDelayInspector();
break;
case CameraPath.PointModes.Options:
OptionsInspectorGUI();
break;
}
GUILayout.EndVertical();
}
private static void ModifyPointsInspectorGUI()
{
CameraPathControlPoint point = null;
if (selectedPointIndex >= _cameraPath.realNumberOfPoints)
ChangeSelectedPointIndex(_cameraPath.realNumberOfPoints - 1);
if (_cameraPath.realNumberOfPoints > 0)
point = _cameraPath[selectedPointIndex];
if (_cameraPath.enableUndo)Undo.RecordObject(point,"Modify Path Point");
if(_animator!=null)
RenderPreview(point.worldPosition, _animator.GetAnimatedOrientation(point.percentage,true), _cameraPath.GetPathFOV(point.percentage));
PointListGUI();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Selected point " + selectedPointIndex);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if (GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
Vector3 pointposition = EditorGUILayout.Vector3Field("Point Position", point.localPosition);
if (pointposition != point.localPosition)
{
point.localPosition = pointposition;
}
//ADD NEW POINTS
if (_pointMode != CameraPath.PointModes.AddPathPoints)
{
if(GUILayout.Button("Add Path Points"))
{
ChangePointMode(CameraPath.PointModes.AddPathPoints);
}
}
else
{
if(GUILayout.Button("Done"))
{
ChangePointMode(CameraPath.PointModes.Transform);
}
}
if (GUILayout.Button("Add Path Point to End of Path"))
AddPointToEnd();
if (_pointMode != CameraPath.PointModes.RemovePathPoints)
{
if(GUILayout.Button("Delete Path Points"))
{
ChangePointMode(CameraPath.PointModes.RemovePathPoints);
}
}
else
{
if(GUILayout.Button("Done"))
{
ChangePointMode(CameraPath.PointModes.Transform);
}
}
}
private static void ModifyControlPointsInspector()
{
bool isBezier = _cameraPath.interpolation == CameraPath.Interpolation.Bezier;
if(!isBezier)
{
EditorGUILayout.HelpBox("Path interpolation is currently not set to Bezier. There are no control points to manipulate", MessageType.Warning);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Interpolation Algorithm");
_cameraPath.interpolation = (CameraPath.Interpolation)EditorGUILayout.EnumPopup(_cameraPath.interpolation);
EditorGUILayout.EndHorizontal();
}
EditorGUI.BeginDisabledGroup(!isBezier);
CameraPathControlPoint point = null;
if (selectedPointIndex >= _cameraPath.realNumberOfPoints)
ChangeSelectedPointIndex(_cameraPath.realNumberOfPoints - 1);
if (_cameraPath.realNumberOfPoints > 0)
point = _cameraPath[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percentage,true),_cameraPath.GetPathFOV(point.percentage));
PointListGUI();
bool pointsplitControlPoints = EditorGUILayout.Toggle("Split Control Points", point.splitControlPoints);
if (pointsplitControlPoints != point.splitControlPoints)
{
point.splitControlPoints = pointsplitControlPoints;
}
Vector3 pointforwardControlPoint = EditorGUILayout.Vector3Field("Control Point Position", point.forwardControlPoint);
if (pointforwardControlPoint != point.forwardControlPoint)
{
point.forwardControlPoint = pointforwardControlPoint;
}
EditorGUI.BeginDisabledGroup(!point.splitControlPoints);
Vector3 pointbackwardControlPoint = EditorGUILayout.Vector3Field("Control Point Reverse Position", point.backwardControlPoint);
if (pointbackwardControlPoint != point.backwardControlPoint)
{
point.backwardControlPoint = pointbackwardControlPoint;
}
EditorGUI.EndDisabledGroup();
if (GUILayout.Button("Auto Place Control Point for "+point.displayName))
AutoSetControlPoint(point);
if (GUILayout.Button("Zero Control Points"))
{
point.forwardControlPointLocal = Vector3.zero;
if(point.splitControlPoints)
point.backwardControlPoint = Vector3.zero;
}
EditorGUI.EndDisabledGroup();
}
private static void ModifyOrientaionInspector()
{
CameraPathOrientationList pointList = _cameraPath.orientationList;
CameraPathOrientation point = null;
if (pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent,true),_cameraPath.GetPathFOV(point.percent));
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Interpolation Algorithm");
pointList.interpolation = (CameraPathOrientationList.Interpolation)EditorGUILayout.EnumPopup(pointList.interpolation);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Show Orientation Inidcators", GUILayout.Width(170));
_cameraPath.showOrientationIndicators = EditorGUILayout.Toggle(_cameraPath.showOrientationIndicators);
EditorGUILayout.LabelField("Every", GUILayout.Width(40));
_cameraPath.orientationIndicatorUnitLength = Mathf.Max(EditorGUILayout.FloatField(_cameraPath.orientationIndicatorUnitLength, GUILayout.Width(30)),0.1f);
EditorGUILayout.LabelField("units", GUILayout.Width(40));
EditorGUILayout.EndHorizontal();
if (pointList.realNumberOfPoints == 0)
EditorGUILayout.HelpBox("There are no orientation points in this path.", MessageType.Warning);
CPPointArrayInspector("Orientation Points", pointList, CameraPath.PointModes.Orientations, CameraPath.PointModes.AddOrientations, CameraPath.PointModes.RemoveOrientations);
if (point != null)
{
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name",GUILayout.Width(120));
point.customName = EditorGUILayout.TextField(point.customName);
if (GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
Vector3 currentRotation = point.rotation.eulerAngles;
EditorGUILayout.LabelField("Angle", GUILayout.Width(60));
Vector3 newRotation = EditorGUILayout.Vector3Field("", currentRotation);
if (currentRotation != newRotation)
{
point.rotation.eulerAngles = newRotation;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Look at CameraPathOnRailsTarget",GUILayout.Width(100));
point.lookAt = (Transform)EditorGUILayout.ObjectField(point.lookAt, typeof(Transform), true);
if(GUILayout.Button("Clear",GUILayout.Width(50)))
point.lookAt = null;
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
if(GUILayout.Button("Reset Angle"))
point.rotation = Quaternion.identity;
if(GUILayout.Button("Set to Path Direction"))
point.rotation.SetLookRotation(_cameraPath.GetPathDirection(point.percent, false));
//Thanks Perso Jery!
if (GUILayout.Button("Set All to Path Direction"))
{
//Get all points
CameraPathOrientationList orientationList = _cameraPath.orientationList;
if (orientationList.realNumberOfPoints > 0)
{
//For each point, do the logic of look rotation (the same than above)
for (int i = 0; i < orientationList.realNumberOfPoints; i++)
{
CameraPathOrientation currentPoint = pointList[i];
currentPoint.rotation.SetLookRotation(_cameraPath.GetPathDirection(currentPoint.percent, false));
}
}
}
}
}
private static void ModifyFOVInspector()
{
CameraPathFOVList pointList = _cameraPath.fovList;
CameraPathFOV point = null;
if (pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent,true),_cameraPath.GetPathFOV(point.percent));
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Interpolation Algorithm");
pointList.interpolation = (CameraPathFOVList.Interpolation)EditorGUILayout.EnumPopup(pointList.interpolation);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(pointList.realNumberOfPoints == 0);
EditorGUILayout.LabelField("Enabled");
pointList.listEnabled = EditorGUILayout.Toggle(pointList.listEnabled);
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
if (pointList.realNumberOfPoints == 0)
EditorGUILayout.HelpBox("There are no FOV points in this path.", MessageType.Warning);
CPPointArrayInspector("Field of View Points", pointList, CameraPath.PointModes.FOV, CameraPath.PointModes.AddFovs, CameraPath.PointModes.RemoveFovs);
if (point != null)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if (GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Field of View Value");
EditorGUILayout.BeginHorizontal();
float currentFOV = point.FOV;
float newFOV = EditorGUILayout.Slider(currentFOV, 0, 180);
EditorGUILayout.EndHorizontal();
if (currentFOV != newFOV)
{
point.FOV = newFOV;
}
if (GUILayout.Button("Set to Camera Default"))
{
if (_animator.isCamera)
point.FOV = _animator.animationObject.camera.fieldOfView;
else
point.FOV = Camera.main.fieldOfView;
}
EditorGUILayout.LabelField("Orthographic Size");
EditorGUILayout.BeginHorizontal();
float currentSize = point.Size;
float newSize = EditorGUILayout.FloatField(currentSize);
EditorGUILayout.EndHorizontal();
if (currentSize != newSize)
{
point.Size = newSize;
}
if (GUILayout.Button("Set to Camera Default"))
{
if (_animator.isCamera)
point.Size = _animator.animationObject.camera.orthographicSize;
else
point.Size = Camera.main.orthographicSize;
}
}
}
private static void ModifyTiltsInspector()
{
CameraPathTiltList pointList = _cameraPath.tiltList;
CameraPathTilt point = null;
if (pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent,true),_cameraPath.GetPathFOV(point.percent));
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Interpolation Algorithm");
pointList.interpolation = (CameraPathTiltList.Interpolation)EditorGUILayout.EnumPopup(pointList.interpolation);
EditorGUILayout.EndHorizontal();
if (pointList.realNumberOfPoints == 0)
EditorGUILayout.HelpBox("There are no tilt points in this path.", MessageType.Warning);
CPPointArrayInspector("Tilt Points", pointList, CameraPath.PointModes.Tilt, CameraPath.PointModes.AddTilts, CameraPath.PointModes.RemoveTilts);
if (point != null)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if (GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Tilt Value");
EditorGUILayout.BeginHorizontal();
float currentTilt = point.tilt;
float newTilt = EditorGUILayout.FloatField(currentTilt);
EditorGUILayout.EndHorizontal();
if (currentTilt != newTilt)
{
point.tilt = newTilt;
}
EditorGUILayout.BeginVertical("box");
EditorGUILayout.LabelField("Auto Set Tile Points");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Sensitivity");
_cameraPath.tiltList.autoSensitivity = EditorGUILayout.Slider(_cameraPath.tiltList.autoSensitivity, 0.0f, 1.0f);
EditorGUILayout.EndHorizontal();
if (GUILayout.Button("Calculate and Assign Selected Path Tilts"))
{
_cameraPath.tiltList.AutoSetTilt(point);
}
if (GUILayout.Button("Calculate and Assign All Path Tilts"))
{
if (EditorUtility.DisplayDialog("Auto Setting All Path Tilt Values", "Are you sure you want to set all the values in this path?", "yes", "noooooo!"))
_cameraPath.tiltList.AutoSetTilts();
}
EditorGUILayout.EndVertical();
}
}
private static void ModifySpeedInspector()
{
CameraPathSpeedList pointList = _cameraPath.speedList;
CameraPathSpeed point = null;
if (pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent,true),_cameraPath.GetPathFOV(point.percent));
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Interpolation Algorithm");
pointList.interpolation = (CameraPathSpeedList.Interpolation)EditorGUILayout.EnumPopup(pointList.interpolation);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginVertical("Box");
EditorGUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(pointList.realNumberOfPoints == 0);
EditorGUILayout.LabelField("Enabled");
pointList.listEnabled = EditorGUILayout.Toggle(pointList.listEnabled);
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
if(pointList.realNumberOfPoints==0)
EditorGUILayout.HelpBox("There are no speed points in this path so it is disabled.", MessageType.Warning);
EditorGUILayout.EndVertical();
CPPointArrayInspector("Speed Points", pointList, CameraPath.PointModes.Speed, CameraPath.PointModes.AddSpeeds, CameraPath.PointModes.RemoveSpeeds);
if(point != null)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if(GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField("Speed Value");
EditorGUILayout.BeginHorizontal();
float currentSpeed = point.speed;
float newSpeed = EditorGUILayout.FloatField(currentSpeed);
EditorGUILayout.EndHorizontal();
point.speed = newSpeed;
}
}
private static void ModifyEventsInspector()
{
CameraPathEventList pointList = _cameraPath.eventList;
CameraPathEvent point = null;
if(pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent, true),_cameraPath.GetPathFOV(point.percent));
}
CPPointArrayInspector("Event Points", pointList, CameraPath.PointModes.Events, CameraPath.PointModes.AddEvents, CameraPath.PointModes.RemoveEvents);
if(point != null)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if (GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Event Type");
point.type = (CameraPathEvent.Types)EditorGUILayout.EnumPopup(point.type);
EditorGUILayout.EndHorizontal();
switch(point.type)
{
case CameraPathEvent.Types.Broadcast:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Event Name");
point.eventName = EditorGUILayout.TextField(point.eventName);
EditorGUILayout.EndHorizontal();
break;
case CameraPathEvent.Types.Call:
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Event Target");
point.target = (GameObject)EditorGUILayout.ObjectField(point.target, typeof(GameObject), true);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Event Call");
point.methodName = EditorGUILayout.TextField(point.methodName);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Event Argument");
point.argumentType = (CameraPathEvent.ArgumentTypes)EditorGUILayout.EnumPopup(point.argumentType);
point.methodArgument = EditorGUILayout.TextField(point.methodArgument);
EditorGUILayout.EndHorizontal();
switch(point.argumentType)
{
case CameraPathEvent.ArgumentTypes.Int:
int testForInt;
if(!int.TryParse(point.methodArgument, out testForInt))
EditorGUILayout.HelpBox("Argument specified is not a valid integer", MessageType.Error);
break;
case CameraPathEvent.ArgumentTypes.Float:
float testForFloat;
if (!float.TryParse(point.methodArgument, out testForFloat))
EditorGUILayout.HelpBox("Argument specified is not a valid number", MessageType.Error);
break;
}
break;
}
}
}
private static void ModifyDelayInspector()
{
CameraPathDelayList pointList = _cameraPath.delayList;
CameraPathDelay point = null;
if (pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent, true),_cameraPath.GetPathFOV(point.percent));
}
CPPointArrayInspector("Delay Points", pointList, CameraPath.PointModes.Delay, CameraPath.PointModes.AddDelays, CameraPath.PointModes.RemoveDelays);
if (point != null)
{
if(point == pointList.outroPoint)
{
EditorGUILayout.LabelField("End Point");
}
else
{
if(point == pointList.introPoint)
EditorGUILayout.LabelField("Start Point");
else
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if(GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Delay Time");
point.time = EditorGUILayout.FloatField(point.time);
EditorGUILayout.LabelField("seconds", GUILayout.Width(60));
EditorGUILayout.EndHorizontal();
}
}
}
private static void ModifyEaseInspector()
{
CameraPathDelayList pointList = _cameraPath.delayList;
CameraPathDelay point = null;
if (pointList.realNumberOfPoints > 0)
{
if (selectedPointIndex >= pointList.realNumberOfPoints)
ChangeSelectedPointIndex(pointList.realNumberOfPoints - 1);
point = pointList[selectedPointIndex];
if (CameraPathPreviewSupport.previewSupported && _cameraPath.editorPreview != null && _animator != null)
RenderPreview(point.worldPosition,_animator.GetAnimatedOrientation(point.percent, true),_cameraPath.GetPathFOV(point.percent));
}
CPPointArrayInspector("Ease Points", pointList, CameraPath.PointModes.Ease, CameraPath.PointModes.Ease, CameraPath.PointModes.Ease);
if (point != null)
{
if (point == pointList.introPoint)
{
EditorGUILayout.LabelField("Start Point");
}
else if (point == pointList.outroPoint)
{
EditorGUILayout.LabelField("End Point");
}
else
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Custom Point Name");
point.customName = EditorGUILayout.TextField(point.customName);
if (GUILayout.Button("Clear"))
point.customName = "";
EditorGUILayout.EndHorizontal();
}
if (point != pointList.introPoint)
{
EditorGUILayout.LabelField("Ease In Curve");
point.introCurve = EditorGUILayout.CurveField(point.introCurve, GUILayout.Height(50));
point.introStartEasePercentage = EditorGUILayout.FloatField(point.introStartEasePercentage);
if (GUILayout.Button("None"))
point.introCurve = AnimationCurve.Linear(0, 1, 1, 1);
if (GUILayout.Button("Linear"))
point.introCurve = AnimationCurve.Linear(0,1,1,0);
if (GUILayout.Button("Ease In"))
point.introCurve = new AnimationCurve(new[] { new Keyframe(0, 1, 0, 0.0f), new Keyframe(1, 0, -1.0f, 0) });
}
if (point != pointList.outroPoint)
{
EditorGUILayout.LabelField("Ease Out Curve");
point.outroCurve = EditorGUILayout.CurveField(point.outroCurve, GUILayout.Height(50));
point.outroEndEasePercentage = EditorGUILayout.FloatField(point.outroEndEasePercentage);
if (GUILayout.Button("None"))
point.outroCurve = AnimationCurve.Linear(0, 1, 1, 1);
if (GUILayout.Button("Linear"))
point.outroCurve = AnimationCurve.Linear(0, 0, 1, 1);
if (GUILayout.Button("Ease Out"))
point.outroCurve = new AnimationCurve(new[] { new Keyframe(0, 0, 0, 1.0f), new Keyframe(1, 1, 0, 0) });
}
}
}
private static void PointListGUI()
{
EditorGUILayout.Space();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Interpolation Algorithm");
_cameraPath.interpolation = (CameraPath.Interpolation)EditorGUILayout.EnumPopup(_cameraPath.interpolation);
EditorGUILayout.EndHorizontal();
if(_cameraPath.interpolation == CameraPath.Interpolation.Hermite)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Tension");
_cameraPath.hermiteTension = EditorGUILayout.Slider(_cameraPath.hermiteTension, -1, 1);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Bias");
_cameraPath.hermiteBias = EditorGUILayout.Slider(_cameraPath.hermiteBias, -1, 1);
EditorGUILayout.EndHorizontal();
}
int numberOfPoints = _cameraPath.realNumberOfPoints;
if(_cameraPath.interpolation == CameraPath.Interpolation.Bezier)
{
if(GUILayout.Button("Auto Set All Control Points"))
for(int i = 0; i < numberOfPoints; i++)
AutoSetControlPoint(_cameraPath[i]);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Path Points ");
for (int i = 0; i < numberOfPoints; i++)
{
bool pointIsSelected = i == selectedPointIndex;
EditorGUILayout.BeginHorizontal((pointIsSelected) ? selectedBox : unselectedBox);
CameraPathControlPoint cpPoint = _cameraPath[i];
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(cpPoint.displayName, GUILayout.Width(100));
if(!pointIsSelected)
{
if (GUILayout.Button("Select"))
{
ChangeSelectedPointIndex(i);
GotoScenePoint(cpPoint.worldPosition);
}
}
else
{
if (GUILayout.Button("Goto"))
GotoScenePoint(cpPoint.worldPosition);
}
if(i < numberOfPoints - 1)
{
if(GUILayout.Button("Insert New Point"))
{
int atIndex = cpPoint.index + 1;
CameraPathControlPoint pointA = _cameraPath.GetPoint(atIndex - 1);
CameraPathControlPoint pointB = _cameraPath.GetPoint(atIndex);
float newPointPercent = _cameraPath.GetPathPercentage(pointA, pointB, 0.5f);
Vector3 newPointPosition = _cameraPath.GetPathPosition(newPointPercent, true);
Vector3 newForwardControlPoint = _cameraPath.GetPathDirection(newPointPercent, true) * ((pointA.forwardControlPointLocal.magnitude + pointB.forwardControlPointLocal.magnitude) * 0.5f);
CameraPathControlPoint newPoint = _cameraPath.InsertPoint(atIndex);
newPoint.worldPosition = newPointPosition;
newPoint.forwardControlPointLocal = newForwardControlPoint;
}
}
else
{
if(GUILayout.Button("Add Point to End"))
{
AddPointToEnd();
}
}
EditorGUI.BeginDisabledGroup(numberOfPoints < 3);
if (GUILayout.Button("Delete"))
{
_cameraPath.RemovePoint(cpPoint);
return;//cheap, but effective. Cancel any further actions on this frame
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndHorizontal();
}
}
private static void CPPointArrayInspector(string title, CameraPathPointList pointList, CameraPath.PointModes deflt, CameraPath.PointModes add, CameraPath.PointModes remove)
{
EditorGUILayout.Space();
EditorGUILayout.LabelField(title);
int numberOfPoints = pointList.realNumberOfPoints;
if(numberOfPoints==0)
EditorGUILayout.LabelField("There are no points", redText);
CameraPathPoint duplicatePoint = pointList.DuplicatePointCheck();
if (duplicatePoint != null)
EditorGUILayout.HelpBox("There are points occuping the same percentage.\n Check "+duplicatePoint.displayName+" thanks.", MessageType.Error);
for (int i = 0; i < numberOfPoints; i++)
{
bool cantDelete = false;
bool pointIsSelected = i == selectedPointIndex;
EditorGUILayout.BeginHorizontal((pointIsSelected) ? selectedBox : unselectedBox);
CameraPathPoint arrayPoint = pointList[i];
EditorGUILayout.BeginHorizontal();
if (arrayPoint.customName == "")
EditorGUILayout.LabelField("Point " + i, GUILayout.Width(85));
else
EditorGUILayout.LabelField(arrayPoint.customName, GUILayout.Width(85));
float valueTextSize = 120;
switch(deflt)
{
case CameraPath.PointModes.FOV:
CameraPathFOV fov = (CameraPathFOV)arrayPoint;
EditorGUILayout.LabelField("FOV", GUILayout.Width(30));
fov.FOV = EditorGUILayout.FloatField(fov.FOV, GUILayout.Width(50));
EditorGUILayout.LabelField("Size", GUILayout.Width(30));
fov.Size = EditorGUILayout.FloatField(fov.Size, GUILayout.Width(50));
break;
case CameraPath.PointModes.Speed:
CameraPathSpeed speed = (CameraPathSpeed)arrayPoint;
speed.speed = EditorGUILayout.FloatField(speed.speed, GUILayout.Width(50));
break;
case CameraPath.PointModes.Delay:
CameraPathDelay delay = (CameraPathDelay)arrayPoint;
if(delay != _cameraPath.delayList.outroPoint)
{
delay.time = EditorGUILayout.FloatField(delay.time, GUILayout.Width(50));
EditorGUILayout.LabelField("secs", GUILayout.Width(40));
if(delay != _cameraPath.delayList.introPoint)
cantDelete = false;
else
cantDelete = true;
}
else
{
cantDelete = true;
}
break;
case CameraPath.PointModes.Ease:
cantDelete = true;
break;
case CameraPath.PointModes.Orientations:
CameraPathOrientation orientation = (CameraPathOrientation)arrayPoint;
EditorGUILayout.LabelField(orientation.rotation.eulerAngles.ToString(), GUILayout.Width(valueTextSize));
break;
case CameraPath.PointModes.Tilt:
CameraPathTilt tilt = (CameraPathTilt)arrayPoint;
tilt.tilt = EditorGUILayout.FloatField(tilt.tilt, GUILayout.Width(50));
break;
case CameraPath.PointModes.Events:
CameraPathEvent point = (CameraPathEvent)arrayPoint;
point.type = (CameraPathEvent.Types)EditorGUILayout.EnumPopup(point.type, GUILayout.Width(50));
if(point.type == CameraPathEvent.Types.Broadcast)
point.eventName = EditorGUILayout.TextField(point.eventName, GUILayout.Width(120));
else
{
point.target = (GameObject)EditorGUILayout.ObjectField(point.target, typeof(GameObject), true);
point.methodName = EditorGUILayout.TextField(point.methodName, GUILayout.Width(55));
}
break;
}
if (!pointIsSelected)
{
if (GUILayout.Button("Select", GUILayout.Width(60)))
{
ChangeSelectedPointIndex(i);
GotoScenePoint(arrayPoint.worldPosition);
}
}
else
{
if (GUILayout.Button("Go to", GUILayout.Width(60)))
{
GotoScenePoint(arrayPoint.worldPosition);
}
}
if(!cantDelete)
{
if (GUILayout.Button("Delete", GUILayout.Width(60)))
{
pointList.RemovePoint(arrayPoint);
return;
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndHorizontal();
}
if(deflt == CameraPath.PointModes.Ease || deflt == CameraPath.PointModes.ControlPoints)
return;
//ADD NEW POINTS
EditorGUILayout.BeginVertical("box");
EditorGUI.BeginDisabledGroup(_pointMode != deflt);
if (GUILayout.Button("Add Point From Inspector"))
AddCPointAtPercent(_cameraPath.addPointAtPercent);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("At Percent", GUILayout.Width(80));
_cameraPath.addPointAtPercent = EditorGUILayout.Slider(_cameraPath.addPointAtPercent, 0, 1);
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
if (_pointMode != add)
{
if(GUILayout.Button("Add Points in Scene"))
{
ChangePointMode(add);
}
}
else
{
if(GUILayout.Button("Done Adding Points"))
{
ChangePointMode(deflt);
}
}
EditorGUI.BeginDisabledGroup(numberOfPoints==0);
if (_pointMode != remove)
{
if(GUILayout.Button("Delete Points in Scene"))
{
ChangePointMode(remove);
}
}
else
{
if(GUILayout.Button("Done"))
{
ChangePointMode(deflt);
}
}
EditorGUI.EndDisabledGroup();
}
private static void OptionsInspectorGUI()
{
EditorGUILayout.Space();
EditorGUILayout.BeginVertical("box");
Texture2D cpLogo = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/logoDual400.png", typeof(Texture2D));
GUILayout.Label(cpLogo, GUILayout.Width(400), GUILayout.Height(72));
EditorGUILayout.Space();
EditorGUILayout.LabelField("Version " + _cameraPath.version);
EditorGUILayout.SelectableLabel("Support Contact: email@jasperstocker.com");
EditorGUILayout.BeginHorizontal();
if(GUILayout.Button("Visit Support Site"))
Application.OpenURL("http://camerapathanimator.jasperstocker.com");
if(GUILayout.Button("Documentation"))
Application.OpenURL("http://camerapathanimator.jasperstocker.com/documentation/");
if(GUILayout.Button("Contact Jasper"))
Application.OpenURL("mailto:email@jasperstocker.com");
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
_cameraPath.showGizmos = EditorGUILayout.Toggle("Show Gizmos", _cameraPath.showGizmos);
EditorGUILayout.BeginVertical("box");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Selected Path Colour");
_cameraPath.selectedPathColour = EditorGUILayout.ColorField(_cameraPath.selectedPathColour);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Unselected Path Colour");
_cameraPath.unselectedPathColour = EditorGUILayout.ColorField(_cameraPath.unselectedPathColour);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Selected Point Colour");
_cameraPath.selectedPointColour = EditorGUILayout.ColorField(_cameraPath.selectedPointColour);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Unselected Point Colour");
_cameraPath.unselectedPointColour = EditorGUILayout.ColorField(_cameraPath.unselectedPointColour);
EditorGUILayout.EndHorizontal();
if(GUILayout.Button("Reset Colours"))
{
_cameraPath.selectedPathColour = CameraPathColours.GREEN;
_cameraPath.unselectedPathColour = CameraPathColours.GREY;
_cameraPath.selectedPointColour = CameraPathColours.RED;
_cameraPath.unselectedPointColour = CameraPathColours.GREEN;
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.HelpBox("The Stored Point Resolution is used by Camera Path Animator to help it judge how many samples it needs to take.\nA higher value means there are less points taken so calculation is faster but normalisation may be less accurate.\nBy default this value is dynamic, set as a percent of the path length but you can choose to hard set it.\nDon't touch it if that didn't just make sense though...", MessageType.Info);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Automatically Calculate Resolution");
_cameraPath.autoSetStoedPointRes = EditorGUILayout.Toggle(_cameraPath.autoSetStoedPointRes, GUILayout.Width(20));
EditorGUILayout.EndHorizontal();
_cameraPath.storedPointResolution = EditorGUILayout.FloatField("Stored Point Resolution", _cameraPath.storedPointResolution);
if(!_cameraPath.speedList.listEnabled)
{
if(_cameraPath.storedPointResolution > _animator.pathSpeed / 10)
EditorGUILayout.HelpBox("The current stored point resolution is possibly too high. Lower it to less than the speed you're using", MessageType.Error);
}else{
if(_cameraPath.storedPointResolution > _cameraPath.speedList.GetLowesetSpeed()/10)
EditorGUILayout.HelpBox("The current stored point resolution is possibly too high. Lower it to less than the lowest speed you're using", MessageType.Error);
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical("box");
EditorGUILayout.HelpBox("Ease curves can end up outputing zero which would pause the animation indefinitly. We negate this issue by defining a minimum speed the animation is allowed to move. You can change that value here.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Minimum Animation Speed");
_animator.minimumCameraSpeed = EditorGUILayout.FloatField(_animator.minimumCameraSpeed, GUILayout.Width(60));
EditorGUILayout.LabelField("m/s", GUILayout.Width(25));
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
_cameraPath.enableUndo = EditorGUILayout.Toggle("Enable Undo", _cameraPath.enableUndo);
_cameraPath.enablePreviews = EditorGUILayout.Toggle("Enable Preview Windows", _cameraPath.enablePreviews);
EditorGUILayout.Space();
if (GUILayout.Button("Export to XML"))
ExportXML();
if(GUILayout.Button("Import from XML"))
{
string xmlpath = EditorUtility.OpenFilePanel("Import Camera Path from XML", "Assets/CameraPath3/", "xml");
if(xmlpath!="")
_cameraPath.FromXML(xmlpath);
}
}
/// <summary>
/// A little hacking of the Unity Editor to allow us to focus on an arbitrary point in 3D Space
/// We're replicating pressing the F button in scene view to focus on the selected object
/// Here we can focus on a 3D point
/// </summary>
/// <param name="position">The 3D point we want to focus on</param>
private static void GotoScenePoint(Vector3 position)
{
Object[] intialFocus = Selection.objects;
GameObject tempFocusView = new GameObject("Temp Focus View");
tempFocusView.transform.position = position;
try
{
Selection.objects = new Object[]{tempFocusView};
SceneView.lastActiveSceneView.FrameSelected();
Selection.objects = intialFocus;
}
catch(NullReferenceException)
{
//do nothing
}
Object.DestroyImmediate(tempFocusView);
}
private static void ToolbarMenuGUI()
{
bool isDefaultMenu = _animator == null || _animator.orientationMode != CameraPathAnimator.orientationModes.custom && _animator.orientationMode != CameraPathAnimator.orientationModes.followpath && _animator.orientationMode != CameraPathAnimator.orientationModes.reverseFollowpath;
int currentPointModeA = -1;
int currentPointModeB = -1;
switch (_pointMode)
{
case CameraPath.PointModes.Transform:
currentPointModeA = 0;
break;
case CameraPath.PointModes.AddPathPoints:
currentPointModeA = 0;
break;
case CameraPath.PointModes.RemovePathPoints:
currentPointModeA = 0;
break;
case CameraPath.PointModes.ControlPoints:
currentPointModeA = 1;
break;
case CameraPath.PointModes.FOV:
currentPointModeA = 2;
break;
case CameraPath.PointModes.AddFovs:
currentPointModeA = 2;
break;
case CameraPath.PointModes.RemoveFovs:
currentPointModeA = 2;
break;
case CameraPath.PointModes.Speed:
currentPointModeA = 3;
break;
case CameraPath.PointModes.AddSpeeds:
currentPointModeA = 3;
break;
case CameraPath.PointModes.RemoveSpeeds:
currentPointModeA = 3;
break;
case CameraPath.PointModes.Delay:
currentPointModeB = 0;
break;
case CameraPath.PointModes.AddDelays:
currentPointModeB = 0;
break;
case CameraPath.PointModes.RemoveDelays:
currentPointModeB = 0;
break;
case CameraPath.PointModes.Ease:
currentPointModeB = 1;
break;
case CameraPath.PointModes.Events:
currentPointModeB = 2;
break;
case CameraPath.PointModes.AddEvents:
currentPointModeB = 2;
break;
case CameraPath.PointModes.RemoveEvents:
currentPointModeB = 2;
break;
case CameraPath.PointModes.Orientations:
currentPointModeB = 3;
break;
case CameraPath.PointModes.AddOrientations:
currentPointModeB = 3;
break;
case CameraPath.PointModes.RemoveOrientations:
currentPointModeB = 3;
break;
case CameraPath.PointModes.Tilt:
currentPointModeB = 3;
break;
case CameraPath.PointModes.AddTilts:
currentPointModeB = 3;
break;
case CameraPath.PointModes.RemoveTilts:
currentPointModeB = 3;
break;
case CameraPath.PointModes.Options:
currentPointModeB = (isDefaultMenu) ? 3 : 4;
break;
}
int newPointModeA = GUILayout.Toolbar(currentPointModeA, _toolBarGUIContentA, GUILayout.Width(320), GUILayout.Height(64));
int newPointModeB = GUILayout.Toolbar(currentPointModeB, _toolBarGUIContentB, GUILayout.Width((isDefaultMenu)?320:400), GUILayout.Height(64));
if(newPointModeA != currentPointModeA)
{
switch(newPointModeA)
{
case 0:
if(_pointMode == CameraPath.PointModes.AddPathPoints)
return;
if(_pointMode == CameraPath.PointModes.RemovePathPoints)
return;
ChangePointMode(CameraPath.PointModes.Transform);
break;
case 1:
ChangePointMode(CameraPath.PointModes.ControlPoints);
break;
case 2:
if(_pointMode == CameraPath.PointModes.AddFovs)
return;
if(_pointMode == CameraPath.PointModes.RemoveFovs)
return;
ChangePointMode(CameraPath.PointModes.FOV);
break;
case 3:
if(_pointMode == CameraPath.PointModes.AddSpeeds)
return;
if(_pointMode == CameraPath.PointModes.RemoveSpeeds)
return;
ChangePointMode(CameraPath.PointModes.Speed);
break;
}
GUI.changed = true;
}
if (newPointModeB != currentPointModeB)
{
switch(newPointModeB)
{
case 0:
if(_pointMode == CameraPath.PointModes.AddDelays)
return;
if(_pointMode == CameraPath.PointModes.RemoveDelays)
return;
ChangePointMode(CameraPath.PointModes.Delay);
break;
case 1:
ChangePointMode(CameraPath.PointModes.Ease);
break;
case 2:
if(_pointMode == CameraPath.PointModes.AddEvents)
return;
if(_pointMode == CameraPath.PointModes.RemoveEvents)
return;
ChangePointMode(CameraPath.PointModes.Events);
break;
case 3:
if(isDefaultMenu)
ChangePointMode(CameraPath.PointModes.Options);
else
{
if(_animator.orientationMode == CameraPathAnimator.orientationModes.custom)
{
if(_pointMode == CameraPath.PointModes.AddOrientations)
return;
if(_pointMode == CameraPath.PointModes.RemoveOrientations)
return;
ChangePointMode(CameraPath.PointModes.Orientations);
}
else
{
if(_pointMode == CameraPath.PointModes.AddTilts)
return;
if(_pointMode == CameraPath.PointModes.RemoveTilts)
return;
ChangePointMode(CameraPath.PointModes.Tilt);
}
}
break;
case 4:
ChangePointMode(CameraPath.PointModes.Options);
break;
}
GUI.changed = true;
}
}
private static void RenderPreview(Vector3 position, Quaternion rotation, float viewSize)
{
if (_cameraPath.realNumberOfPoints < 2)
return;
if (!CameraPathPreviewSupport.previewSupported || _cameraPath.editorPreview == null)
return;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Preview");
string showPreviewButtonLabel = (_cameraPath.showPreview) ? "hide" : "show";
if (GUILayout.Button(showPreviewButtonLabel, GUILayout.Width(74)))
_cameraPath.showPreview = !_cameraPath.showPreview;
EditorGUILayout.EndHorizontal();
if(!_cameraPath.enablePreviews || !_cameraPath.showPreview)
return;
GameObject editorPreview = _cameraPath.editorPreview;
if (CameraPathPreviewSupport.previewSupported && !EditorApplication.isPlaying)
{
RenderTexture rt = RenderTexture.GetTemporary(previewResolution, Mathf.RoundToInt(previewResolution / aspect), 24, RenderTextureFormat.Default, RenderTextureReadWrite.sRGB, 1);
editorPreview.SetActive(true);
editorPreview.transform.position = position;
editorPreview.transform.rotation = rotation;
Camera previewCam = editorPreview.camera;
previewCam.enabled = true;
if (previewCam.isOrthoGraphic)
previewCam.orthographicSize = _cameraPath.GetPathOrthographicSize(_animator.editorPercentage);
else
previewCam.fieldOfView = _cameraPath.GetPathFOV(_animator.editorPercentage);
previewCam.targetTexture = rt;
previewCam.Render();
previewCam.targetTexture = null;
previewCam.enabled = false;
editorPreview.SetActive(false);
GUILayout.Label("", GUILayout.Width(400), GUILayout.Height(225));
Rect guiRect = GUILayoutUtility.GetLastRect();
GUI.DrawTexture(guiRect, rt, ScaleMode.ScaleToFit, false);
RenderTexture.ReleaseTemporary(rt);
}
else
{
string errorMsg = (!CameraPathPreviewSupport.previewSupported) ? CameraPathPreviewSupport.previewSupportedText : "No Preview When Playing.";
EditorGUILayout.LabelField(errorMsg, GUILayout.Height(225));
}
}
private static void AddPointToEnd()
{
CameraPathControlPoint newPoint = _cameraPath.gameObject.AddComponent<CameraPathControlPoint>();//ScriptableObject.CreateInstance<CameraPathControlPoint>();
Vector3 finalPathPosition = _cameraPath.GetPathPosition(1.0f);
Vector3 finalPathDirection = _cameraPath.GetPathDirection(1.0f);
float finalArcLength = _cameraPath.StoredArcLength(_cameraPath.numberOfCurves - 1);
Vector3 newPathPointPosition = finalPathPosition + finalPathDirection * (finalArcLength);
newPoint.worldPosition = newPathPointPosition;
newPoint.forwardControlPointLocal = _cameraPath[_cameraPath.realNumberOfPoints - 1].forwardControlPointLocal;
_cameraPath.AddPoint(newPoint);
ChangeSelectedPointIndex(_cameraPath.realNumberOfPoints - 1);
GUI.changed = true;
}
private static void AddCPointAtPercent(float percent)
{
CameraPathPointList pointList = null;
switch(_pointMode)
{
case CameraPath.PointModes.Orientations:
pointList = _cameraPath.orientationList;
break;
case CameraPath.PointModes.FOV:
pointList = _cameraPath.fovList;
break;
case CameraPath.PointModes.Tilt:
pointList = _cameraPath.tiltList;
break;
case CameraPath.PointModes.Events:
pointList = _cameraPath.eventList;
break;
case CameraPath.PointModes.Speed:
pointList = _cameraPath.speedList;
break;
case CameraPath.PointModes.Delay:
pointList = _cameraPath.delayList;
break;
}
CameraPathControlPoint curvePointA = _cameraPath[_cameraPath.GetLastPointIndex(percent, false)];
CameraPathControlPoint curvePointB = _cameraPath[_cameraPath.GetNextPointIndex(percent, false)];
float curvePercentage = _cameraPath.GetCurvePercentage(curvePointA, curvePointB, percent);
switch(_pointMode)
{
case CameraPath.PointModes.Orientations:
Quaternion pointRotation = Quaternion.LookRotation(_cameraPath.GetPathDirection(percent));
CameraPathOrientation newOrientation = ((CameraPathOrientationList)pointList).AddOrientation(curvePointA, curvePointB, curvePercentage, pointRotation);
selectedPointIndex = (pointList.IndexOf(newOrientation));
break;
case CameraPath.PointModes.FOV:
float pointFOV = _cameraPath.fovList.GetValue(percent, CameraPathFOVList.ProjectionType.FOV);
float pointSize = _cameraPath.fovList.GetValue(percent, CameraPathFOVList.ProjectionType.Orthographic);
CameraPathFOV newFOVPoint = ((CameraPathFOVList)pointList).AddFOV(curvePointA, curvePointB, curvePercentage, pointFOV, pointSize);
selectedPointIndex = (pointList.IndexOf(newFOVPoint));
break;
case CameraPath.PointModes.Tilt:
float pointTilt = _cameraPath.GetPathTilt(percent);
CameraPathTilt newTiltPoint = ((CameraPathTiltList)pointList).AddTilt(curvePointA, curvePointB, curvePercentage, pointTilt);
selectedPointIndex = (pointList.IndexOf(newTiltPoint));
break;
case CameraPath.PointModes.Events:
CameraPathEvent newEventPoint = ((CameraPathEventList)pointList).AddEvent(curvePointA, curvePointB, curvePercentage);
selectedPointIndex = (pointList.IndexOf(newEventPoint));
break;
case CameraPath.PointModes.Speed:
_cameraPath.speedList.listEnabled = true;//if we're adding speeds then we probable want to enable it
CameraPathSpeed newSpeedPoint = ((CameraPathSpeedList)pointList).AddSpeedPoint(curvePointA, curvePointB, curvePercentage);
newSpeedPoint.speed = _animator.pathSpeed;
selectedPointIndex = (pointList.IndexOf(newSpeedPoint));
break;
case CameraPath.PointModes.Delay:
CameraPathDelay newDelayPoint = ((CameraPathDelayList)pointList).AddDelayPoint(curvePointA, curvePointB, curvePercentage);
selectedPointIndex = (pointList.IndexOf(newDelayPoint));
break;
}
GUI.changed = true;
}
private static void ChangePointMode(CameraPath.PointModes newPointMode)
{
_pointMode = newPointMode;
EditorGUIUtility.hotControl = 0;
EditorGUIUtility.keyboardControl = 0;
}
private static void ChangeSelectedPointIndex(int newPointSelected)
{
selectedPointIndex = newPointSelected;
EditorGUIUtility.hotControl = 0;
EditorGUIUtility.keyboardControl = 0;
}
public static void CleanUp()
{
if (_cameraPath.editorPreview != null)
Object.DestroyImmediate(_cameraPath.editorPreview);
Object.DestroyImmediate(selectedBoxColour);
Object.DestroyImmediate(unselectedBoxColour);
}
private static void SetupToolbar()
{
int menuType = 0;
CameraPathAnimator.orientationModes orientationMode;
orientationMode = (_animator != null) ? _animator.orientationMode : CameraPathAnimator.orientationModes.none;
switch (orientationMode)
{
case CameraPathAnimator.orientationModes.custom:
menuType = 1;
break;
case CameraPathAnimator.orientationModes.followpath:
menuType = 2;
break;
case CameraPathAnimator.orientationModes.reverseFollowpath:
menuType = 2;
break;
default:
menuType = 0;
break;
}
int menuLengthA = 0;
int menuLengthB = 0;
string[] menuStringA = new string[0];
string[] menuStringB = new string[0];
Texture2D[] toolbarTexturesA = new Texture2D[0];
Texture2D[] toolbarTexturesB = new Texture2D[0];
switch (menuType)
{
default:
menuLengthA = 4;
menuLengthB = 4;
menuStringA = new[] { "Path Points", "Control Points", "FOV", "Speed" };
menuStringB = new[] { "Delays", "Ease", "Events", "Options" };
toolbarTexturesA = new Texture2D[menuLengthA];
toolbarTexturesB = new Texture2D[menuLengthB];
toolbarTexturesA[0] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/pathpoints.png", typeof(Texture2D));
toolbarTexturesA[1] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/controlpoints.png", typeof(Texture2D));
toolbarTexturesA[2] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/fov.png", typeof(Texture2D));
toolbarTexturesA[3] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/speed.png", typeof(Texture2D));
toolbarTexturesB[0] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/delay.png", typeof(Texture2D));
toolbarTexturesB[1] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/easecurves.png", typeof(Texture2D));
toolbarTexturesB[2] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/events.png", typeof(Texture2D));
toolbarTexturesB[3] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/options.png", typeof(Texture2D));
break;
case 1:
menuLengthA = 4;
menuLengthB = 5;
menuStringA = new[] { "Path Points", "Control Points", "FOV", "Speed"};
menuStringB = new[] { "Delays", "Ease", "Events", "Orientations", "Options" };
toolbarTexturesA = new Texture2D[menuLengthA];
toolbarTexturesB = new Texture2D[menuLengthB];
toolbarTexturesA[0] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/pathpoints.png", typeof(Texture2D));
toolbarTexturesA[1] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/controlpoints.png", typeof(Texture2D));
toolbarTexturesA[2] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/fov.png", typeof(Texture2D));
toolbarTexturesA[3] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/speed.png", typeof(Texture2D));
toolbarTexturesB[0] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/delay.png", typeof(Texture2D));
toolbarTexturesB[1] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/easecurves.png", typeof(Texture2D));
toolbarTexturesB[2] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/events.png", typeof(Texture2D));
toolbarTexturesB[3] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/orientation.png", typeof(Texture2D));
toolbarTexturesB[4] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/options.png", typeof(Texture2D));
break;
case 2:
menuLengthA = 4;
menuLengthB = 5;
menuStringA = new[] { "Path Points", "Control Points", "FOV", "Speed"};
menuStringB = new[] { "Delays", "Ease", "Events", "Tilt", "Options" };
toolbarTexturesA = new Texture2D[menuLengthA];
toolbarTexturesB = new Texture2D[menuLengthB];
toolbarTexturesA[0] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/pathpoints.png", typeof(Texture2D));
toolbarTexturesA[1] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/controlpoints.png", typeof(Texture2D));
toolbarTexturesA[2] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/fov.png", typeof(Texture2D));
toolbarTexturesA[3] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/speed.png", typeof(Texture2D));
toolbarTexturesB[0] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/delay.png", typeof(Texture2D));
toolbarTexturesB[1] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/easecurves.png", typeof(Texture2D));
toolbarTexturesB[2] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/events.png", typeof(Texture2D));
toolbarTexturesB[3] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/tilt.png", typeof(Texture2D));
toolbarTexturesB[4] = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/CameraPath3/Icons/options.png", typeof(Texture2D));
break;
}
_toolBarGUIContentA = new GUIContent[menuLengthA];
for (int i = 0; i < menuLengthA; i++)
_toolBarGUIContentA[i] = new GUIContent(toolbarTexturesA[i], menuStringA[i]);
_toolBarGUIContentB = new GUIContent[menuLengthB];
for (int i = 0; i < menuLengthB; i++)
_toolBarGUIContentB[i] = new GUIContent(toolbarTexturesB[i], menuStringB[i]);
if(_animator!=null)
_orientationmode = _animator.orientationMode;
}
private static void ExportXML()
{
string defaultName = _cameraPath.name;
defaultName.Replace(" ", "_");
string filepath = EditorUtility.SaveFilePanel("Export Camera Path Animator to XML", "Assets/CameraPath3", defaultName, "xml");
if(filepath != "")
{
using (StreamWriter sw = new StreamWriter(filepath))
{
sw.Write(_cameraPath.ToXML());//write out contents of data to XML
}
}
}
private static void AutoSetControlPoint(CameraPathControlPoint point)
{
CameraPathControlPoint point0 = _cameraPath.GetPoint(point.index - 1);
CameraPathControlPoint point1 = _cameraPath.GetPoint(point.index + 1);
float distanceA = Vector3.Distance(point.worldPosition, point0.worldPosition);
float distanceB = Vector3.Distance(point.worldPosition, point1.worldPosition);
float controlPointLength = Mathf.Min(distanceA,distanceB) * 0.33333f;
Vector3 controlPointDirection = ((point.worldPosition - point0.worldPosition) + (point1.worldPosition - point.worldPosition)).normalized;
point.forwardControlPointLocal = controlPointDirection * controlPointLength;
}
private static void ResetFocus()
{
EditorGUIUtility.hotControl = 0;
EditorGUIUtility.keyboardControl = 0;
}
}
| |
// 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.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
using Microsoft.SqlServer.TDS.EndPoint;
using Microsoft.SqlServer.TDS.EndPoint.SSPI;
using Microsoft.SqlServer.TDS.PreLogin;
using Microsoft.SqlServer.TDS.Login7;
using Microsoft.SqlServer.TDS.SessionState;
namespace Microsoft.SqlServer.TDS.Servers
{
/// <summary>
/// Generic session for TDS Server
/// </summary>
public class GenericTDSServerSession : ITDSServerSession
{
/// <summary>
/// Server that created the session
/// </summary>
public ITDSServer Server { get; private set; }
/// <summary>
/// Session identifier
/// </summary>
public uint SessionID { get; private set; }
/// <summary>
/// Size of the TDS packet
/// </summary>
public uint PacketSize { get; set; }
/// <summary>
/// User name if SQL authentication is used
/// </summary>
public string SQLUserID { get; set; }
/// <summary>
/// Context that indicates the stage of SSPI authentication
/// </summary>
public SSPIContext NTUserAuthenticationContext { get; set; }
/// <summary>
/// Database to which connection is established
/// </summary>
public string Database { get; set; }
/// <summary>
/// Collation
/// </summary>
public byte[] Collation { get; set; }
/// <summary>
/// TDS version of the communication
/// </summary>
public Version TDSVersion { get; set; }
/// <summary>
/// Local connection end-point information
/// </summary>
public TDSEndPointInfo ServerEndPointInfo { get; set; }
/// <summary>
/// Remote connection end-point information
/// </summary>
public TDSEndPointInfo ClientEndPointInfo { get; set; }
/// <summary>
/// Transport encryption
/// </summary>
public TDSEncryptionType Encryption { get; set; }
/// <summary>
/// Certificate to use for encryption
/// </summary>
public X509Certificate EncryptionCertificate { get; set; }
/// <summary>
/// Nonce option sent by client
/// </summary>
public byte[] ClientNonce { get; set; }
/// <summary>
/// Nonce option sent by server
/// </summary>
public byte[] ServerNonce { get; set; }
/// <summary>
/// FedAuthRequired Response sent by server
/// </summary>
public TdsPreLoginFedAuthRequiredOption FedAuthRequiredPreLoginServerResponse { get; set; }
/// <summary>
/// Federated authentication set of libraries to be used
/// </summary>
public TDSFedAuthLibraryType FederatedAuthenticationLibrary { get; set; }
/// <summary>
/// Counter of connection reset requests for this session
/// </summary>
public int ConnectionResetRequestCount { get; set; }
/// <summary>
/// Indicates whether this session supports transport-level recovery
/// </summary>
public bool IsSessionRecoveryEnabled { get; set; }
#region Session Options
/// <summary>
/// Controls a group of SQL Server settings that collectively specify ISO standard behavior
/// </summary>
public bool AnsiDefaults
{
get
{
// See ...\sql\ntdbms\include\typesystem\setopts.h, SetAnsiDefaults()
return AnsiNullDefaultOn && AnsiNulls && AnsiPadding && AnsiWarnings && CursorCloseOnCommit && ImplicitTransactions && QuotedIdentifier;
}
set
{
// Populate ansi defaults
AnsiNullDefaultOn = value;
AnsiNulls = value;
AnsiPadding = value;
AnsiWarnings = value;
CursorCloseOnCommit = value;
ImplicitTransactions = value;
QuotedIdentifier = value;
}
}
/// <summary>
/// Affects the nullability of new columns when the nullability of the column is not specified in the CREATE TABLE and ALTER TABLE statements.
/// </summary>
public bool AnsiNullDefaultOn { get; set; }
/// <summary>
/// Controls null behavior in T-SQL
/// </summary>
public bool AnsiNulls { get; set; }
/// <summary>
/// Impacts character column behavior (char, varchar, binary, and varbinary)
/// </summary>
public bool AnsiPadding { get; set; }
/// <summary>
/// Controls certain warning messages required for ansi compliance
/// </summary>
public bool AnsiWarnings { get; set; }
/// <summary>
/// Terminates a query when an overflow or divide-by-zero error occurs during query execution
/// </summary>
public bool ArithAbort { get; set; }
/// <summary>
/// Controls whether error messages are returned from overflow or divide-by-zero errors during a query
/// </summary>
public bool ArithIgnore { get; set; }
/// <summary>
/// Controls whether concatenation results are treated as null or empty string values
/// </summary>
public bool ConcatNullYieldsNull { get; set; }
/// <summary>
/// Associates up to 128 bytes of binary information with the current session or connection
/// </summary>
public byte[] ContextInfo { get; set; }
/// <summary>
/// Controls whether the server will close cursors when you commit a transaction
/// </summary>
public bool CursorCloseOnCommit { get; set; }
/// <summary>
/// Sets the first day of the week to a number from 1 through 7
/// </summary>
public byte DateFirst { get; set; }
/// <summary>
/// Sets the order of the month, day, and year date parts for interpreting date character strings
/// </summary>
public DateFormatType DateFormat { get; set; }
/// <summary>
/// Specifies the relative importance that the current session continue processing if it is deadlocked with another session.
/// </summary>
public int DeadlockPriority { get; set; }
/// <summary>
/// Sets implicit transaction mode for the connection
/// </summary>
public bool ImplicitTransactions { get; set; }
/// <summary>
/// Specifies the language environment for the session (language name from sys.syslanguages). The session language determines the datetime formats and system messages.
/// </summary>
public LanguageType Language { get; set; }
/// <summary>
/// Specifies the number of milliseconds a statement waits for a lock to be released
/// </summary>
public int LockTimeout { get; set; }
/// <summary>
/// Controls the emitting of Done w/count tokens from Transact-SQL.
/// </summary>
public bool NoCount { get; set; }
/// <summary>
/// Generates an error when a loss of precision occurs in an expression
/// </summary>
public bool NumericRoundAbort { get; set; }
/// <summary>
/// Causes SQL Server to follow the ISO rules regarding quotation mark delimiting identifiers and literal strings
/// </summary>
public bool QuotedIdentifier { get; set; }
/// <summary>
/// Specifies the size of varchar(max), nvarchar(max), varbinary(max), text, ntext, and image data returned by a SELECT statement
/// </summary>
public int TextSize { get; set; }
/// <summary>
/// Controls the locking and row versioning behavior of Transact-SQL statements issued by a connection to SQL Server.
/// </summary>
public TransactionIsolationLevelType TransactionIsolationLevel { get; set; }
/// <summary>
/// Specifies whether SQL Server automatically rolls back the current transaction when a Transact-SQL statement raises a run-time error
/// </summary>
public bool TransactionAbortOnError { get; set; }
#endregion
/// <summary>
/// Initialization constructor
/// </summary>
public GenericTDSServerSession(ITDSServer server, uint sessionID) :
this(server, sessionID, 4096)
{
}
/// <summary>
/// Initialization constructor
/// </summary>
public GenericTDSServerSession(ITDSServer server, uint sessionID, uint packetSize)
{
// Save the server
Server = server;
// Save session identifier
SessionID = sessionID;
// Save packet size
PacketSize = packetSize;
// By default encryption is disabled
Encryption = TDSEncryptionType.Off;
// First day of the week
DateFirst = 7;
// Transaction isolation level
TransactionIsolationLevel = TransactionIsolationLevelType.ReadCommited;
// Language
Language = LanguageType.English;
// Date format
DateFormat = DateFormatType.MonthDayYear;
// Default collation
Collation = new byte[] { 0x09, 0x04, 0xD0, 0x00, 0x34 };
// Infinite text size
TextSize = -1;
}
/// <summary>
/// Inflate the session state using options
/// </summary>
public virtual void Inflate(TDSSessionRecoveryData initial, TDSSessionRecoveryData current)
{
// Check if we have an initial state
if (initial != null)
{
// Save initial values
_InflateRecoveryData(initial);
}
// Check if we have a current value
if (current != null)
{
// Update values with current
_InflateRecoveryData(current);
}
}
/// <summary>
/// Serialize session state into a collection of options
/// </summary>
/// <returns></returns>
public virtual IList<TDSSessionStateOption> Deflate()
{
// Prepare options list
IList<TDSSessionStateOption> options = new List<TDSSessionStateOption>();
// Create user options option
TDSSessionStateUserOptionsOption userOptionsOption = new TDSSessionStateUserOptionsOption();
// Transfer properties from the session onto the session state
userOptionsOption.AnsiWarnings = AnsiWarnings;
userOptionsOption.AnsiNulls = AnsiNulls;
userOptionsOption.CursorCloseOnCommit = CursorCloseOnCommit;
userOptionsOption.QuotedIdentifier = QuotedIdentifier;
userOptionsOption.ConcatNullYieldsNull = ConcatNullYieldsNull;
userOptionsOption.AnsiNullDefaultOn = AnsiNullDefaultOn;
userOptionsOption.AnsiPadding = AnsiPadding;
userOptionsOption.ArithAbort = ArithAbort;
userOptionsOption.TransactionAbortOnError = TransactionAbortOnError;
userOptionsOption.NoCount = NoCount;
userOptionsOption.ArithIgnore = ArithIgnore;
userOptionsOption.ImplicitTransactions = ImplicitTransactions;
userOptionsOption.NumericRoundAbort = ImplicitTransactions;
// Register option with the collection
options.Add(userOptionsOption);
// Create date first/date format option
TDSSessionStateDateFirstDateFormatOption dateFirstDateFormatOption = new TDSSessionStateDateFirstDateFormatOption();
// Transfer properties from the session onto the session state
dateFirstDateFormatOption.DateFirst = DateFirst;
dateFirstDateFormatOption.DateFormat = DateFormat;
// Register option with the collection
options.Add(dateFirstDateFormatOption);
// Allocate deadlock priority option
TDSSessionStateDeadlockPriorityOption deadlockPriorityOption = new TDSSessionStateDeadlockPriorityOption();
// Transfer properties from the session onto the session state
deadlockPriorityOption.Value = (sbyte)DeadlockPriority;
// Register option with the collection
options.Add(deadlockPriorityOption);
// Allocate lock timeout option
TDSSessionStateLockTimeoutOption lockTimeoutOption = new TDSSessionStateLockTimeoutOption();
// Transfer properties from the session onto the session state
lockTimeoutOption.Value = LockTimeout;
// Register option with the collection
options.Add(lockTimeoutOption);
// Allocate ISO fips option
TDSSessionStateISOFipsOption isoFipsOption = new TDSSessionStateISOFipsOption();
// Transfer properties from the session onto the session state
isoFipsOption.TransactionIsolationLevel = TransactionIsolationLevel;
// Register option with the collection
options.Add(isoFipsOption);
// Allocate text size option
TDSSessionStateTextSizeOption textSizeOption = new TDSSessionStateTextSizeOption();
// Transfer properties from the session onto the session state
textSizeOption.Value = TextSize;
// Register option with the collection
options.Add(textSizeOption);
// Check if context info is specified
if (ContextInfo != null)
{
// Allocate context info option
TDSSessionStateContextInfoOption contextInfoOption = new TDSSessionStateContextInfoOption();
// Transfer properties from the session onto the session state
contextInfoOption.Value = ContextInfo;
// Register option with the collection
options.Add(isoFipsOption);
}
return options;
}
/// <summary>
/// Inflate recovery data
/// </summary>
private void _InflateRecoveryData(TDSSessionRecoveryData data)
{
// Check if database is available
if (data.Database != null)
{
// Apply database
Database = data.Database;
}
// Check if language is available
if (data.Language != null)
{
// Apply language
Language = LanguageString.ToEnum(data.Language);
}
// Check if collation is available
if (data.Collation != null)
{
Collation = data.Collation;
}
// Traverse all session states and inflate each separately
foreach (TDSSessionStateOption option in data.Options)
{
// Check on the options
if (option is TDSSessionStateUserOptionsOption)
{
// Cast to specific option
TDSSessionStateUserOptionsOption specificOption = option as TDSSessionStateUserOptionsOption;
// Transfer properties from the session state onto the session
AnsiWarnings = specificOption.AnsiWarnings;
AnsiNulls = specificOption.AnsiNulls;
CursorCloseOnCommit = specificOption.CursorCloseOnCommit;
QuotedIdentifier = specificOption.QuotedIdentifier;
ConcatNullYieldsNull = specificOption.ConcatNullYieldsNull;
AnsiNullDefaultOn = specificOption.AnsiNullDefaultOn;
AnsiPadding = specificOption.AnsiPadding;
ArithAbort = specificOption.ArithAbort;
TransactionAbortOnError = specificOption.TransactionAbortOnError;
NoCount = specificOption.NoCount;
ArithIgnore = specificOption.ArithIgnore;
ImplicitTransactions = specificOption.ImplicitTransactions;
NumericRoundAbort = specificOption.NumericRoundAbort;
}
else if (option is TDSSessionStateDateFirstDateFormatOption)
{
// Cast to specific option
TDSSessionStateDateFirstDateFormatOption specificOption = option as TDSSessionStateDateFirstDateFormatOption;
// Transfer properties from the session state onto the session
DateFirst = specificOption.DateFirst;
DateFormat = specificOption.DateFormat;
}
else if (option is TDSSessionStateDeadlockPriorityOption)
{
// Cast to specific option
TDSSessionStateDeadlockPriorityOption specificOption = option as TDSSessionStateDeadlockPriorityOption;
// Transfer properties from the session state onto the session
DeadlockPriority = specificOption.Value;
}
else if (option is TDSSessionStateLockTimeoutOption)
{
// Cast to specific option
TDSSessionStateLockTimeoutOption specificOption = option as TDSSessionStateLockTimeoutOption;
// Transfer properties from the session state onto the session
LockTimeout = specificOption.Value;
}
else if (option is TDSSessionStateISOFipsOption)
{
// Cast to specific option
TDSSessionStateISOFipsOption specificOption = option as TDSSessionStateISOFipsOption;
// Transfer properties from the session state onto the session
TransactionIsolationLevel = specificOption.TransactionIsolationLevel;
}
else if (option is TDSSessionStateTextSizeOption)
{
// Cast to specific option
TDSSessionStateTextSizeOption specificOption = option as TDSSessionStateTextSizeOption;
// Transfer properties from the session state onto the session
TextSize = specificOption.Value;
}
else if (option is TDSSessionStateContextInfoOption)
{
// Cast to specific option
TDSSessionStateContextInfoOption specificOption = option as TDSSessionStateContextInfoOption;
// Transfer properties from the session state onto the session
ContextInfo = specificOption.Value;
}
}
}
}
}
| |
namespace android.media
{
[global::MonoJavaBridge.JavaClass()]
public partial class AudioTrack : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static AudioTrack()
{
InitJNI();
}
protected AudioTrack(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_))]
public interface OnPlaybackPositionUpdateListener : global::MonoJavaBridge.IJavaObject
{
void onMarkerReached(android.media.AudioTrack arg0);
void onPeriodicNotification(android.media.AudioTrack arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.AudioTrack.OnPlaybackPositionUpdateListener))]
public sealed partial class OnPlaybackPositionUpdateListener_ : java.lang.Object, OnPlaybackPositionUpdateListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnPlaybackPositionUpdateListener_()
{
InitJNI();
}
internal OnPlaybackPositionUpdateListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onMarkerReached4890;
void android.media.AudioTrack.OnPlaybackPositionUpdateListener.onMarkerReached(android.media.AudioTrack arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._onMarkerReached4890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._onMarkerReached4890, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onPeriodicNotification4891;
void android.media.AudioTrack.OnPlaybackPositionUpdateListener.onPeriodicNotification(android.media.AudioTrack arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._onPeriodicNotification4891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._onPeriodicNotification4891, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioTrack$OnPlaybackPositionUpdateListener"));
global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._onMarkerReached4890 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass, "onMarkerReached", "(Landroid/media/AudioTrack;)V");
global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._onPeriodicNotification4891 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass, "onPeriodicNotification", "(Landroid/media/AudioTrack;)V");
}
}
internal static global::MonoJavaBridge.MethodId _finalize4892;
protected override void finalize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._finalize4892);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._finalize4892);
}
internal static global::MonoJavaBridge.MethodId _write4893;
public virtual int write(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._write4893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._write4893, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _write4894;
public virtual int write(short[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._write4894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._write4894, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _stop4895;
public virtual void stop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._stop4895);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._stop4895);
}
internal static global::MonoJavaBridge.MethodId _getState4896;
public virtual int getState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getState4896);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getState4896);
}
internal static global::MonoJavaBridge.MethodId _flush4897;
public virtual void flush()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._flush4897);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._flush4897);
}
internal static global::MonoJavaBridge.MethodId _setState4898;
protected virtual void setState(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._setState4898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setState4898, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _release4899;
public virtual void release()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._release4899);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._release4899);
}
internal static global::MonoJavaBridge.MethodId _play4900;
public virtual void play()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._play4900);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._play4900);
}
internal static global::MonoJavaBridge.MethodId _getSampleRate4901;
public virtual int getSampleRate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getSampleRate4901);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getSampleRate4901);
}
internal static global::MonoJavaBridge.MethodId _getAudioFormat4902;
public virtual int getAudioFormat()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getAudioFormat4902);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getAudioFormat4902);
}
internal static global::MonoJavaBridge.MethodId _getChannelConfiguration4903;
public virtual int getChannelConfiguration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getChannelConfiguration4903);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getChannelConfiguration4903);
}
internal static global::MonoJavaBridge.MethodId _getChannelCount4904;
public virtual int getChannelCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getChannelCount4904);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getChannelCount4904);
}
internal static global::MonoJavaBridge.MethodId _getNotificationMarkerPosition4905;
public virtual int getNotificationMarkerPosition()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getNotificationMarkerPosition4905);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getNotificationMarkerPosition4905);
}
internal static global::MonoJavaBridge.MethodId _getPositionNotificationPeriod4906;
public virtual int getPositionNotificationPeriod()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getPositionNotificationPeriod4906);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getPositionNotificationPeriod4906);
}
internal static global::MonoJavaBridge.MethodId _getMinBufferSize4907;
public static int getMinBufferSize(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getMinBufferSize4907, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setNotificationMarkerPosition4908;
public virtual int setNotificationMarkerPosition(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._setNotificationMarkerPosition4908, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setNotificationMarkerPosition4908, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPositionNotificationPeriod4909;
public virtual int setPositionNotificationPeriod(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._setPositionNotificationPeriod4909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setPositionNotificationPeriod4909, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getMinVolume4910;
public static float getMinVolume()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getMinVolume4910);
}
internal static global::MonoJavaBridge.MethodId _getMaxVolume4911;
public static float getMaxVolume()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticFloatMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getMaxVolume4911);
}
internal static global::MonoJavaBridge.MethodId _getPlaybackRate4912;
public virtual int getPlaybackRate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getPlaybackRate4912);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getPlaybackRate4912);
}
internal static global::MonoJavaBridge.MethodId _getStreamType4913;
public virtual int getStreamType()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getStreamType4913);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getStreamType4913);
}
internal static global::MonoJavaBridge.MethodId _getPlayState4914;
public virtual int getPlayState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getPlayState4914);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getPlayState4914);
}
internal static global::MonoJavaBridge.MethodId _getNativeFrameCount4915;
protected virtual int getNativeFrameCount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getNativeFrameCount4915);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getNativeFrameCount4915);
}
internal static global::MonoJavaBridge.MethodId _getPlaybackHeadPosition4916;
public virtual int getPlaybackHeadPosition()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._getPlaybackHeadPosition4916);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getPlaybackHeadPosition4916);
}
internal static global::MonoJavaBridge.MethodId _getNativeOutputSampleRate4917;
public static int getNativeOutputSampleRate(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._getNativeOutputSampleRate4917, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPlaybackPositionUpdateListener4918;
public virtual void setPlaybackPositionUpdateListener(android.media.AudioTrack.OnPlaybackPositionUpdateListener arg0, android.os.Handler arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._setPlaybackPositionUpdateListener4918, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setPlaybackPositionUpdateListener4918, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setPlaybackPositionUpdateListener4919;
public virtual void setPlaybackPositionUpdateListener(android.media.AudioTrack.OnPlaybackPositionUpdateListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._setPlaybackPositionUpdateListener4919, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setPlaybackPositionUpdateListener4919, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setStereoVolume4920;
public virtual int setStereoVolume(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._setStereoVolume4920, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setStereoVolume4920, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setPlaybackRate4921;
public virtual int setPlaybackRate(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._setPlaybackRate4921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setPlaybackRate4921, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPlaybackHeadPosition4922;
public virtual int setPlaybackHeadPosition(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._setPlaybackHeadPosition4922, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setPlaybackHeadPosition4922, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setLoopPoints4923;
public virtual int setLoopPoints(int arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._setLoopPoints4923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._setLoopPoints4923, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _pause4924;
public virtual void pause()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.AudioTrack._pause4924);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._pause4924);
}
internal static global::MonoJavaBridge.MethodId _reloadStaticData4925;
public virtual int reloadStaticData()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.AudioTrack._reloadStaticData4925);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.AudioTrack.staticClass, global::android.media.AudioTrack._reloadStaticData4925);
}
internal static global::MonoJavaBridge.MethodId _AudioTrack4926;
public AudioTrack(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._AudioTrack4926, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5));
Init(@__env, handle);
}
public static int PLAYSTATE_STOPPED
{
get
{
return 1;
}
}
public static int PLAYSTATE_PAUSED
{
get
{
return 2;
}
}
public static int PLAYSTATE_PLAYING
{
get
{
return 3;
}
}
public static int MODE_STATIC
{
get
{
return 0;
}
}
public static int MODE_STREAM
{
get
{
return 1;
}
}
public static int STATE_UNINITIALIZED
{
get
{
return 0;
}
}
public static int STATE_INITIALIZED
{
get
{
return 1;
}
}
public static int STATE_NO_STATIC_DATA
{
get
{
return 2;
}
}
public static int SUCCESS
{
get
{
return 0;
}
}
public static int ERROR
{
get
{
return -1;
}
}
public static int ERROR_BAD_VALUE
{
get
{
return -2;
}
}
public static int ERROR_INVALID_OPERATION
{
get
{
return -3;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.AudioTrack.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioTrack"));
global::android.media.AudioTrack._finalize4892 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "finalize", "()V");
global::android.media.AudioTrack._write4893 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "write", "([BII)I");
global::android.media.AudioTrack._write4894 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "write", "([SII)I");
global::android.media.AudioTrack._stop4895 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "stop", "()V");
global::android.media.AudioTrack._getState4896 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getState", "()I");
global::android.media.AudioTrack._flush4897 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "flush", "()V");
global::android.media.AudioTrack._setState4898 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setState", "(I)V");
global::android.media.AudioTrack._release4899 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "release", "()V");
global::android.media.AudioTrack._play4900 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "play", "()V");
global::android.media.AudioTrack._getSampleRate4901 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getSampleRate", "()I");
global::android.media.AudioTrack._getAudioFormat4902 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getAudioFormat", "()I");
global::android.media.AudioTrack._getChannelConfiguration4903 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getChannelConfiguration", "()I");
global::android.media.AudioTrack._getChannelCount4904 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getChannelCount", "()I");
global::android.media.AudioTrack._getNotificationMarkerPosition4905 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getNotificationMarkerPosition", "()I");
global::android.media.AudioTrack._getPositionNotificationPeriod4906 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getPositionNotificationPeriod", "()I");
global::android.media.AudioTrack._getMinBufferSize4907 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getMinBufferSize", "(III)I");
global::android.media.AudioTrack._setNotificationMarkerPosition4908 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setNotificationMarkerPosition", "(I)I");
global::android.media.AudioTrack._setPositionNotificationPeriod4909 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setPositionNotificationPeriod", "(I)I");
global::android.media.AudioTrack._getMinVolume4910 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getMinVolume", "()F");
global::android.media.AudioTrack._getMaxVolume4911 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getMaxVolume", "()F");
global::android.media.AudioTrack._getPlaybackRate4912 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getPlaybackRate", "()I");
global::android.media.AudioTrack._getStreamType4913 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getStreamType", "()I");
global::android.media.AudioTrack._getPlayState4914 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getPlayState", "()I");
global::android.media.AudioTrack._getNativeFrameCount4915 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getNativeFrameCount", "()I");
global::android.media.AudioTrack._getPlaybackHeadPosition4916 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getPlaybackHeadPosition", "()I");
global::android.media.AudioTrack._getNativeOutputSampleRate4917 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getNativeOutputSampleRate", "(I)I");
global::android.media.AudioTrack._setPlaybackPositionUpdateListener4918 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setPlaybackPositionUpdateListener", "(Landroid/media/AudioTrack$OnPlaybackPositionUpdateListener;Landroid/os/Handler;)V");
global::android.media.AudioTrack._setPlaybackPositionUpdateListener4919 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setPlaybackPositionUpdateListener", "(Landroid/media/AudioTrack$OnPlaybackPositionUpdateListener;)V");
global::android.media.AudioTrack._setStereoVolume4920 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setStereoVolume", "(FF)I");
global::android.media.AudioTrack._setPlaybackRate4921 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setPlaybackRate", "(I)I");
global::android.media.AudioTrack._setPlaybackHeadPosition4922 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setPlaybackHeadPosition", "(I)I");
global::android.media.AudioTrack._setLoopPoints4923 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "setLoopPoints", "(III)I");
global::android.media.AudioTrack._pause4924 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "pause", "()V");
global::android.media.AudioTrack._reloadStaticData4925 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "reloadStaticData", "()I");
global::android.media.AudioTrack._AudioTrack4926 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "<init>", "(IIIIII)V");
}
}
}
| |
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony
{
public class Dictionary<K, V> : global::haxe.lang.HxObject, global::pony.Dictionary
{
public Dictionary(global::haxe.lang.EmptyObject empty)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
{
}
}
#line default
}
public Dictionary(global::haxe.lang.Null<int> maxDepth)
{
unchecked
{
#line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
global::pony.Dictionary<object, object>.__hx_ctor_pony_Dictionary<K, V>(this, maxDepth);
}
#line default
}
public static void __hx_ctor_pony_Dictionary<K_c, V_c>(global::pony.Dictionary<K_c, V_c> __temp_me84, global::haxe.lang.Null<int> maxDepth)
{
unchecked
{
#line 46 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
int __temp_maxDepth83 = ( (global::haxe.lang.Runtime.eq((maxDepth).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (1) )) : (maxDepth.@value) );
__temp_me84.maxDepth = __temp_maxDepth83;
{
#line 48 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
__temp_me84.ks = new global::Array<K_c>(new K_c[]{});
#line 48 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
__temp_me84.vs = new global::Array<V_c>(new V_c[]{});
}
}
#line default
}
public static object __hx_cast<K_c_c, V_c_c>(global::pony.Dictionary me)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ( (( me != default(global::pony.Dictionary) )) ? (me.pony_Dictionary_cast<K_c_c, V_c_c>()) : (default(global::pony.Dictionary)) );
}
#line default
}
public static new object __hx_createEmpty()
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return new global::pony.Dictionary<object, object>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
}
#line default
}
public static new object __hx_create(global::Array arr)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return new global::pony.Dictionary<object, object>(global::haxe.lang.Null<object>.ofDynamic<int>(arr[0]));
}
#line default
}
public virtual object pony_Dictionary_cast<K_c, V_c>()
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
if (( global::haxe.lang.Runtime.eq(typeof(K), typeof(K_c)) && global::haxe.lang.Runtime.eq(typeof(V), typeof(V_c)) ))
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this;
}
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
global::pony.Dictionary<K_c, V_c> new_me = new global::pony.Dictionary<K_c, V_c>(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) ));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
object __temp_iterator180 = global::Reflect.fields(this).iterator();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator180, "hasNext", 407283053, default(global::Array))) ))
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
string field = global::haxe.lang.Runtime.toString(global::haxe.lang.Runtime.callField(__temp_iterator180, "next", 1224901875, default(global::Array)));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
switch (field)
{
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
global::Reflect.setField(new_me, field, ((object) (global::Reflect.field(this, field)) ));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
break;
}
}
}
}
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return new_me;
}
#line default
}
public global::Array<K> ks;
public global::Array<V> vs;
public int count;
public int maxDepth;
public int getIndex(K k)
{
unchecked
{
#line 51 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return global::pony.Tools.superIndexOf<K>(this.ks, k, new global::haxe.lang.Null<int>(this.maxDepth, true));
}
#line default
}
public virtual void @set(K k, V v)
{
unchecked
{
#line 54 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
int i = global::pony.Tools.superIndexOf<K>(this.ks, k, new global::haxe.lang.Null<int>(this.maxDepth, true));
if (( i != -1 ))
{
this.vs[i] = v;
}
else
{
#line 58 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.ks.push(k);
this.vs.push(v);
}
}
#line default
}
public virtual V @get(K k)
{
unchecked
{
#line 64 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
int i = global::pony.Tools.superIndexOf<K>(this.ks, k, new global::haxe.lang.Null<int>(this.maxDepth, true));
if (( i == -1 ))
{
return default(V);
}
else
{
#line 68 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.vs[i];
}
}
#line default
}
public bool exists(K k)
{
unchecked
{
#line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ( global::pony.Tools.superIndexOf<K>(this.ks, k, new global::haxe.lang.Null<int>(this.maxDepth, true)) != -1 );
}
#line default
}
public virtual bool @remove(K k)
{
unchecked
{
#line 74 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
int i = global::pony.Tools.superIndexOf<K>(this.ks, k, new global::haxe.lang.Null<int>(this.maxDepth, true));
if (( i != -1 ))
{
this.ks.splice(i, 1);
this.vs.splice(i, 1);
return true;
}
else
{
#line 80 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return false;
}
}
#line default
}
public void clear()
{
unchecked
{
#line 84 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.ks = new global::Array<K>(new K[]{});
this.vs = new global::Array<V>(new V[]{});
}
#line default
}
public object iterator()
{
unchecked
{
#line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.vs.iterator();
}
#line default
}
public object keys()
{
unchecked
{
#line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.ks.iterator();
}
#line default
}
public virtual string toString()
{
unchecked
{
#line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
global::Array<object> a = new global::Array<object>(new object[]{});
{
#line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
object __temp_iterator181 = this.ks.iterator();
#line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator181, "hasNext", 407283053, default(global::Array))) ))
{
#line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
K k = global::haxe.lang.Runtime.genericCast<K>(global::haxe.lang.Runtime.callField(__temp_iterator181, "next", 1224901875, default(global::Array)));
a.push(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(global::Std.@string(k), ": "), global::Std.@string(this.@get(k))));
}
}
#line 97 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat("[", a.@join(", ")), "]");
}
#line default
}
public virtual void removeValue(V v)
{
unchecked
{
#line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
int i = global::Lambda.indexOf<V>(this.vs, v);
if (( i != -1 ))
{
this.ks.splice(i, 1);
this.vs.splice(i, 1);
}
}
#line default
}
public int _get_count()
{
unchecked
{
#line 108 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.ks.length;
}
#line default
}
public override double __hx_setField_f(string field, int hash, double @value, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
switch (hash)
{
case 21447615:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.maxDepth = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return @value;
}
case 1248019663:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.count = ((int) (@value) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return @value;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return base.__hx_setField_f(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_setField(string field, int hash, object @value, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
switch (hash)
{
case 21447615:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.maxDepth = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return @value;
}
case 1248019663:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.count = ((int) (global::haxe.lang.Runtime.toInt(@value)) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return @value;
}
case 26429:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.vs = ((global::Array<V>) (global::Array<object>.__hx_cast<V>(((global::Array) (@value) ))) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return @value;
}
case 23976:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.ks = ((global::Array<K>) (global::Array<object>.__hx_cast<K>(((global::Array) (@value) ))) );
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return @value;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return base.__hx_setField(field, hash, @value, handleProperties);
}
}
}
#line default
}
public override object __hx_getField(string field, int hash, bool throwErrors, bool isCheck, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
switch (hash)
{
case 235708710:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("get_count"), ((int) (235708710) ))) );
}
case 804019341:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("removeValue"), ((int) (804019341) ))) );
}
case 946786476:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("toString"), ((int) (946786476) ))) );
}
case 1191633396:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("keys"), ((int) (1191633396) ))) );
}
case 328878574:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("iterator"), ((int) (328878574) ))) );
}
case 1213952397:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("clear"), ((int) (1213952397) ))) );
}
case 76061764:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("remove"), ((int) (76061764) ))) );
}
case 1071652316:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("exists"), ((int) (1071652316) ))) );
}
case 5144726:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("get"), ((int) (5144726) ))) );
}
case 5741474:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("set"), ((int) (5741474) ))) );
}
case 501983900:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((global::haxe.lang.Function) (new global::haxe.lang.Closure(((object) (this) ), global::haxe.lang.Runtime.toString("getIndex"), ((int) (501983900) ))) );
}
case 21447615:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.maxDepth;
}
case 1248019663:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
if (handleProperties)
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this._get_count();
}
else
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.count;
}
}
case 26429:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.vs;
}
case 23976:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.ks;
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return base.__hx_getField(field, hash, throwErrors, isCheck, handleProperties);
}
}
}
#line default
}
public override double __hx_getField_f(string field, int hash, bool throwErrors, bool handleProperties)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
switch (hash)
{
case 21447615:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((double) (this.maxDepth) );
}
case 1248019663:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
if (handleProperties)
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((double) (this._get_count()) );
}
else
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return ((double) (this.count) );
}
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return base.__hx_getField_f(field, hash, throwErrors, handleProperties);
}
}
}
#line default
}
public override object __hx_invokeField(string field, int hash, global::Array dynargs)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
switch (hash)
{
case 235708710:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this._get_count();
}
case 804019341:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.removeValue(global::haxe.lang.Runtime.genericCast<V>(dynargs[0]));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
break;
}
case 946786476:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.toString();
}
case 1191633396:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.keys();
}
case 328878574:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.iterator();
}
case 1213952397:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.clear();
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
break;
}
case 76061764:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.@remove(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]));
}
case 1071652316:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.exists(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]));
}
case 5144726:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.@get(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]));
}
case 5741474:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
this.@set(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]), global::haxe.lang.Runtime.genericCast<V>(dynargs[1]));
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
break;
}
case 501983900:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return this.getIndex(global::haxe.lang.Runtime.genericCast<K>(dynargs[0]));
}
default:
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return base.__hx_invokeField(field, hash, dynargs);
}
}
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
return default(object);
}
#line default
}
public override void __hx_getFields(global::Array<object> baseArr)
{
unchecked
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
baseArr.push("maxDepth");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
baseArr.push("count");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
baseArr.push("vs");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
baseArr.push("ks");
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
{
#line 37 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Dictionary.hx"
base.__hx_getFields(baseArr);
}
}
#line default
}
public override string ToString()
{
return this.toString();
}
}
}
#pragma warning disable 109, 114, 219, 429, 168, 162
namespace pony
{
public interface Dictionary : global::haxe.lang.IHxObject, global::haxe.lang.IGenericObject
{
object pony_Dictionary_cast<K_c, V_c>();
}
}
| |
// 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.Linq.Tests
{
public class OrderByTests : EnumerableTests
{
private class BadComparer1 : IComparer<int>
{
public int Compare(int x, int y)
{
return 1;
}
}
private class BadComparer2 : IComparer<int>
{
public int Compare(int x, int y)
{
return -1;
}
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
var q = from x1 in new int[] { 1, 6, 0, -1, 3 }
from x2 in new int[] { 55, 49, 9, -100, 24, 25 }
select new { a1 = x1, a2 = x2 };
Assert.Equal(q.OrderBy(e => e.a1).ThenBy(f => f.a2), q.OrderBy(e => e.a1).ThenBy(f => f.a2));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
var q = from x1 in new[] { 55, 49, 9, -100, 24, 25, -1, 0 }
from x2 in new[] { "!@#$%^", "C", "AAA", "", null, "Calling Twice", "SoS", string.Empty }
where !string.IsNullOrEmpty(x2)
select new { a1 = x1, a2 = x2 };
Assert.Equal(q.OrderBy(e => e.a1), q.OrderBy(e => e.a1));
}
[Fact]
public void SourceEmpty()
{
int[] source = { };
Assert.Empty(source.OrderBy(e => e));
}
[Fact]
public void OrderedCount()
{
var source = Enumerable.Range(0, 20).Shuffle();
Assert.Equal(20, source.OrderBy(i => i).Count());
}
//FIXME: This will hang with a larger source. Do we want to deal with that case?
[Fact]
public void SurviveBadComparerAlwaysReturnsNegative()
{
int[] source = { 1 };
int[] expected = { 1 };
Assert.Equal(expected, source.OrderBy(e => e, new BadComparer2()));
}
[Fact]
public void KeySelectorReturnsNull()
{
int?[] source = { null, null, null };
int?[] expected = { null, null, null };
Assert.Equal(expected, source.OrderBy(e => e));
}
[Fact]
public void ElementsAllSameKey()
{
int?[] source = { 9, 9, 9, 9, 9, 9 };
int?[] expected = { 9, 9, 9, 9, 9, 9 };
Assert.Equal(expected, source.OrderBy(e => e));
}
[Fact]
public void KeySelectorCalled()
{
var source = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 45 },
new { Name = "Prakash", Score = 99 }
};
var expected = new[]
{
new { Name = "Prakash", Score = 99 },
new { Name = "Robert", Score = 45 },
new { Name = "Tim", Score = 90 }
};
Assert.Equal(expected, source.OrderBy(e => e.Name, null));
}
[Fact]
public void FirstAndLastAreDuplicatesCustomComparer()
{
string[] source = { "Prakash", "Alpha", "dan", "DAN", "Prakash" };
string[] expected = { "Alpha", "dan", "DAN", "Prakash", "Prakash" };
Assert.Equal(expected, source.OrderBy(e => e, StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void RunOnce()
{
string[] source = { "Prakash", "Alpha", "dan", "DAN", "Prakash" };
string[] expected = { "Alpha", "dan", "DAN", "Prakash", "Prakash" };
Assert.Equal(expected, source.RunOnce().OrderBy(e => e, StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void FirstAndLastAreDuplicatesNullPassedAsComparer()
{
int[] source = { 5, 1, 3, 2, 5 };
int[] expected = { 1, 2, 3, 5, 5 };
Assert.Equal(expected, source.OrderBy(e => e, null));
}
[Fact]
public void SourceReverseOfResultNullPassedAsComparer()
{
int?[] source = { 100, 30, 9, 5, 0, -50, -75, null };
int?[] expected = { null, -75, -50, 0, 5, 9, 30, 100 };
Assert.Equal(expected, source.OrderBy(e => e, null));
}
[Fact]
public void SameKeysVerifySortStable()
{
var source = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
var expected = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
Assert.Equal(expected, source.OrderBy(e => e.Score));
}
[Fact]
public void OrderedToArray()
{
var source = new []
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
var expected = new []
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
Assert.Equal(expected, source.OrderBy(e => e.Score).ToArray());
}
[Fact]
public void EmptyOrderedToArray()
{
Assert.Empty(Enumerable.Empty<int>().OrderBy(e => e).ToArray());
}
[Fact]
public void OrderedToList()
{
var source = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
var expected = new[]
{
new { Name = "Tim", Score = 90 },
new { Name = "Robert", Score = 90 },
new { Name = "Prakash", Score = 90 },
new { Name = "Jim", Score = 90 },
new { Name = "John", Score = 90 },
new { Name = "Albert", Score = 90 },
};
Assert.Equal(expected, source.OrderBy(e => e.Score).ToList());
}
[Fact]
public void EmptyOrderedToList()
{
Assert.Empty(Enumerable.Empty<int>().OrderBy(e => e).ToList());
}
//FIXME: This will hang with a larger source. Do we want to deal with that case?
[Fact]
public void SurviveBadComparerAlwaysReturnsPositive()
{
int[] source = { 1 };
int[] expected = { 1 };
Assert.Equal(expected, source.OrderBy(e => e, new BadComparer1()));
}
private class ExtremeComparer : IComparer<int>
{
public int Compare(int x, int y)
{
if (x == y)
return 0;
if (x < y)
return int.MinValue;
return int.MaxValue;
}
}
[Fact]
public void OrderByExtremeComparer()
{
var outOfOrder = new[] { 7, 1, 0, 9, 3, 5, 4, 2, 8, 6 };
Assert.Equal(Enumerable.Range(0, 10), outOfOrder.OrderBy(i => i, new ExtremeComparer()));
}
[Fact]
public void NullSource()
{
IEnumerable<int> source = null;
AssertExtensions.Throws<ArgumentNullException>("source", () => source.OrderBy(i => i));
}
[Fact]
public void NullKeySelector()
{
Func<DateTime, int> keySelector = null;
AssertExtensions.Throws<ArgumentNullException>("keySelector", () => Enumerable.Empty<DateTime>().OrderBy(keySelector));
}
[Fact]
public void FirstOnOrdered()
{
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).First());
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).First());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderByDescending(i => i.ToString().Length).ThenBy(i => i).First());
}
[Fact]
public void FirstOnEmptyOrderedThrows()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).First());
}
[Fact]
public void FirstOrDefaultOnOrdered()
{
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).FirstOrDefault());
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).FirstOrDefault());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderByDescending(i => i.ToString().Length).ThenBy(i => i).FirstOrDefault());
Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).FirstOrDefault());
}
[Fact]
public void LastOnOrdered()
{
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).Last());
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).Last());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).Last());
}
[Fact]
public void LastOnOrderedMatchingCases()
{
object[] boxedInts = new object[] {0, 1, 2, 9, 1, 2, 3, 9, 4, 5, 7, 8, 9, 0, 1};
Assert.Same(boxedInts[12], boxedInts.OrderBy(o => (int)o).Last());
Assert.Same(boxedInts[12], boxedInts.OrderBy(o => (int)o).LastOrDefault());
Assert.Same(boxedInts[12], boxedInts.OrderBy(o => (int)o).Last(o => (int)o % 2 == 1));
Assert.Same(boxedInts[12], boxedInts.OrderBy(o => (int)o).LastOrDefault(o => (int)o % 2 == 1));
}
[Fact]
public void LastOnEmptyOrderedThrows()
{
Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().OrderBy(i => i).Last());
}
[Fact]
public void LastOrDefaultOnOrdered()
{
Assert.Equal(9, Enumerable.Range(0, 10).Shuffle().OrderBy(i => i).LastOrDefault());
Assert.Equal(0, Enumerable.Range(0, 10).Shuffle().OrderByDescending(i => i).LastOrDefault());
Assert.Equal(10, Enumerable.Range(0, 100).Shuffle().OrderBy(i => i.ToString().Length).ThenByDescending(i => i).LastOrDefault());
Assert.Equal(0, Enumerable.Empty<int>().OrderBy(i => i).LastOrDefault());
}
[Fact]
public void EnumeratorDoesntContinue()
{
var enumerator = NumberRangeGuaranteedNotCollectionType(0, 3).Shuffle().OrderBy(i => i).GetEnumerator();
while (enumerator.MoveNext()) { }
Assert.False(enumerator.MoveNext());
}
[Fact]
public void OrderByIsCovariantTestWithCast()
{
var ordered = Enumerable.Range(0, 100).Select(i => i.ToString()).OrderBy(i => i.Length);
IOrderedEnumerable<IComparable> covariantOrdered = ordered;
covariantOrdered = covariantOrdered.ThenBy(i => i);
string[] expected =
Enumerable.Range(0, 100).Select(i => i.ToString()).OrderBy(i => i.Length).ThenBy(i => i).ToArray();
Assert.Equal(expected, covariantOrdered);
}
[Fact]
public void OrderByIsCovariantTestWithAssignToArgument()
{
var ordered = Enumerable.Range(0, 100).Select(i => i.ToString()).OrderBy(i => i.Length);
IOrderedEnumerable<IComparable> covariantOrdered = ordered.ThenByDescending<IComparable, IComparable>(i => i);
string[] expected = Enumerable.Range(0, 100)
.Select(i => i.ToString())
.OrderBy(i => i.Length)
.ThenByDescending(i => i)
.ToArray();
Assert.Equal(expected, covariantOrdered);
}
[Fact]
public void CanObtainFromCovariantIOrderedQueryable()
{
// If an ordered queryable is cast covariantly and then has ThenBy() called on it,
// it depends on IOrderedEnumerable<TElement> also being covariant to allow for
// that ThenBy() to be processed within Linq-to-objects, as otherwise there is no
// equivalent ThenBy() overload to translate the call to.
IOrderedQueryable<IComparable> ordered =
Enumerable.Range(0, 100).AsQueryable().Select(i => i.ToString()).OrderBy(i => i.Length);
ordered = ordered.ThenBy(i => i);
string[] expected =
Enumerable.Range(0, 100).Select(i => i.ToString()).OrderBy(i => i.Length).ThenBy(i => i).ToArray();
Assert.Equal(expected, ordered);
}
[Fact]
public void SortsLargeAscendingEnumerableCorrectly()
{
const int Items = 1_000_000;
IEnumerable<int> expected = NumberRangeGuaranteedNotCollectionType(0, Items);
IEnumerable<int> unordered = expected.Select(i => i);
IOrderedEnumerable<int> ordered = unordered.OrderBy(i => i);
Assert.Equal(expected, ordered);
}
[Fact]
public void SortsLargeDescendingEnumerableCorrectly()
{
const int Items = 1_000_000;
IEnumerable<int> expected = NumberRangeGuaranteedNotCollectionType(0, Items);
IEnumerable<int> unordered = expected.Select(i => Items - i - 1);
IOrderedEnumerable<int> ordered = unordered.OrderBy(i => i);
Assert.Equal(expected, ordered);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(8)]
[InlineData(16)]
[InlineData(1024)]
[InlineData(4096)]
[InlineData(1_000_000)]
public void SortsRandomizedEnumerableCorrectly(int items)
{
var r = new Random(42);
int[] randomized = Enumerable.Range(0, items).Select(i => r.Next()).ToArray();
int[] ordered = ForceNotCollection(randomized).OrderBy(i => i).ToArray();
Array.Sort(randomized);
Assert.Equal(randomized, ordered);
}
[Theory]
[InlineData(new[] { 1 })]
[InlineData(new[] { 1, 2 })]
[InlineData(new[] { 2, 1 })]
[InlineData(new[] { 1, 2, 3, 4, 5 })]
[InlineData(new[] { 5, 4, 3, 2, 1 })]
[InlineData(new[] { 4, 3, 2, 1, 5, 9, 8, 7, 6 })]
[InlineData(new[] { 2, 4, 6, 8, 10, 5, 3, 7, 1, 9 })]
public void TakeOne(IEnumerable<int> source)
{
int count = 0;
foreach (int x in source.OrderBy(i => i).Take(1))
{
count++;
Assert.Equal(source.Min(), x);
}
Assert.Equal(1, count);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2015 Tim Stair
//
// 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 CardMaker.Forms
{
partial class MDICanvas
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MDICanvas));
this.numericUpDownZoom = new System.Windows.Forms.NumericUpDown();
this.toolStrip = new System.Windows.Forms.ToolStrip();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.verticalCenterButton = new System.Windows.Forms.ToolStripButton();
this.horizontalCenterButton = new System.Windows.Forms.ToolStripButton();
this.customAlignButton = new System.Windows.Forms.ToolStripButton();
this.customVerticalAlignButton = new System.Windows.Forms.ToolStripButton();
this.customHoritonalAlignButton = new System.Windows.Forms.ToolStripButton();
this.panelCardCanvas = new Support.UI.PanelEx();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownZoom)).BeginInit();
this.toolStrip.SuspendLayout();
this.SuspendLayout();
//
// numericUpDownZoom
//
this.numericUpDownZoom.DecimalPlaces = 2;
this.numericUpDownZoom.Increment = new decimal(new int[] {
25,
0,
0,
131072});
this.numericUpDownZoom.Location = new System.Drawing.Point(4, 2);
this.numericUpDownZoom.Maximum = new decimal(new int[] {
1000,
0,
0,
131072});
this.numericUpDownZoom.Minimum = new decimal(new int[] {
25,
0,
0,
131072});
this.numericUpDownZoom.Name = "numericUpDownZoom";
this.numericUpDownZoom.Size = new System.Drawing.Size(59, 20);
this.numericUpDownZoom.TabIndex = 0;
this.numericUpDownZoom.TabStop = false;
this.numericUpDownZoom.Value = new decimal(new int[] {
100,
0,
0,
131072});
this.numericUpDownZoom.ValueChanged += new System.EventHandler(this.numericUpDownZoom_ValueChanged);
//
// toolStrip
//
this.toolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel1,
this.toolStripSeparator1,
this.verticalCenterButton,
this.customVerticalAlignButton,
this.horizontalCenterButton,
this.customHoritonalAlignButton,
this.customAlignButton});
this.toolStrip.Location = new System.Drawing.Point(0, 0);
this.toolStrip.Name = "toolStrip";
this.toolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.toolStrip.Size = new System.Drawing.Size(292, 25);
this.toolStrip.TabIndex = 2;
//
// toolStripLabel1
//
this.toolStripLabel1.AutoSize = false;
this.toolStripLabel1.Name = "toolStripLabel1";
this.toolStripLabel1.Size = new System.Drawing.Size(64, 22);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// verticalCenterButton
//
this.verticalCenterButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.verticalCenterButton.Image = ((System.Drawing.Image)(resources.GetObject("verticalCenterButton.Image")));
this.verticalCenterButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.verticalCenterButton.Name = "verticalCenterButton";
this.verticalCenterButton.Size = new System.Drawing.Size(23, 22);
this.verticalCenterButton.Text = "toolStripButton1";
this.verticalCenterButton.ToolTipText = "Center Elements Vertically";
this.verticalCenterButton.Click += new System.EventHandler(this.verticalCenterButton_Click);
//
// horizontalCenterButton
//
this.horizontalCenterButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.horizontalCenterButton.Image = ((System.Drawing.Image)(resources.GetObject("horizontalCenterButton.Image")));
this.horizontalCenterButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.horizontalCenterButton.Name = "horizontalCenterButton";
this.horizontalCenterButton.Size = new System.Drawing.Size(23, 22);
this.horizontalCenterButton.Text = "toolStripButton1";
this.horizontalCenterButton.ToolTipText = "Center Elements Horizontally";
this.horizontalCenterButton.Click += new System.EventHandler(this.horizontalCenterButton_Click);
//
// customAlignButton
//
this.customAlignButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.customAlignButton.Image = ((System.Drawing.Image)(resources.GetObject("customAlignButton.Image")));
this.customAlignButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.customAlignButton.Name = "customAlignButton";
this.customAlignButton.Size = new System.Drawing.Size(23, 22);
this.customAlignButton.Text = "toolStripButton1";
this.customAlignButton.ToolTipText = "Custom Align Elements";
this.customAlignButton.Click += new System.EventHandler(this.customAlignElementButton_Click);
//
// customVerticalAlignButton
//
this.customVerticalAlignButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.customVerticalAlignButton.Image = ((System.Drawing.Image)(resources.GetObject("customVerticalAlignButton.Image")));
this.customVerticalAlignButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.customVerticalAlignButton.Name = "customVerticalAlignButton";
this.customVerticalAlignButton.Size = new System.Drawing.Size(23, 22);
this.customVerticalAlignButton.Text = "toolStripButton1";
this.customVerticalAlignButton.ToolTipText = "Custom Align Elements Vertically";
this.customVerticalAlignButton.Click += new System.EventHandler(this.customVerticalAlignButton_Click);
//
// customHoritonalAlignButton
//
this.customHoritonalAlignButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.customHoritonalAlignButton.Image = ((System.Drawing.Image)(resources.GetObject("customHoritonalAlignButton.Image")));
this.customHoritonalAlignButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.customHoritonalAlignButton.Name = "customHoritonalAlignButton";
this.customHoritonalAlignButton.Size = new System.Drawing.Size(23, 22);
this.customHoritonalAlignButton.Text = "toolStripButton2";
this.customHoritonalAlignButton.ToolTipText = "Custom Align Elements Horizontally";
this.customHoritonalAlignButton.Click += new System.EventHandler(this.customHoritonalAlignButton_Click);
//
// panelCardCanvas
//
this.panelCardCanvas.AutoScroll = true;
this.panelCardCanvas.DisableScrollToControl = true;
this.panelCardCanvas.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelCardCanvas.Location = new System.Drawing.Point(0, 25);
this.panelCardCanvas.Name = "panelCardCanvas";
this.panelCardCanvas.Size = new System.Drawing.Size(292, 248);
this.panelCardCanvas.TabIndex = 1;
//
// MDICanvas
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.Add(this.numericUpDownZoom);
this.Controls.Add(this.panelCardCanvas);
this.Controls.Add(this.toolStrip);
this.Name = "MDICanvas";
this.ShowIcon = false;
this.Text = " Canvas";
((System.ComponentModel.ISupportInitialize)(this.numericUpDownZoom)).EndInit();
this.toolStrip.ResumeLayout(false);
this.toolStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Support.UI.PanelEx panelCardCanvas;
private System.Windows.Forms.NumericUpDown numericUpDownZoom;
private System.Windows.Forms.ToolStrip toolStrip;
private System.Windows.Forms.ToolStripButton verticalCenterButton;
private System.Windows.Forms.ToolStripButton horizontalCenterButton;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton customAlignButton;
private System.Windows.Forms.ToolStripButton customVerticalAlignButton;
private System.Windows.Forms.ToolStripButton customHoritonalAlignButton;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.Environment.Shell;
using OrchardCore.Environment.Shell.Builders;
using OrchardCore.Environment.Shell.Descriptor;
using OrchardCore.Environment.Shell.Descriptor.Models;
using OrchardCore.Environment.Shell.Models;
using OrchardCore.Modules;
using OrchardCore.Recipes.Models;
using OrchardCore.Recipes.Services;
using OrchardCore.Setup.Events;
using YesSql;
namespace OrchardCore.Setup.Services
{
/// <summary>
/// Represents a setup service.
/// </summary>
public class SetupService : ISetupService
{
private readonly IShellHost _shellHost;
private readonly IShellContextFactory _shellContextFactory;
private readonly IEnumerable<IRecipeHarvester> _recipeHarvesters;
private readonly ILogger _logger;
private readonly IStringLocalizer S;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly string _applicationName;
private IEnumerable<RecipeDescriptor> _recipes;
/// <summary>
/// Creates a new instance of <see cref="SetupService"/>.
/// </summary>
/// <param name="shellHost">The <see cref="IShellHost"/>.</param>
/// <param name="hostingEnvironment">The <see cref="IHostEnvironment"/>.</param>
/// <param name="shellContextFactory">The <see cref="IShellContextFactory"/>.</param>
/// <param name="recipeHarvesters">A list of <see cref="IRecipeHarvester"/>s.</param>
/// <param name="logger">The <see cref="ILogger"/>.</param>
/// <param name="stringLocalizer">The <see cref="IStringLocalizer"/>.</param>
/// <param name="applicationLifetime">The <see cref="IHostApplicationLifetime"/>.</param>
public SetupService(
IShellHost shellHost,
IHostEnvironment hostingEnvironment,
IShellContextFactory shellContextFactory,
IEnumerable<IRecipeHarvester> recipeHarvesters,
ILogger<SetupService> logger,
IStringLocalizer<SetupService> stringLocalizer,
IHostApplicationLifetime applicationLifetime
)
{
_shellHost = shellHost;
_applicationName = hostingEnvironment.ApplicationName;
_shellContextFactory = shellContextFactory;
_recipeHarvesters = recipeHarvesters;
_logger = logger;
S = stringLocalizer;
_applicationLifetime = applicationLifetime;
}
/// <inheridoc />
public async Task<IEnumerable<RecipeDescriptor>> GetSetupRecipesAsync()
{
if (_recipes == null)
{
var recipeCollections = await Task.WhenAll(_recipeHarvesters.Select(x => x.HarvestRecipesAsync()));
_recipes = recipeCollections.SelectMany(x => x).Where(x => x.IsSetupRecipe).ToArray();
}
return _recipes;
}
/// <inheridoc />
public async Task<string> SetupAsync(SetupContext context)
{
var initialState = context.ShellSettings.State;
try
{
var executionId = await SetupInternalAsync(context);
if (context.Errors.Any())
{
context.ShellSettings.State = initialState;
}
return executionId;
}
catch
{
context.ShellSettings.State = initialState;
throw;
}
}
private async Task<string> SetupInternalAsync(SetupContext context)
{
string executionId;
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Running setup for tenant '{TenantName}'.", context.ShellSettings.Name);
}
// Features to enable for Setup
string[] hardcoded =
{
_applicationName,
"OrchardCore.Features",
"OrchardCore.Scripting",
"OrchardCore.Recipes"
};
context.EnabledFeatures = hardcoded.Union(context.EnabledFeatures ?? Enumerable.Empty<string>()).Distinct().ToList();
// Set shell state to "Initializing" so that subsequent HTTP requests are responded to with "Service Unavailable" while Orchard is setting up.
context.ShellSettings.State = TenantState.Initializing;
var shellSettings = new ShellSettings(context.ShellSettings);
if (string.IsNullOrEmpty(shellSettings["DatabaseProvider"]))
{
shellSettings["DatabaseProvider"] = context.DatabaseProvider;
shellSettings["ConnectionString"] = context.DatabaseConnectionString;
shellSettings["TablePrefix"] = context.DatabaseTablePrefix;
}
if (String.IsNullOrWhiteSpace(shellSettings["DatabaseProvider"]))
{
throw new ArgumentException($"{nameof(context.DatabaseProvider)} is required");
}
// Creating a standalone environment based on a "minimum shell descriptor".
// In theory this environment can be used to resolve any normal components by interface, and those
// components will exist entirely in isolation - no crossover between the safemode container currently in effect
// It is used to initialize the database before the recipe is run.
var shellDescriptor = new ShellDescriptor
{
Features = context.EnabledFeatures.Select(id => new ShellFeature { Id = id }).ToList()
};
using (var shellContext = await _shellContextFactory.CreateDescribedContextAsync(shellSettings, shellDescriptor))
{
await shellContext.CreateScope().UsingServiceScopeAsync(async scope =>
{
IStore store;
try
{
store = scope.ServiceProvider.GetRequiredService<IStore>();
}
catch (Exception e)
{
// Tables already exist or database was not found
// The issue is that the user creation needs the tables to be present,
// if the user information is not valid, the next POST will try to recreate the
// tables. The tables should be rolled back if one of the steps is invalid,
// unless the recipe is executing?
_logger.LogError(e, "An error occurred while initializing the datastore.");
context.Errors.Add("DatabaseProvider", S["An error occurred while initializing the datastore: {0}", e.Message]);
return;
}
// Create the "minimum shell descriptor"
await scope
.ServiceProvider
.GetService<IShellDescriptorManager>()
.UpdateShellDescriptorAsync(0,
shellContext.Blueprint.Descriptor.Features,
shellContext.Blueprint.Descriptor.Parameters);
});
if (context.Errors.Any())
{
return null;
}
executionId = Guid.NewGuid().ToString("n");
var recipeExecutor = shellContext.ServiceProvider.GetRequiredService<IRecipeExecutor>();
await recipeExecutor.ExecuteAsync(executionId, context.Recipe, new
{
context.SiteName,
context.AdminUsername,
context.AdminEmail,
context.AdminPassword,
context.DatabaseProvider,
context.DatabaseConnectionString,
context.DatabaseTablePrefix
},
_applicationLifetime.ApplicationStopping);
}
// Reloading the shell context as the recipe has probably updated its features
await (await _shellHost.GetScopeAsync(shellSettings)).UsingAsync(async scope =>
{
void reportError(string key, string message)
{
context.Errors[key] = message;
}
// Invoke modules to react to the setup event
var setupEventHandlers = scope.ServiceProvider.GetServices<ISetupEventHandler>();
var logger = scope.ServiceProvider.GetRequiredService<ILogger<SetupService>>();
await setupEventHandlers.InvokeAsync((handler, context) => handler.Setup(
context.SiteName,
context.AdminUsername,
context.AdminEmail,
context.AdminPassword,
context.DatabaseProvider,
context.DatabaseConnectionString,
context.DatabaseTablePrefix,
context.SiteTimeZone,
reportError
), context, logger);
});
if (context.Errors.Any())
{
return executionId;
}
// Update the shell state
shellSettings.State = TenantState.Running;
await _shellHost.UpdateShellSettingsAsync(shellSettings);
return executionId;
}
}
}
| |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
namespace UnrealControls
{
partial class OutputWindowView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager( typeof( OutputWindowView ) );
this.mHScrollBar = new System.Windows.Forms.HScrollBar();
this.mVScrollBar = new System.Windows.Forms.VScrollBar();
this.mDefaultCtxMenu = new System.Windows.Forms.ContextMenuStrip( this.components );
this.mCtxDefault_Copy = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.mCtxDefault_ScrollToEnd = new System.Windows.Forms.ToolStripMenuItem();
this.mCtxDefault_ScrollToHome = new System.Windows.Forms.ToolStripMenuItem();
this.mScrollSelectedTextTimer = new System.Windows.Forms.Timer( this.components );
this.mToolStrip_Find = new System.Windows.Forms.ToolStrip();
this.toolStripLabel_Find = new System.Windows.Forms.ToolStripLabel();
this.mToolStripTextBox_Find = new System.Windows.Forms.ToolStripTextBox();
this.mToolStripButton_FindNext = new System.Windows.Forms.ToolStripButton();
this.mToolStripButton_FindPrevious = new System.Windows.Forms.ToolStripButton();
this.ToolStripMenuItemClear = new System.Windows.Forms.ToolStripMenuItem();
this.mDefaultCtxMenu.SuspendLayout();
this.mToolStrip_Find.SuspendLayout();
this.SuspendLayout();
//
// mHScrollBar
//
this.mHScrollBar.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.mHScrollBar.Cursor = System.Windows.Forms.Cursors.Arrow;
this.mHScrollBar.Location = new System.Drawing.Point( 0, 225 );
this.mHScrollBar.Name = "mHScrollBar";
this.mHScrollBar.Size = new System.Drawing.Size( 422, 17 );
this.mHScrollBar.TabIndex = 0;
this.mHScrollBar.ValueChanged += new System.EventHandler( this.mHScrollBar_ValueChanged );
//
// mVScrollBar
//
this.mVScrollBar.Anchor = ( ( System.Windows.Forms.AnchorStyles )( ( ( System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom )
| System.Windows.Forms.AnchorStyles.Right ) ) );
this.mVScrollBar.Cursor = System.Windows.Forms.Cursors.Arrow;
this.mVScrollBar.Location = new System.Drawing.Point( 422, 0 );
this.mVScrollBar.Name = "mVScrollBar";
this.mVScrollBar.Size = new System.Drawing.Size( 17, 225 );
this.mVScrollBar.TabIndex = 1;
this.mVScrollBar.ValueChanged += new System.EventHandler( this.mVScrollBar_ValueChanged );
//
// mDefaultCtxMenu
//
this.mDefaultCtxMenu.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.mCtxDefault_Copy,
this.ToolStripMenuItemClear,
this.toolStripSeparator1,
this.mCtxDefault_ScrollToEnd,
this.mCtxDefault_ScrollToHome} );
this.mDefaultCtxMenu.Name = "mDefaultCtxMenu";
this.mDefaultCtxMenu.Size = new System.Drawing.Size( 153, 120 );
//
// mCtxDefault_Copy
//
this.mCtxDefault_Copy.Name = "mCtxDefault_Copy";
this.mCtxDefault_Copy.Size = new System.Drawing.Size( 152, 22 );
this.mCtxDefault_Copy.Text = "Copy";
this.mCtxDefault_Copy.Click += new System.EventHandler( this.mCtxDefault_Copy_Click );
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size( 149, 6 );
//
// mCtxDefault_ScrollToEnd
//
this.mCtxDefault_ScrollToEnd.Name = "mCtxDefault_ScrollToEnd";
this.mCtxDefault_ScrollToEnd.Size = new System.Drawing.Size( 152, 22 );
this.mCtxDefault_ScrollToEnd.Text = "Scroll To End";
this.mCtxDefault_ScrollToEnd.Click += new System.EventHandler( this.mCtxDefault_ScrollToEnd_Click );
//
// mCtxDefault_ScrollToHome
//
this.mCtxDefault_ScrollToHome.Name = "mCtxDefault_ScrollToHome";
this.mCtxDefault_ScrollToHome.Size = new System.Drawing.Size( 152, 22 );
this.mCtxDefault_ScrollToHome.Text = "Scroll To Home";
this.mCtxDefault_ScrollToHome.Click += new System.EventHandler( this.mCtxDefault_ScrollToHome_Click );
//
// mScrollSelectedTextTimer
//
this.mScrollSelectedTextTimer.Interval = 20;
this.mScrollSelectedTextTimer.Tick += new System.EventHandler( this.mScrollSelectedTextTimer_Tick );
//
// mToolStrip_Find
//
this.mToolStrip_Find.Dock = System.Windows.Forms.DockStyle.Bottom;
this.mToolStrip_Find.Font = new System.Drawing.Font( "Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ( ( byte )( 0 ) ) );
this.mToolStrip_Find.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.mToolStrip_Find.Items.AddRange( new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel_Find,
this.mToolStripTextBox_Find,
this.mToolStripButton_FindNext,
this.mToolStripButton_FindPrevious} );
this.mToolStrip_Find.Location = new System.Drawing.Point( 0, 242 );
this.mToolStrip_Find.Name = "mToolStrip_Find";
this.mToolStrip_Find.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.mToolStrip_Find.Size = new System.Drawing.Size( 439, 25 );
this.mToolStrip_Find.TabIndex = 2;
this.mToolStrip_Find.Text = "toolStrip1";
this.mToolStrip_Find.VisibleChanged += new System.EventHandler( this.mToolStrip_Find_VisibleChanged );
this.mToolStrip_Find.MouseEnter += new System.EventHandler( this.ChildControl_MouseEnter );
//
// toolStripLabel_Find
//
this.toolStripLabel_Find.BackColor = System.Drawing.SystemColors.Control;
this.toolStripLabel_Find.Name = "toolStripLabel_Find";
this.toolStripLabel_Find.Size = new System.Drawing.Size( 33, 22 );
this.toolStripLabel_Find.Text = "Find:";
//
// mToolStripTextBox_Find
//
this.mToolStripTextBox_Find.Name = "mToolStripTextBox_Find";
this.mToolStripTextBox_Find.Size = new System.Drawing.Size( 100, 25 );
this.mToolStripTextBox_Find.TextChanged += new System.EventHandler( this.mToolStripTextBox_Find_TextChanged );
//
// mToolStripButton_FindNext
//
this.mToolStripButton_FindNext.Image = ( ( System.Drawing.Image )( resources.GetObject( "mToolStripButton_FindNext.Image" ) ) );
this.mToolStripButton_FindNext.ImageTransparentColor = System.Drawing.Color.Gray;
this.mToolStripButton_FindNext.Name = "mToolStripButton_FindNext";
this.mToolStripButton_FindNext.Size = new System.Drawing.Size( 51, 22 );
this.mToolStripButton_FindNext.Text = "Next";
this.mToolStripButton_FindNext.Click += new System.EventHandler( this.mToolStripButton_FindNext_Click );
//
// mToolStripButton_FindPrevious
//
this.mToolStripButton_FindPrevious.Image = ( ( System.Drawing.Image )( resources.GetObject( "mToolStripButton_FindPrevious.Image" ) ) );
this.mToolStripButton_FindPrevious.ImageTransparentColor = System.Drawing.Color.Gray;
this.mToolStripButton_FindPrevious.Name = "mToolStripButton_FindPrevious";
this.mToolStripButton_FindPrevious.Size = new System.Drawing.Size( 72, 22 );
this.mToolStripButton_FindPrevious.Text = "Previous";
this.mToolStripButton_FindPrevious.Click += new System.EventHandler( this.mToolStripButton_FindPrevious_Click );
//
// ToolStripMenuItemClear
//
this.ToolStripMenuItemClear.Name = "ToolStripMenuItemClear";
this.ToolStripMenuItemClear.Size = new System.Drawing.Size( 152, 22 );
this.ToolStripMenuItemClear.Text = "Clear";
this.ToolStripMenuItemClear.Click += new System.EventHandler( this.ToolStripMenuItem_Clear_Click );
//
// OutputWindowView
//
this.AutoScaleDimensions = new System.Drawing.SizeF( 7F, 15F );
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Window;
this.ContextMenuStrip = this.mDefaultCtxMenu;
this.Controls.Add( this.mToolStrip_Find );
this.Controls.Add( this.mVScrollBar );
this.Controls.Add( this.mHScrollBar );
this.Cursor = System.Windows.Forms.Cursors.Arrow;
this.DoubleBuffered = true;
this.Font = new System.Drawing.Font( "Courier New", 9F );
this.ForeColor = System.Drawing.SystemColors.WindowText;
this.Name = "OutputWindowView";
this.Size = new System.Drawing.Size( 439, 267 );
this.MouseMove += new System.Windows.Forms.MouseEventHandler( this.OutputWindowView_MouseMove );
this.mDefaultCtxMenu.ResumeLayout( false );
this.mToolStrip_Find.ResumeLayout( false );
this.mToolStrip_Find.PerformLayout();
this.ResumeLayout( false );
this.PerformLayout();
}
#endregion
private System.Windows.Forms.HScrollBar mHScrollBar;
private System.Windows.Forms.VScrollBar mVScrollBar;
private System.Windows.Forms.ContextMenuStrip mDefaultCtxMenu;
private System.Windows.Forms.ToolStripMenuItem mCtxDefault_Copy;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem mCtxDefault_ScrollToEnd;
private System.Windows.Forms.ToolStripMenuItem mCtxDefault_ScrollToHome;
private System.Windows.Forms.Timer mScrollSelectedTextTimer;
private System.Windows.Forms.ToolStrip mToolStrip_Find;
private System.Windows.Forms.ToolStripLabel toolStripLabel_Find;
private System.Windows.Forms.ToolStripButton mToolStripButton_FindNext;
private System.Windows.Forms.ToolStripButton mToolStripButton_FindPrevious;
private System.Windows.Forms.ToolStripTextBox mToolStripTextBox_Find;
private System.Windows.Forms.ToolStripMenuItem ToolStripMenuItemClear;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
/// <summary>
/// Wraps IGridCache implementation to simplify async mode testing.
/// </summary>
internal class CacheTestAsyncWrapper<TK, TV> : ICache<TK, TV>
{
private readonly ICache<TK, TV> _cache;
/// <summary>
/// Initializes a new instance of the <see cref="CacheTestAsyncWrapper{K, V}"/> class.
/// </summary>
/// <param name="cache">The cache to be wrapped.</param>
public CacheTestAsyncWrapper(ICache<TK, TV> cache)
{
Debug.Assert(cache != null);
_cache = cache;
}
/** <inheritDoc /> */
public string Name
{
get { return _cache.Name; }
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _cache.Ignite; }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return _cache.GetConfiguration();
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return _cache.IsEmpty();
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _cache.IsKeepBinary; }
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
return _cache.WithSkipStore().WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
return _cache.WithExpiryPolicy(plc).WrapAsync();
}
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
return _cache.WithKeepBinary<TK1, TV1>().WrapAsync();
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
WaitResult(_cache.LoadCacheAsync(p, args));
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
WaitResult(_cache.LocalLoadCacheAsync(p, args));
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return _cache.LocalLoadCacheAsync(p, args);
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
_cache.LoadAll(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return _cache.LoadAllAsync(keys, replaceExistingValues);
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
return GetResult(_cache.ContainsKeyAsync(key));
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
return _cache.ContainsKeyAsync(key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
return GetResult(_cache.ContainsKeysAsync(keys));
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
return _cache.ContainsKeysAsync(keys);
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
return _cache.LocalPeek(key, modes);
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
return _cache.TryLocalPeek(key, out value, modes);
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return _cache[key]; }
set { _cache[key] = value; }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
return GetResult(_cache.GetAsync(key));
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
return _cache.GetAsync(key);
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
return _cache.TryGet(key, out value);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
return _cache.TryGetAsync(key);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
return GetResult(_cache.GetAllAsync(keys));
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
return _cache.GetAllAsync(keys);
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
WaitResult(_cache.PutAsync(key, val));
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
return _cache.PutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
return GetResult(_cache.GetAndPutAsync(key, val));
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
return _cache.GetAndPutAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
return GetResult(_cache.GetAndReplaceAsync(key, val));
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
return _cache.GetAndReplaceAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
return GetResult(_cache.GetAndRemoveAsync(key));
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
return _cache.GetAndRemoveAsync(key);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
return GetResult(_cache.PutIfAbsentAsync(key, val));
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
return _cache.PutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
return GetResult(_cache.GetAndPutIfAbsentAsync(key, val));
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
return _cache.GetAndPutIfAbsentAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
return GetResult(_cache.ReplaceAsync(key, val));
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
return _cache.ReplaceAsync(key, val);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
return GetResult(_cache.ReplaceAsync(key, oldVal, newVal));
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
return _cache.ReplaceAsync(key, oldVal, newVal);
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
WaitResult(_cache.PutAllAsync(vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
return _cache.PutAllAsync(vals);
}
/** <inheritDoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
_cache.LocalEvict(keys);
}
/** <inheritDoc /> */
public void Clear()
{
WaitResult(_cache.ClearAsync());
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return _cache.ClearAsync();
}
/** <inheritDoc /> */
public void Clear(TK key)
{
WaitResult(_cache.ClearAsync(key));
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
return _cache.ClearAsync(key);
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
WaitResult(_cache.ClearAllAsync(keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
return _cache.ClearAllAsync(keys);
}
/** <inheritDoc /> */
public void LocalClear(TK key)
{
_cache.LocalClear(key);
}
/** <inheritDoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
_cache.LocalClearAll(keys);
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
return GetResult(_cache.RemoveAsync(key));
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
return _cache.RemoveAsync(key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
return GetResult(_cache.RemoveAsync(key, val));
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
return _cache.RemoveAsync(key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
WaitResult(_cache.RemoveAllAsync(keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
return _cache.RemoveAllAsync(keys);
}
/** <inheritDoc /> */
public void RemoveAll()
{
WaitResult(_cache.RemoveAllAsync());
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return _cache.RemoveAllAsync();
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return _cache.GetLocalSize(modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return GetResult(_cache.GetSizeAsync(modes));
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
return _cache.GetSizeAsync(modes);
}
/** <inheritDoc /> */
public void LocalPromote(IEnumerable<TK> keys)
{
_cache.LocalPromote(keys);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
return _cache.Query(qry);
}
/** <inheritDoc /> */
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return _cache.QueryFields(qry);
}
/** <inheritDoc /> */
IContinuousQueryHandle ICache<TK, TV>.QueryContinuous(ContinuousQuery<TK, TV> qry)
{
return _cache.QueryContinuous(qry);
}
/** <inheritDoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
return _cache.QueryContinuous(qry, initialQry);
}
/** <inheritDoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(params CachePeekMode[] peekModes)
{
return _cache.GetLocalEntries(peekModes);
}
/** <inheritDoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return GetResult(_cache.InvokeAsync(key, processor, arg));
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAsync(key, processor, arg);
}
/** <inheritDoc /> */
public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return GetResult(_cache.InvokeAllAsync(keys, processor, arg));
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
return _cache.InvokeAllAsync(keys, processor, arg);
}
/** <inheritDoc /> */
public ICacheLock Lock(TK key)
{
return _cache.Lock(key);
}
/** <inheritDoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
return _cache.LockAll(keys);
}
/** <inheritDoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
return _cache.IsLocalLocked(key, byCurrentThread);
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return _cache.GetMetrics();
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
return _cache.GetMetrics(clusterGroup);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return _cache.GetLocalMetrics();
}
/** <inheritDoc /> */
public Task Rebalance()
{
return _cache.Rebalance();
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
return _cache.WithNoRetries();
}
/** <inheritDoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return _cache.GetEnumerator();
}
/** <inheritDoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Waits the result of a task, unwraps exceptions.
/// </summary>
/// <param name="task">The task.</param>
private static void WaitResult(Task task)
{
try
{
task.Wait();
}
catch (AggregateException ex)
{
throw ex.InnerException;
}
}
/// <summary>
/// Gets the result of a task, unwraps exceptions.
/// </summary>
private static T GetResult<T>(Task<T> task)
{
try
{
return task.Result;
}
catch (Exception ex)
{
throw ex.InnerException;
}
}
}
/// <summary>
/// Extension methods for IGridCache.
/// </summary>
public static class CacheExtensions
{
/// <summary>
/// Wraps specified instance into GridCacheTestAsyncWrapper.
/// </summary>
public static ICache<TK, TV> WrapAsync<TK, TV>(this ICache<TK, TV> cache)
{
return new CacheTestAsyncWrapper<TK, TV>(cache);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//Simple arithmatic manipulation of one 2D array elements
using System;
public class Arrayclass
{
public double[,] a2d;
public double[,,] a3d;
public Arrayclass(int size)
{
a2d = new double[size, size];
a3d = new double[size, size + 5, size + 10];
}
}
public class class1
{
public static Random rand;
public static int size;
public static Arrayclass ima;
public static double GenerateDbl()
{
int e;
int op1 = (int)((float)rand.Next() / Int32.MaxValue * 2);
if (op1 == 0)
e = -rand.Next(0, 14);
else
e = +rand.Next(0, 14);
return Math.Pow(2, e);
}
public static void Init2DMatrix(out double[,] m, out double[][] refm)
{
int i, j;
i = 0;
double temp;
m = new double[size, size];
refm = new double[size][];
for (int k = 0; k < refm.Length; k++)
refm[k] = new double[size];
while (i < size)
{
j = 0;
while (j < size)
{
temp = GenerateDbl();
m[i, j] = temp - 60;
refm[i][j] = temp - 60;
j++;
}
i++;
}
}
public static void Process2DArray(ref double[,] a2d)
{
for (int i = 3; i < size + 3; i++)
for (int j = -10; j < size - 10; j++)
{
int b = j + 5;
a2d[i - 3, b + 5] += a2d[0, b + 5] + a2d[1, b + 5];
a2d[i - 3, b + 5] *= a2d[i - 3, j + 10] + a2d[2, b + 5];
a2d[i - 3, j + 10] -= a2d[i - 3, b + 5] * a2d[3, j + 10];
if ((a2d[i - 3, b + 5] + a2d[4, j + 10]) != 0)
a2d[i - 3, b + 5] /= a2d[i - 3, b + 5] + a2d[4, b + 5];
else
a2d[i - 3, j + 10] += a2d[i - 3, j + 10] * a2d[4, j + 10];
for (int k = 5; k < size; k++)
a2d[i - 3, b + 5] += a2d[k, j + 10];
}
}
public static void ProcessJagged2DArray(ref double[][] a2d)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
a2d[i][j] += a2d[0][j] + a2d[1][j];
a2d[i][j] *= a2d[i][j] + a2d[2][j];
a2d[i][j] -= a2d[i][j] * a2d[3][j];
if ((a2d[i][j] + a2d[4][j]) != 0)
a2d[i][j] /= a2d[i][j] + a2d[4][j];
else
a2d[i][j] += a2d[i][j] * a2d[4][j];
for (int k = 5; k < size; k++)
a2d[i][j] += a2d[k][j];
}
}
public static void Init3DMatrix(double[,,] m, double[][] refm)
{
int i, j;
i = 0;
double temp;
//m = new double[size, size, size];
//refm = new double[size][];
//for (int k=0; k<refm.Length; k++)
//refm[k] = new double[size];
while (i < size)
{
j = 0;
while (j < size)
{
temp = GenerateDbl();
m[i, j, size] = temp - 60;
refm[i][j] = temp - 60;
j++;
}
i++;
}
}
public static void Process3DArray(double[,,] a3d)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
a3d[i, j, size] += a3d[0, j, size] + a3d[1, j, size];
a3d[i, j, size] *= a3d[i, j, size] + a3d[2, j, size];
a3d[i, j, size] -= a3d[i, j, size] * a3d[3, j, size];
if ((a3d[i, j, size] + a3d[4, j, size]) != 0)
a3d[i, j, size] /= a3d[i, j, size] + a3d[4, j, size];
else
a3d[i, j, size] += a3d[i, j, size] * a3d[4, j, size];
for (int k = 5; k < size; k++)
a3d[i, j, size] *= a3d[k, j, size];
}
}
public static void ProcessJagged3DArray(double[][] a3d)
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
{
a3d[i][j] += a3d[0][j] + a3d[1][j];
a3d[i][j] *= a3d[i][j] + a3d[2][j];
a3d[i][j] -= a3d[i][j] * a3d[3][j];
if ((a3d[i][j] + a3d[4][j]) != 0)
a3d[i][j] /= a3d[i][j] + a3d[4][j];
else
a3d[i][j] += a3d[i][j] * a3d[4][j];
for (int k = 5; k < size; k++)
a3d[i][j] *= a3d[k][j];
}
}
public static int Main()
{
bool pass = false;
rand = new Random();
size = rand.Next(5, 10);
Console.WriteLine();
Console.WriteLine("2D Array");
Console.WriteLine("Element manipulation of {0} by {0} matrices with different arithmatic operations", size);
Console.WriteLine("Matrix is member of class, element stores random double");
Console.WriteLine("array set/get, ref/out param are used");
ima = new Arrayclass(size);
double[][] refa2d = new double[size][];
Init2DMatrix(out ima.a2d, out refa2d);
int m = 0;
int n;
while (m < size)
{
n = 0;
while (n < size)
{
Process2DArray(ref ima.a2d);
ProcessJagged2DArray(ref refa2d);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (ima.a2d[i, j] != refa2d[i][j])
if (!Double.IsNaN(ima.a2d[i, j]) || !Double.IsNaN(refa2d[i][j]))
{
Console.WriteLine("i={0}, j={1}, ima.a2d[i,j] {2}!=refa2d[i][j] {3}", i, j, ima.a2d[i, j], refa2d[i][j]);
pass = false;
}
}
if (pass)
{
try
{
ima.a2d[size, 0] = 5;
pass = false;
}
catch (IndexOutOfRangeException)
{ }
}
Console.WriteLine();
Console.WriteLine("3D Array");
Console.WriteLine("Element manipulation of {0} by {1} by {2} matrices with different arithmatic operations", size, size + 5, size + 10);
Console.WriteLine("Matrix is member of class, element stores random double");
double[][] refa3d = new double[size][];
for (int k = 0; k < refa3d.Length; k++)
refa3d[k] = new double[size];
Init3DMatrix(ima.a3d, refa3d);
m = 0;
n = 0;
while (m < size)
{
n = 0;
while (n < size)
{
Process3DArray(ima.a3d);
ProcessJagged3DArray(refa3d);
n++;
}
m++;
}
for (int i = 0; i < size; i++)
{
pass = true;
for (int j = 0; j < size; j++)
if (ima.a3d[i, j, size] != refa3d[i][j])
if (!Double.IsNaN(ima.a3d[i, j, size]) || !Double.IsNaN(refa3d[i][j]))
{
Console.WriteLine("i={0}, j={1}, ima.a3d[i,j,size] {2}!=refa3d[i][j] {3}", i, j, ima.a3d[i, j, size], refa3d[i][j]);
pass = false;
}
}
if (pass)
{
try
{
ima.a3d[-1, 0, 0] = 5;
pass = false;
}
catch (IndexOutOfRangeException)
{ }
}
Console.WriteLine();
if (pass)
{
Console.WriteLine("PASSED");
return 100;
}
else
{
Console.WriteLine("FAILED");
return 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.IdentityModel.Selectors;
using System.ServiceModel.Security;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using System.Threading;
using System.IO;
using Infrastructure.Common;
public partial class ExpectedExceptionTests : ConditionalWcfTest
{
[WcfFact]
[OuterLoop]
public static void NotExistentHost_Throws_EndpointNotFoundException()
{
string nonExistentHost = "http://nonexisthost/WcfService/WindowsCommunicationFoundation";
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(10000);
EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() =>
{
using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(nonExistentHost)))
{
IWcfService serviceProxy = factory.CreateChannel();
string response = serviceProxy.Echo("Hello");
}
});
// On .Net Native retail, exception message is stripped to include only parameter
Assert.True(exception.Message.Contains(nonExistentHost), string.Format("Expected exception message to contain: '{0}'", nonExistentHost));
}
[WcfFact]
[OuterLoop]
[Issue(398)]
public static void ServiceRestart_Throws_CommunicationException()
{
StringBuilder errorBuilder = new StringBuilder();
string restartServiceAddress = "";
BasicHttpBinding binding = new BasicHttpBinding();
try
{
using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)))
{
IWcfService serviceProxy = factory.CreateChannel();
restartServiceAddress = serviceProxy.GetRestartServiceEndpoint();
}
}
catch (Exception e)
{
string error = String.Format("Unexpected exception thrown while calling the 'GetRestartServiceEndpoint' operation. {0}", e.ToString());
if (e.InnerException != null)
error += String.Format("\r\nInnerException:\r\n{0}", e.InnerException.ToString());
errorBuilder.AppendLine(error);
}
if (errorBuilder.Length == 0)
{
// Get the Service host name and replace localhost with it
UriBuilder builder = new UriBuilder(Endpoints.HttpBaseAddress_Basic);
string hostName = builder.Uri.Host;
restartServiceAddress = restartServiceAddress.Replace("[HOST]", hostName);
//On .NET Native retail, exception message is stripped to include only parameter
string expectExceptionMsg = restartServiceAddress;
try
{
using (ChannelFactory<IWcfRestartService> factory = new ChannelFactory<IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress)))
{
// Get the last portion of the restart service url which is a Guid and convert it back to a Guid
// This is needed by the RestartService operation as a Dictionary key to get the ServiceHost
string uniqueIdentifier = restartServiceAddress.Substring(restartServiceAddress.LastIndexOf("/") + 1);
Guid guid = new Guid(uniqueIdentifier);
IWcfRestartService serviceProxy = factory.CreateChannel();
serviceProxy.RestartService(guid);
}
errorBuilder.AppendLine("Expected CommunicationException exception, but no exception thrown.");
}
catch (Exception e)
{
if (e.GetType() == typeof(CommunicationException))
{
if (e.Message.Contains(expectExceptionMsg))
{
}
else
{
errorBuilder.AppendLine(string.Format("Expected exception message contains: {0}, actual: {1}", expectExceptionMsg, e.Message));
}
}
else
{
errorBuilder.AppendLine(string.Format("Expected exception: {0}, actual: {1}/n Exception was: {2}", "CommunicationException", e.GetType(), e.ToString()));
}
}
}
Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: ServiceRestart_Throws_CommunicationException FAILED with the following errors: {0}", errorBuilder));
}
[WcfFact]
[OuterLoop]
public static void UnknownUrl_Throws_EndpointNotFoundException()
{
// We need a running service host at the other end but mangle the endpoint suffix
string notFoundUrl = Endpoints.HttpBaseAddress_Basic + "not-an-endpoint";
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(10000);
EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() =>
{
try
{
using (
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding,
new EndpointAddress(notFoundUrl)))
{
IWcfService serviceProxy = factory.CreateChannel();
string response = serviceProxy.Echo("Hello");
}
}
catch (EndpointNotFoundException)
{
throw;
}
catch (CommunicationException ce)
{
if (ce.InnerException == null)
throw;
if (ce.InnerException.GetType() == typeof(HttpRequestException))
{
var httpReqExcep = ce.InnerException as HttpRequestException;
StringBuilder sb = new StringBuilder();
sb.Append("Received HttpRequestException with unknown error code ")
.AppendLine(ce.InnerException.HResult.ToString())
.AppendLine("Full details for HttpRequestException:")
.AppendLine(httpReqExcep.ToString());
throw new CommunicationException(sb.ToString());
}
throw;
}
});
// On .Net Native retail, exception message is stripped to include only parameter
Assert.True(exception.Message.Contains(notFoundUrl), string.Format("Expected exception message to contain: '{0}'", notFoundUrl));
}
[WcfFact]
[OuterLoop]
public static void UnknownUrl_Throws_ProtocolException()
{
string protocolExceptionUri = Endpoints.HttpProtocolError_Address;
BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMilliseconds(10000);
using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(protocolExceptionUri)))
{
IWcfService serviceProxy = factory.CreateChannel();
ProtocolException exception = Assert.Throws<ProtocolException>(() =>
{
string response = serviceProxy.Echo("Hello");
});
// On .Net Native retail, exception message is stripped to include only parameter
Assert.True(exception.Message.Contains(protocolExceptionUri), string.Format("Expected exception message to contain '{0}'", protocolExceptionUri));
}
}
[WcfFact]
[OuterLoop]
public static void DuplexCallback_Throws_FaultException_DirectThrow()
{
DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null;
Guid guid = Guid.NewGuid();
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback(true);
InstanceContext context = new InstanceContext(callbackService);
try
{
var exception = Assert.Throws<FaultException<FaultDetail>>(() =>
{
factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address));
IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel();
Task<Guid> task = serviceProxy.FaultPing(guid);
if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout))
{
Guid returnedGuid = task.GetAwaiter().GetResult();
}
else
{
throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout));
}
// Not closing the factory as an exception will always be thrown prior to this point.
});
Assert.Equal("ServicePingFaultCallback", exception.Code.Name);
Assert.Equal("Reason: Testing FaultException returned from Duplex Callback", exception.Reason.GetMatchingTranslation().Text);
}
finally
{
if (factory != null && factory.State != CommunicationState.Closed)
{
factory.Abort();
}
}
}
[WcfFact]
[OuterLoop]
public static void DuplexCallback_Throws_FaultException_ReturnsFaultedTask()
{
DuplexChannelFactory<IWcfDuplexTaskReturnService> factory = null;
Guid guid = Guid.NewGuid();
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
DuplexTaskReturnServiceCallback callbackService = new DuplexTaskReturnServiceCallback();
InstanceContext context = new InstanceContext(callbackService);
try
{
var exception = Assert.Throws<FaultException<FaultDetail>>(() =>
{
factory = new DuplexChannelFactory<IWcfDuplexTaskReturnService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_TaskReturn_Address));
IWcfDuplexTaskReturnService serviceProxy = factory.CreateChannel();
Task<Guid> task = serviceProxy.FaultPing(guid);
if ((task as IAsyncResult).AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout))
{
Guid returnedGuid = task.GetAwaiter().GetResult();
}
else
{
throw new TimeoutException(String.Format("The call to the Service did not complete within the alloted time of: {0}", ScenarioTestHelpers.TestTimeout));
}
// Not closing the factory as an exception will always be thrown prior to this point.
});
Assert.Equal("ServicePingFaultCallback", exception.Code.Name);
Assert.Equal("Reason: Testing FaultException returned from Duplex Callback", exception.Reason.GetMatchingTranslation().Text);
}
finally
{
if (factory != null && factory.State != CommunicationState.Closed)
{
factory.Abort();
}
}
}
[WcfFact]
[OuterLoop]
// Verify product throws MessageSecurityException when the Dns identity from the server does not match the expectation
public static void TCP_ServiceCertExpired_Throw_MessageSecurityException()
{
string testString = "Hello";
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
EndpointAddress endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_ExpiredServerCertResource_Address));
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
IWcfService serviceProxy = factory.CreateChannel();
try
{
var result = serviceProxy.Echo(testString);
Assert.True(false, "Expected: SecurityNegotiationException, Actual: no exception");
}
catch (CommunicationException exception)
{
string exceptionType = exception.GetType().Name;
if (exceptionType != "SecurityNegotiationException")
{
Assert.True(false, string.Format("Expected type SecurityNegotiationException, Actual: {0}", exceptionType));
}
}
finally
{
ScenarioTestHelpers.CloseCommunicationObjects(factory);
}
}
[WcfFact]
[OuterLoop]
// Verify product throws SecurityNegotiationException when the service cert is revoked
public static void TCP_ServiceCertRevoked_Throw_SecurityNegotiationException()
{
string testString = "Hello";
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
EndpointAddress endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_RevokedServerCertResource_Address), new DnsEndpointIdentity(Endpoints.Tcp_RevokedServerCertResource_HostName));
ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
IWcfService serviceProxy = factory.CreateChannel();
try
{
var result = serviceProxy.Echo(testString);
Assert.True(false, "Expected: SecurityNegotiationException, Actual: no exception");
}
catch (CommunicationException exception)
{
string exceptionType = exception.GetType().Name;
if (exceptionType != "SecurityNegotiationException")
{
Assert.True(false, string.Format("Expected type SecurityNegotiationException, Actual: {0}", exceptionType));
}
string exceptionMessage = exception.Message;
Assert.True(exceptionMessage.Contains(Endpoints.Tcp_RevokedServerCertResource_HostName), string.Format("Expected message contains {0}, actual message: {1}", Endpoints.Tcp_RevokedServerCertResource_HostName, exception.ToString()));
}
finally
{
ScenarioTestHelpers.CloseCommunicationObjects(factory);
}
}
[WcfFact]
[OuterLoop]
public static void Abort_During_Implicit_Open_Closes_Sync_Waiters()
{
// This test is a regression test of an issue with CallOnceManager.
// When a single proxy is used to make several service calls without
// explicitly opening it, the CallOnceManager queues up all the requests
// that happen while it is opening the channel (or handling previously
// queued service calls. If the channel was closed or faulted during
// the handling of any queued requests, it caused a pathological worst
// case where every queued request waited for its complete SendTimeout
// before failing.
//
// This test operates by making multiple concurrent synchronous service
// calls, but stalls the Opening event to allow them to be queued before
// any of them are allowed to proceed. It then aborts the channel when
// the first service operation is allowed to proceed. This causes the
// CallOnce manager to deal with all its queued operations and cause
// them to complete other than by timing out.
BasicHttpBinding binding = null;
ChannelFactory<IWcfService> factory = null;
IWcfService serviceProxy = null;
int timeoutMs = 20000;
long operationsQueued = 0;
int operationCount = 5;
Task<string>[] tasks = new Task<string>[operationCount];
Exception[] exceptions = new Exception[operationCount];
string[] results = new string[operationCount];
bool isClosed = false;
DateTime endOfOpeningStall = DateTime.Now;
int serverDelayMs = 100;
TimeSpan serverDelayTimeSpan = TimeSpan.FromMilliseconds(serverDelayMs);
string testMessage = "testMessage";
try
{
// *** SETUP *** \\
binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.TransferMode = TransferMode.Streamed;
// SendTimeout is the timeout used for implicit opens
binding.SendTimeout = TimeSpan.FromMilliseconds(timeoutMs);
factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic));
serviceProxy = factory.CreateChannel();
// Force the implicit open to stall until we have multiple concurrent calls pending.
// This forces the CallOnceManager to have a queue of waiters it will need to notify.
((ICommunicationObject)serviceProxy).Opening += (s, e) =>
{
// Wait until we see sync calls have been queued
DateTime startOfOpeningStall = DateTime.Now;
while (true)
{
endOfOpeningStall = DateTime.Now;
// Don't wait forever -- if we stall longer than the SendTimeout, it means something
// is wrong other than what we are testing, so just fail early.
if ((endOfOpeningStall - startOfOpeningStall).TotalMilliseconds > timeoutMs)
{
Assert.True(false, "The Opening event timed out waiting for operations to queue, which was not expected for this test.");
}
// As soon as we have all our Tasks at least running, wait a little
// longer to allow them finish queuing up their waiters, then stop stalling the Opening
if (Interlocked.Read(ref operationsQueued) >= operationCount)
{
Task.Delay(500).Wait();
endOfOpeningStall = DateTime.Now;
return;
}
Task.Delay(100).Wait();
}
};
// Each task will make a synchronous service call, which will cause all but the
// first to be queued for the implicit open. The first call to complete then closes
// the channel so that it is forced to deal with queued waiters.
Func<string> callFunc = () =>
{
// We increment the # ops queued before making the actual sync call, which is
// technically a short race condition in the test. But reversing the order would
// timeout the implicit open and fault the channel.
Interlocked.Increment(ref operationsQueued);
// The call of the operation is what creates the entry in the CallOnceManager queue.
// So as each Task below starts, it increments the count and adds a waiter to the
// queue. We ask for a small delay on the server side just to introduce a small
// stall after the sync request has been made before it can complete. Otherwise
// fast machines can finish all the requests before the first one finishes the Close().
string result = serviceProxy.EchoWithTimeout("test", serverDelayTimeSpan);
lock (tasks)
{
if (!isClosed)
{
try
{
isClosed = true;
((ICommunicationObject)serviceProxy).Abort();
}
catch { }
}
}
return result;
};
// *** EXECUTE *** \\
DateTime startTime = DateTime.Now;
for (int i = 0; i < operationCount; ++i)
{
tasks[i] = Task.Run(callFunc);
}
for (int i = 0; i < operationCount; ++i)
{
try
{
results[i] = tasks[i].GetAwaiter().GetResult();
}
catch (Exception ex)
{
exceptions[i] = ex;
}
}
// *** VALIDATE *** \\
double elapsedMs = (DateTime.Now - endOfOpeningStall).TotalMilliseconds;
// Before validating that the issue was fixed, first validate that we received the exceptions or the
// results we expected. This is to verify the fix did not introduce a behavioral change other than the
// elimination of the long unnecessary timeouts after the channel was closed.
int nFailures = 0;
for (int i = 0; i < operationCount; ++i)
{
if (exceptions[i] == null)
{
Assert.True((String.Equals("test", results[i])),
String.Format("Expected operation #{0} to return '{1}' but actual was '{2}'",
i, testMessage, results[i]));
}
else
{
++nFailures;
TimeoutException toe = exceptions[i] as TimeoutException;
Assert.True(toe == null, String.Format("Task [{0}] should not have failed with TimeoutException", i));
}
}
Assert.True(nFailures > 0,
String.Format("Expected at least one operation to throw an exception, but none did. Elapsed time = {0} ms.",
elapsedMs));
Assert.True(nFailures < operationCount,
String.Format("Expected at least one operation to succeed but none did. Elapsed time = {0} ms.",
elapsedMs));
// The original issue was that sync waiters in the CallOnceManager were not notified when
// the channel became unusable and therefore continued to time out for the full amount.
// Additionally, because they were executed sequentially, it was also possible for each one
// to time out for the full amount. Given that we closed the channel, we expect all the queued
// waiters to have been immediately waked up and detected failure.
int expectedElapsedMs = (operationCount * serverDelayMs) + timeoutMs / 2;
Assert.True(elapsedMs < expectedElapsedMs,
String.Format("The {0} operations took {1} ms to complete which exceeds the expected {2} ms",
operationCount, elapsedMs, expectedElapsedMs));
// *** CLEANUP *** \\
((ICommunicationObject)serviceProxy).Close();
factory.Close();
}
finally
{
// *** ENSURE CLEANUP *** \\
ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using Shielded;
namespace ShieldedTests
{
[TestFixture()]
public class SeqTests
{
[Test()]
public void BasicOps()
{
var seq = new ShieldedSeq<int>(
Enumerable.Range(1, 20).ToArray());
Assert.AreEqual(20, seq.Count);
Assert.IsTrue(seq.Any());
Assert.AreEqual(1, seq.Head);
for (int i = 0; i < 20; i++)
Assert.AreEqual(i + 1, seq [i]);
Shield.InTransaction(() => {
int i = 1;
foreach (int x in seq)
{
Assert.AreEqual(i, x);
i++;
}
});
ParallelEnumerable.Range(0, 20)
.ForAll(n => Shield.InTransaction(() =>
seq [n] = seq [n] + 20)
);
for (int i = 0; i < 20; i++)
Assert.AreEqual(i + 21, seq [i]);
Shield.InTransaction(() => {
seq.Append(0);
// test commute
Assert.AreEqual(0, seq [20]);
}
);
Assert.AreEqual(21, seq.Count);
var a = Shield.InTransaction(() => seq.TakeHead());
Assert.AreEqual(20, seq.Count);
Assert.AreEqual(21, a);
for (int i = 0; i < 19; i++)
Assert.AreEqual(i + 22, seq [i]);
Assert.AreEqual(0, seq [19]);
Shield.InTransaction(() => {
seq.Prepend(a);
seq.RemoveAt(20);
}
);
Assert.AreEqual(20, seq.Count);
for (int i = 0; i < 20; i++)
Assert.AreEqual(i + 21, seq [i]);
Shield.InTransaction(() => seq.RemoveAll(i => (i & 1) == 1));
Assert.AreEqual(10, seq.Count);
for (int i = 0; i < 10; i++)
Assert.AreEqual(i * 2 + 22, seq [i]);
var seq2 = new ShieldedSeq<int>(
Shield.InTransaction(() => seq.ToArray()));
Shield.InTransaction(() => seq.RemoveAll(i => true));
Assert.AreEqual(0, seq.Count);
Shield.InTransaction(() => seq2.Clear());
Assert.AreEqual(0, seq2.Count);
var seq3 = new ShieldedSeq<int>(
Enumerable.Range(1, 5).ToArray());
Shield.InTransaction(() => seq3.RemoveAt(0));
Assert.AreEqual(4, seq3.Count);
Assert.AreEqual(2, seq3 [0]);
Shield.InTransaction(() => seq3.RemoveAt(3));
Assert.AreEqual(3, seq3.Count);
Assert.AreEqual(4, seq3 [2]);
Shield.InTransaction(() => seq3.Append(100));
Assert.AreEqual(4, seq3.Count);
Assert.AreEqual(100, seq3 [3]);
Shield.InTransaction(() => seq3.RemoveAll(i => i == 100));
Assert.AreEqual(3, seq3.Count);
Assert.AreEqual(4, seq3 [2]);
Shield.InTransaction(() => seq3.Append(100));
Assert.AreEqual(4, seq3.Count);
Assert.AreEqual(100, seq3 [3]);
}
[Test()]
public void HeadTests()
{
var seq4 = new ShieldedSeq<int>(
Enumerable.Range(1, 10).ToArray());
Shield.InTransaction(() => { seq4.Prepend(100); });
Assert.AreEqual(11, seq4.Count);
Assert.AreEqual(100, seq4.Head);
Assert.AreEqual(100, seq4.First());
Assert.IsTrue(seq4.Any());
Assert.AreEqual(100,
Shield.InTransaction(() => seq4.TakeHead()));
Assert.AreEqual(10, seq4.Count);
Assert.AreEqual(1, seq4.Head);
Assert.IsTrue(seq4.Any());
for (int i = 0; i < 10; i++)
{
Assert.AreEqual(i + 1, seq4.Head);
Assert.AreEqual(i + 1, Shield.InTransaction(() => seq4.TakeHead()));
}
Assert.Throws<InvalidOperationException>(() =>
Shield.InTransaction(() => {
seq4.TakeHead();
}));
Assert.Throws<InvalidOperationException>(() => {
var x = seq4.Head;
});
Assert.IsFalse(seq4.Any());
Assert.AreEqual(0, seq4.Count);
}
[Test]
public void RemoveTest()
{
var seq = new ShieldedSeq<int>(
Enumerable.Range(1, 20).ToArray());
Shield.InTransaction(() =>
Assert.IsTrue(seq.Remove(5)));
Assert.AreEqual(19, seq.Count);
Assert.IsTrue(seq.Any());
Assert.AreEqual(1, seq.Head);
for (int i = 1; i <= 20; i++)
if (i == 5)
continue;
else
Assert.AreEqual(i, seq[i > 5 ? i - 2 : i - 1]);
Shield.InTransaction(() =>
Assert.IsTrue(seq.Remove(1)));
Assert.AreEqual(18, seq.Count);
Assert.IsTrue(seq.Any());
Assert.AreEqual(2, seq.Head);
Shield.InTransaction(() =>
Assert.IsTrue(seq.Remove(20)));
Shield.InTransaction(() =>
Assert.IsFalse(seq.Remove(30)));
Assert.AreEqual(17, seq.Count);
Assert.IsTrue(seq.Any());
Assert.AreEqual(2, seq.Head);
Assert.AreEqual(19, seq[16]);
}
[Test]
public void TailPassTest()
{
// pass by the tail - potential commute bug
// - when you append(), and then iterate a seq,
// will you find the new last item missing?
var tailPass = new ShieldedSeq<int>(
Enumerable.Range(1, 5).ToArray());
Shield.InTransaction(() => {
tailPass.Append(6);
int counter = 0;
foreach (var i in tailPass)
counter++;
Assert.AreEqual(6, counter);
});
Shield.InTransaction(() => {
// this causes immediate degeneration of the Append commute.
var h = tailPass.Any();
tailPass.Append(7);
int counter = 0;
foreach (var i in tailPass)
counter++;
Assert.AreEqual(7, counter);
});
Shield.InTransaction(() => {
tailPass.Append(8);
tailPass.Append(9);
Assert.AreEqual(1, tailPass.Head);
int counter = 0;
foreach (var i in tailPass)
Assert.AreEqual(++counter, i);
Assert.AreEqual(9, counter);
});
Assert.AreEqual(9, tailPass.Count);
}
[Test]
public void TwoQueuesTest()
{
var seq1 = new ShieldedSeq<int>();
var seq2 = new ShieldedSeq<int>();
// conflict should happen only on the accessed sequence, if we're appending to two..
int transactionCount = 0;
Thread oneTimer = null;
Shield.InTransaction(() => {
transactionCount++;
seq2.Append(2);
seq1.Append(1);
if (oneTimer == null)
{
oneTimer = new Thread(() => Shield.InTransaction(() =>
{
seq2.Append(1);
}));
oneTimer.Start();
oneTimer.Join();
}
var b = seq1.Any();
});
Assert.AreEqual(1, transactionCount);
Assert.AreEqual(2, seq2.Count);
Assert.IsTrue(seq2.Any());
Assert.AreEqual(1, seq2[0]);
Assert.AreEqual(2, seq2[1]);
Shield.InTransaction(() => { seq1.Clear(); seq2.Clear(); });
transactionCount = 0;
oneTimer = null;
Shield.InTransaction(() => {
transactionCount++;
seq1.Append(1);
seq2.Append(2);
if (oneTimer == null)
{
oneTimer = new Thread(() => Shield.InTransaction(() =>
{
seq2.Append(1);
}));
oneTimer.Start();
oneTimer.Join();
}
// the difference is here - seq2:
var b = seq2.Any();
});
Assert.AreEqual(2, transactionCount);
Assert.AreEqual(2, seq2.Count);
Assert.IsTrue(seq2.Any());
Assert.AreEqual(1, seq2[0]);
Assert.AreEqual(2, seq2[1]);
}
[Test]
public void InsertTest()
{
var emptySeq = new ShieldedSeqNc<int>();
Shield.InTransaction(() => emptySeq.Insert(0, 1));
Assert.IsTrue(emptySeq.Any());
Assert.AreEqual(1, emptySeq[0]);
Assert.Throws<InvalidOperationException>(() => emptySeq.Count());
Shield.InTransaction(() =>
Assert.AreEqual(1, emptySeq.Count()));
var seq = new ShieldedSeq<int>(2, 3, 4, 6, 7);
Shield.InTransaction(() => seq.Insert(0, 1));
Assert.AreEqual(6, seq.Count);
Assert.AreEqual(1, seq[0]);
Assert.AreEqual(2, seq[1]);
Shield.InTransaction(() => seq.Insert(4, 5));
Assert.AreEqual(7, seq.Count);
Assert.AreEqual(1, seq[0]);
Assert.AreEqual(2, seq[1]);
Assert.AreEqual(5, seq[4]);
Assert.AreEqual(6, seq[5]);
Shield.InTransaction(() => seq.Insert(7, 8));
Assert.AreEqual(8, seq.Count);
Shield.InTransaction(() => {
for (int i=0; i < seq.Count; i++)
Assert.AreEqual(i + 1, seq[i]);
});
}
[Test]
public void RemoveAllWithExceptions()
{
var seq = new ShieldedSeq<int>(Enumerable.Range(1, 10).ToArray());
Shield.InTransaction(() =>
// handling the exception here means the transaction will commit.
Assert.Throws<InvalidOperationException>(() =>
seq.RemoveAll(i => {
if (i == 5)
throw new InvalidOperationException();
return true;
})));
Assert.AreEqual(5, seq[0]);
Assert.AreEqual(6, seq.Count);
}
[Test]
public void RemoveAllLastElement()
{
var seq = new ShieldedSeq<int>(Enumerable.Range(1, 10).ToArray());
Shield.InTransaction(() => seq.RemoveAll(i => i == 10));
Shield.InTransaction(() =>
Assert.IsTrue(seq.SequenceEqual(Enumerable.Range(1, 9))));
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Reflection;
using Common.Logging;
using Spring.Expressions;
using Spring.Messaging.Nms.Core;
using Spring.Messaging.Nms.Support;
using Spring.Messaging.Nms.Support.Converter;
using Spring.Messaging.Nms.Support.Destinations;
using Spring.Messaging.Nms.Listener;
using Spring.Util;
using Apache.NMS;
namespace Spring.Messaging.Nms.Listener.Adapter
{
/// <summary>
/// Message listener adapter that delegates the handling of messages to target
/// listener methods via reflection, with flexible message type conversion.
/// Allows listener methods to operate on message content types, completely
/// independent from the NMS API.
/// </summary>
/// <remarks>
/// <para>By default, the content of incoming messages gets extracted before
/// being passed into the target listener method, to let the target method
/// operate on message content types such as String or byte array instead of
/// the raw Message. Message type conversion is delegated to a Spring
/// <see cref="IMessageConverter"/>. By default, a <see cref="SimpleMessageConverter"/>
/// will be used. (If you do not want such automatic message conversion taking
/// place, then be sure to set the <see cref="MessageConverter"/> property
/// to <code>null</code>.)
/// </para>
/// <para>If a target listener method returns a non-null object (typically of a
/// message content type such as <code>String</code> or byte array), it will get
/// wrapped in a NMS <code>Message</code> and sent to the response destination
/// (either the NMS "reply-to" destination or the <see cref="defaultResponseDestination"/>
/// specified.
/// </para>
/// <para>
/// The sending of response messages is only available when
/// using the <see cref="ISessionAwareMessageListener"/> entry point (typically through a
/// Spring message listener container). Usage as standard NMS MessageListener
/// does <i>not</i> support the generation of response messages.
/// </para>
/// <para>Consult the reference documentation for examples of method signatures compliant with this
/// adapter class.
/// </para>
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Mark Pollack (.NET)</author>
public class MessageListenerAdapter : IMessageListener, ISessionAwareMessageListener
{
#region Logging
private readonly ILog logger = LogManager.GetLogger(typeof (MessageListenerAdapter));
#endregion
#region Fields
/// <summary>
/// The default handler method name.
/// </summary>
public static string ORIGINAL_DEFAULT_HANDLER_METHOD = "HandleMessage";
private object handlerObject;
private string defaultHandlerMethod = ORIGINAL_DEFAULT_HANDLER_METHOD;
private IExpression processingExpression;
private object defaultResponseDestination;
private IDestinationResolver destinationResolver = new DynamicDestinationResolver();
private IMessageConverter messageConverter;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class with default settings.
/// </summary>
public MessageListenerAdapter()
{
InitDefaultStrategies();
handlerObject = this;
}
/// <summary>
/// Initializes a new instance of the <see cref="MessageListenerAdapter"/> class for the given handler object
/// </summary>
/// <param name="handlerObject">The delegate object.</param>
public MessageListenerAdapter(object handlerObject)
{
InitDefaultStrategies();
this.handlerObject = handlerObject;
}
#endregion
/// <summary>
/// Gets or sets the handler object to delegate message listening to.
/// </summary>
/// <remarks>
/// Specified listener methods have to be present on this target object.
/// If no explicit handler object has been specified, listener
/// methods are expected to present on this adapter instance, that is,
/// on a custom subclass of this adapter, defining listener methods.
/// </remarks>
/// <value>The handler object.</value>
public object HandlerObject
{
get { return handlerObject; }
set { handlerObject = value; }
}
/// <summary>
/// Gets or sets the default handler method to delegate to,
/// for the case where no specific listener method has been determined.
/// Out-of-the-box value is <see cref="ORIGINAL_DEFAULT_HANDLER_METHOD"/> ("HandleMessage"}.
/// </summary>
/// <value>The default handler method.</value>
public string DefaultHandlerMethod
{
get { return defaultHandlerMethod; }
set
{
defaultHandlerMethod = value;
processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)");
}
}
/// <summary>
/// Sets the default destination to send response messages to. This will be applied
/// in case of a request message that does not carry a "JMSReplyTo" field.
/// Response destinations are only relevant for listener methods that return
/// result objects, which will be wrapped in a response message and sent to a
/// response destination.
/// <para>
/// Alternatively, specify a "DefaultResponseQueueName" or "DefaultResponseTopicName",
/// to be dynamically resolved via the DestinationResolver.
/// </para>
/// </summary>
/// <value>The default response destination.</value>
public object DefaultResponseDestination
{
set { defaultResponseDestination = value; }
}
/// <summary>
/// Sets the name of the default response queue to send response messages to.
/// This will be applied in case of a request message that does not carry a
/// "NMSReplyTo" field.
/// <para>Alternatively, specify a JMS Destination object as "defaultResponseDestination".</para>
/// </summary>
/// <value>The name of the default response destination queue.</value>
public string DefaultResponseQueueName
{
set { defaultResponseDestination = new DestinationNameHolder(value, false); }
}
/// <summary>
/// Sets the name of the default response topic to send response messages to.
/// This will be applied in case of a request message that does not carry a
/// "NMSReplyTo" field.
/// <para>Alternatively, specify a JMS Destination object as "defaultResponseDestination".</para>
/// </summary>
/// <value>The name of the default response destination topic.</value>
public string DefaultResponseTopicName
{
set { defaultResponseDestination = new DestinationNameHolder(value, true); }
}
/// <summary>
/// Gets or sets the destination resolver that should be used to resolve response
/// destination names for this adapter.
/// <para>The default resolver is a <see cref="DynamicDestinationResolver"/>.
/// Specify another implementation, for other strategies, perhaps from a directory service.</para>
/// </summary>
/// <value>The destination resolver.</value>
public IDestinationResolver DestinationResolver
{
get { return destinationResolver; }
set
{
AssertUtils.ArgumentNotNull(value, "DestinationResolver must not be null");
destinationResolver = value;
}
}
/// <summary>
/// Gets or sets the message converter that will convert incoming JMS messages to
/// listener method arguments, and objects returned from listener
/// methods back to NMS messages.
/// </summary>
/// <remarks>
/// <para>The default converter is a {@link SimpleMessageConverter}, which is able
/// to handle BytesMessages}, TextMessages, MapMessages, and ObjectMessages.
/// </para>
/// </remarks>
/// <value>The message converter.</value>
public IMessageConverter MessageConverter
{
get { return messageConverter; }
set { messageConverter = value; }
}
/// <summary>
/// Standard JMS {@link MessageListener} entry point.
/// <para>Delegates the message to the target listener method, with appropriate
/// conversion of the message arguments
/// </para>
/// </summary>
/// <remarks>
/// In case of an exception, the <see cref="HandleListenerException"/> method will be invoked.
/// <b>Note</b>
/// Does not support sending response messages based on
/// result objects returned from listener methods. Use the
/// <see cref="ISessionAwareMessageListener"/> entry point (typically through a Spring
/// message listener container) for handling result objects as well.
/// </remarks>
/// <param name="message">The incoming message.</param>
public void OnMessage(IMessage message)
{
try
{
OnMessage(message, null);
}
catch (Exception e)
{
HandleListenerException(e);
}
}
/// <summary>
/// Spring <see cref="ISessionAwareMessageListener"/> entry point.
/// <para>
/// Delegates the message to the target listener method, with appropriate
/// conversion of the message argument. If the target method returns a
/// non-null object, wrap in a NMS message and send it back.
/// </para>
/// </summary>
/// <param name="message">The incoming message.</param>
/// <param name="session">The session to operate on.</param>
public void OnMessage(IMessage message, ISession session)
{
if (handlerObject != this)
{
if (typeof(ISessionAwareMessageListener).IsInstanceOfType(handlerObject))
{
if (session != null)
{
((ISessionAwareMessageListener) handlerObject).OnMessage(message, session);
return;
}
else if (!typeof(IMessageListener).IsInstanceOfType(handlerObject))
{
throw new InvalidOperationException("MessageListenerAdapter cannot handle a " +
"SessionAwareMessageListener delegate if it hasn't been invoked with a Session itself");
}
}
if (typeof(IMessageListener).IsInstanceOfType(handlerObject))
{
((IMessageListener)handlerObject).OnMessage(message);
return;
}
}
// Regular case: find a handler method reflectively.
object convertedMessage = ExtractMessage(message);
IDictionary vars = new Hashtable();
vars["convertedObject"] = convertedMessage;
//Need to parse each time since have overloaded methods and
//expression processor caches target of first invocation.
//TODO - check JIRA as I believe this has been fixed, otherwise, use regular reflection. -MLP
//processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)");
//Invoke message handler method and get result.
object result;
try
{
result = processingExpression.GetValue(handlerObject, vars);
}
catch (NMSException)
{
throw;
}
// Will only happen if dynamic method invocation falls back to standard reflection.
catch (TargetInvocationException ex)
{
Exception targetEx = ex.InnerException;
if (ObjectUtils.IsAssignable(typeof(NMSException), targetEx))
{
throw ReflectionUtils.UnwrapTargetInvocationException(ex);
}
else
{
throw new ListenerExecutionFailedException("Listener method '" + defaultHandlerMethod + "' threw exception", targetEx);
}
}
catch (Exception ex)
{
throw new ListenerExecutionFailedException("Failed to invoke target method '" + defaultHandlerMethod +
"' with argument " + convertedMessage, ex);
}
if (result != null)
{
HandleResult(result, message, session);
}
else
{
logger.Debug("No result object given - no result to handle");
}
}
/// <summary>
/// Initialize the default implementations for the adapter's strategies.
/// </summary>
protected virtual void InitDefaultStrategies()
{
MessageConverter = new SimpleMessageConverter();
processingExpression = Expression.Parse(defaultHandlerMethod + "(#convertedObject)");
}
/// <summary>
/// Handle the given exception that arose during listener execution.
/// The default implementation logs the exception at error level.
/// <para>This method only applies when used as standard NMS MessageListener.
/// In case of the Spring <see cref="ISessionAwareMessageListener"/> mechanism,
/// exceptions get handled by the caller instead.
/// </para>
/// </summary>
/// <param name="ex">The exception to handle.</param>
protected virtual void HandleListenerException(Exception ex)
{
logger.Error("Listener execution failed", ex);
}
/// <summary>
/// Extract the message body from the given message.
/// </summary>
/// <param name="message">The message.</param>
/// <returns>the content of the message, to be passed into the
/// listener method as argument</returns>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
private object ExtractMessage(IMessage message)
{
IMessageConverter converter = MessageConverter;
if (converter != null)
{
return converter.FromMessage(message);
}
return message;
}
/// <summary>
/// Gets the name of the listener method that is supposed to
/// handle the given message.
/// The default implementation simply returns the configured
/// default listener method, if any.
/// </summary>
/// <param name="originalIMessage">The NMS request message.</param>
/// <param name="extractedMessage">The converted JMS request message,
/// to be passed into the listener method as argument.</param>
/// <returns>the name of the listener method (never <code>null</code>)</returns>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
protected virtual string GetHandlerMethodName(IMessage originalIMessage, object extractedMessage)
{
return DefaultHandlerMethod;
}
/// <summary>
/// Handles the given result object returned from the listener method, sending a response message back.
/// </summary>
/// <param name="result">The result object to handle (never <code>null</code>).</param>
/// <param name="request">The original request message.</param>
/// <param name="session">The session to operate on (may be <code>null</code>).</param>
protected virtual void HandleResult(object result, IMessage request, ISession session)
{
if (session != null)
{
if (logger.IsDebugEnabled)
{
logger.Debug("Listener method returned result [" + result +
"] - generating response message for it");
}
IMessage response = BuildMessage(session, result);
PostProcessResponse(request, response);
IDestination destination = GetResponseDestination(request, response, session);
SendResponse(session, destination, response);
}
else
{
if (logger.IsDebugEnabled)
{
logger.Debug("Listener method returned result [" + result +
"]: not generating response message for it because of no NMS ISession given");
}
}
}
/// <summary>
/// Builds a JMS message to be sent as response based on the given result object.
/// </summary>
/// <param name="session">The JMS Session to operate on.</param>
/// <param name="result">The content of the message, as returned from the listener method.</param>
/// <returns>the JMS <code>Message</code> (never <code>null</code>)</returns>
/// <exception cref="MessageConversionException">If there was an error in message conversion</exception>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
protected virtual IMessage BuildMessage(ISession session, Object result)
{
IMessageConverter converter = MessageConverter;
if (converter != null)
{
return converter.ToMessage(result, session);
}
else
{
IMessage msg = result as IMessage;
if (msg == null)
{
throw new MessageConversionException(
"No IMessageConverter specified - cannot handle message [" + result + "]");
}
return msg;
}
}
/// <summary>
/// Post-process the given response message before it will be sent. The default implementation
/// sets the response's correlation id to the request message's correlation id.
/// </summary>
/// <param name="request">The original incoming message.</param>
/// <param name="response">The outgoing JMS message about to be sent.</param>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
protected virtual void PostProcessResponse(IMessage request, IMessage response)
{
response.NMSCorrelationID = request.NMSCorrelationID;
}
/// <summary>
/// Determine a response destination for the given message.
/// </summary>
/// <remarks>
/// <para>The default implementation first checks the JMS Reply-To
/// Destination of the supplied request; if that is not <code>null</code>
/// it is returned; if it is <code>null</code>, then the configured
/// <see cref="DefaultResponseDestination"/> default response destination
/// is returned; if this too is <code>null</code>, then an
/// <see cref="InvalidDestinationException"/>is thrown.
/// </para>
/// </remarks>
/// <param name="request">The original incoming message.</param>
/// <param name="response">Tthe outgoing message about to be sent.</param>
/// <param name="session">The session to operate on.</param>
/// <returns>the response destination (never <code>null</code>)</returns>
/// <exception cref="NMSException">if thrown by NMS API methods</exception>
/// <exception cref="InvalidDestinationException">if no destination can be determined.</exception>
protected virtual IDestination GetResponseDestination(IMessage request, IMessage response, ISession session)
{
IDestination replyTo = request.NMSReplyTo;
if (replyTo == null)
{
replyTo = ResolveDefaultResponseDestination(session);
if (replyTo == null)
{
throw new InvalidDestinationException("Cannot determine response destination: " +
"Request message does not contain reply-to destination, and no default response destination set.");
}
}
return replyTo;
}
/// <summary>
/// Resolves the default response destination into a Destination, using this
/// accessor's <see cref="IDestinationResolver"/> in case of a destination name.
/// </summary>
/// <param name="session">The session to operate on.</param>
/// <returns>The located destination</returns>
protected virtual IDestination ResolveDefaultResponseDestination(ISession session)
{
IDestination dest = defaultResponseDestination as IDestination;
if (dest != null)
{
return dest;
}
DestinationNameHolder destNameHolder = defaultResponseDestination as DestinationNameHolder;
if (destNameHolder != null)
{
return DestinationResolver.ResolveDestinationName(session, destNameHolder.Name, destNameHolder.IsTopic);
}
return null;
}
/// <summary>
/// Sends the given response message to the given destination.
/// </summary>
/// <param name="session">The session to operate on.</param>
/// <param name="destination">The destination to send to.</param>
/// <param name="response">The outgoing message about to be sent.</param>
protected virtual void SendResponse(ISession session, IDestination destination, IMessage response)
{
IMessageProducer producer = session.CreateProducer(destination);
try
{
PostProcessProducer(producer, response);
producer.Send(response);
}
finally
{
NmsUtils.CloseMessageProducer(producer);
}
}
/// <summary>
/// Post-process the given message producer before using it to send the response.
/// The default implementation is empty.
/// </summary>
/// <param name="producer">The producer that will be used to send the message.</param>
/// <param name="response">The outgoing message about to be sent.</param>
protected virtual void PostProcessProducer(IMessageProducer producer, IMessage response)
{
}
}
/// <summary>
/// Internal class combining a destination name and its target destination type (queue or topic).
/// </summary>
internal class DestinationNameHolder
{
private readonly string name;
private readonly bool isTopic;
public DestinationNameHolder(string name, bool isTopic)
{
this.name = name;
this.isTopic = isTopic;
}
public string Name
{
get { return name; }
}
public bool IsTopic
{
get { return isTopic; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using ImGuiNET;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Nez.Sprites;
using Num = System.Numerics;
namespace Nez.ImGuiTools
{
public class SpriteAtlasEditorWindow
{
enum Origin
{
TopLeft,
Top,
TopRight,
Left,
Center,
Right,
BottomLeft,
Bottom,
BottomRight,
Custom
}
struct StartEndInt { public int Start, End; }
/// <summary>
/// default location of SpriteAtlasPacker.exe. If you use a non-standard Nez install location set this before using the atlas editor
/// </summary>
public static string PathToSpritePacker = "../../../Nez/Nez.SpriteAtlasPacker/PrebuiltExecutable/SpriteAtlasPacker.exe";
/// <summary>
/// default export path for atlases generated from a folder
/// </summary>
public static string AtlasExportFolder = "../../Content/Atlases";
string _sourceImageFile;
string _sourceAtlasFile;
Num.Vector2 _textureSize;
float _textureAspectRatio;
IntPtr _texturePtr;
bool _textureLoadedThisFrame;
float _imageZoom = 1;
Num.Vector2 _imagePosition;
SpriteAtlasData _spriteAtlasData = new SpriteAtlasData();
string[] _originEnumNames;
string _stringBuffer = "";
StartEndInt _startEndInt;
int _animationPreviewSize = 50;
bool _hasSlicedContent;
bool _atlasAllowsAnimationEditing;
bool _showSourceRectIndexes = true;
List<int> _nonEditableAnimations = new List<int>();
public SpriteAtlasEditorWindow()
{
_originEnumNames = Enum.GetNames(typeof(Origin));
PathToSpritePacker = Path.GetFullPath(PathToSpritePacker);
if (!File.Exists(PathToSpritePacker))
Debug.Warn("PathToSpritePacker doesnt exist! " + PathToSpritePacker);
// ensure out export folder exists
AtlasExportFolder = Path.GetFullPath(AtlasExportFolder);
Directory.CreateDirectory(AtlasExportFolder);
}
public bool Show()
{
ImGui.SetNextWindowPos(new Num.Vector2(0, 25), ImGuiCond.FirstUseEver);
ImGui.SetNextWindowSize(new Num.Vector2(Screen.Width / 2, Screen.Height / 2), ImGuiCond.FirstUseEver);
var isOpen = true;
if (ImGui.Begin("Sprite Atlas Editor", ref isOpen, ImGuiWindowFlags.MenuBar))
{
DrawMenuBar();
if (_hasSlicedContent)
{
ImGui.BeginChild("Slice Origins", new Num.Vector2(250, 0), true);
DrawLeftPane();
ImGui.EndChild();
ImGui.SameLine();
}
var frame = ImGui.GetStyle().FramePadding.X + ImGui.GetStyle().FrameBorderSize;
var rightPanePaddedSize = 300 + frame * 2;
if (!_hasSlicedContent)
rightPanePaddedSize = 0;
ImGui.BeginChild("item view", new Num.Vector2(ImGui.GetContentRegionAvail().X - rightPanePaddedSize, 0), false, ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse);
if (_textureLoadedThisFrame)
{
FrameImage();
_textureLoadedThisFrame = false;
}
DrawCenterPane();
ImGui.EndChild();
ImGui.SameLine();
if (_hasSlicedContent)
{
ImGui.BeginChild("Right Pane", new Num.Vector2(300, 0), true);
DrawRightPane();
ImGui.EndChild();
}
ImGui.End();
}
return isOpen;
}
void LoadTextureAndAtlasFiles()
{
if (_texturePtr != IntPtr.Zero)
Core.GetGlobalManager<ImGuiManager>().UnbindTexture(_texturePtr);
_spriteAtlasData.Clear();
_nonEditableAnimations.Clear();
_atlasAllowsAnimationEditing = true;
_hasSlicedContent = false;
var _atlasTexture = Texture2D.FromStream(Core.GraphicsDevice, File.OpenRead(_sourceImageFile));
_textureSize = new Num.Vector2(_atlasTexture.Width, _atlasTexture.Height);
_textureAspectRatio = _textureSize.X / _textureSize.Y;
_texturePtr = Core.GetGlobalManager<ImGuiManager>().BindTexture(_atlasTexture);
_textureLoadedThisFrame = true;
if (File.Exists(_sourceAtlasFile))
{
_hasSlicedContent = true;
_spriteAtlasData = SpriteAtlasLoader.ParseSpriteAtlasData(_sourceAtlasFile, true);
// ensure animations are contiguous, since that is all we support.
// First check that all frames are in order in the animations
for (var j = 0; j < _spriteAtlasData.AnimationFrames.Count; j++)
{
var animation = _spriteAtlasData.AnimationFrames[j];
for (var i = 0; i < animation.Count; i++)
{
if (i == 0)
continue;
if (animation[i] != animation[i - 1] + 1)
{
_atlasAllowsAnimationEditing = false;
_nonEditableAnimations.Add(j);
}
}
}
// Next check that all frames are in order, ghetto style. We check that all the y-values of the rects
// always increase or stay the same. Not perfect by any means, but we dont know if this is padded in some
// odd way or contains sprites of odd sizes so this is a quick and dirty solution.
var lastRectY = -1;
for (var i = 0; i < _spriteAtlasData.SourceRects.Count; i++)
{
if (i == 0 || lastRectY <= _spriteAtlasData.SourceRects[i].Y)
{
lastRectY = _spriteAtlasData.SourceRects[i].Y;
continue;
}
_atlasAllowsAnimationEditing = false;
return;
}
}
}
void GenerateSpriteAtlasFromFolder(string path)
{
// use the chosen folder name as the atlas name
var name = Path.GetFileName(path);
var args = $"{PathToSpritePacker} -image:{AtlasExportFolder}/{name}.png -map:{AtlasExportFolder}/{name}.atlas -fps:7 {path}";
Process.Start(new ProcessStartInfo
{
FileName = "mono",
Arguments = args,
WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit();
_sourceImageFile = Path.Combine(AtlasExportFolder, name + ".png");
_sourceAtlasFile = Path.Combine(AtlasExportFolder, name + ".atlas");
LoadTextureAndAtlasFiles();
}
#region Drawing Methods
int _globalOriginEnumValue;
void DrawLeftPane()
{
Origin OriginIndex(Vector2 origin)
{
switch (origin)
{
case Vector2 o when o.X == 0 && o.Y == 0: // tl
return Origin.TopLeft;
case Vector2 o when o.X == 0.5f && o.Y == 0: // t
return Origin.Top;
case Vector2 o when o.X == 1 && o.Y == 0: // tr
return Origin.TopRight;
case Vector2 o when o.X == 0 && o.Y == 0.5f: // l
return Origin.Left;
case Vector2 o when o.X == 0.5f && o.Y == 0.5f: // center
return Origin.Center;
case Vector2 o when o.X == 1 && o.Y == 0.5f: // right
return Origin.Right;
case Vector2 o when o.X == 0 && o.Y == 1: // bl
return Origin.BottomLeft;
case Vector2 o when o.X == 0.5f && o.Y == 1: // b
return Origin.Bottom;
case Vector2 o when o.X == 1 && o.Y == 1: // br
return Origin.BottomRight;
default:
return Origin.Custom;
}
}
Vector2 OriginValue(Origin origin, Vector2 currentOrigin)
{
switch (origin)
{
case Origin.TopLeft: return new Vector2(0, 0);
case Origin.Top: return new Vector2(0.5f, 0);
case Origin.TopRight: return new Vector2(1, 0);
case Origin.Left: return new Vector2(0, 0.5f);
case Origin.Center: return new Vector2(0.5f, 0.5f);
case Origin.Right: return new Vector2(1, 0.5f);
case Origin.BottomLeft: return new Vector2(0, 1);
case Origin.Bottom: return new Vector2(0.5f, 1);
case Origin.BottomRight: return new Vector2(1, 1);
default: return currentOrigin + new Vector2(0.01f, 0.01f);
}
}
if (NezImGui.CenteredButton("Set All Origins", 0.75f))
{
_globalOriginEnumValue = 7;
ImGui.OpenPopup("set-all-origins");
}
NezImGui.MediumVerticalSpace();
if (ImGui.BeginPopup("set-all-origins"))
{
ImGui.Combo("###global-origin", ref _globalOriginEnumValue, _originEnumNames, _originEnumNames.Length);
if (ImGui.Button("Set All Origins"))
{
for (var i = 0; i < _spriteAtlasData.Origins.Count; i++)
_spriteAtlasData.Origins[i] = OriginValue((Origin)_globalOriginEnumValue, _spriteAtlasData.Origins[i]);
ImGui.CloseCurrentPopup();
}
ImGui.EndPopup();
}
for (var i = 0; i < _spriteAtlasData.Origins.Count; i++)
{
ImGui.PushID(i);
var name = _spriteAtlasData.Names[i];
if (ImGui.InputText("Name", ref name, 25))
_spriteAtlasData.Names[i] = name;
var origin = _spriteAtlasData.Origins[i].ToNumerics();
if (ImGui.SliderFloat2("Origin", ref origin, 0f, 1f))
_spriteAtlasData.Origins[i] = origin.ToXNA();
var originEnum = OriginIndex(_spriteAtlasData.Origins[i]);
var originEnumValue = (int)originEnum;
if (ImGui.Combo($"###enum_{i}", ref originEnumValue, _originEnumNames, _originEnumNames.Length))
_spriteAtlasData.Origins[i] = OriginValue((Origin)originEnumValue, _spriteAtlasData.Origins[i]);
ImGui.Separator();
ImGui.PopID();
}
}
void DrawCenterPane()
{
if (ImGui.IsWindowFocused() && ImGui.GetIO().MouseWheel != 0)
{
var minZoom = 0.2f;
var maxZoom = 10f;
var oldSize = _imageZoom * _textureSize;
var zoomSpeed = _imageZoom * 0.1f;
_imageZoom += Math.Min(maxZoom - _imageZoom, ImGui.GetIO().MouseWheel * zoomSpeed);
_imageZoom = Mathf.Clamp(_imageZoom, minZoom, maxZoom);
// zoom in, move up/left, zoom out the opposite
var deltaSize = oldSize - (_imageZoom * _textureSize);
_imagePosition += deltaSize * 0.5f;
}
ImGui.GetIO().ConfigWindowsResizeFromEdges = true;
if (ImGui.IsWindowFocused() && ImGui.IsMouseDown(0) && ImGui.GetIO().KeyAlt)
{
_imagePosition += ImGui.GetMouseDragDelta(0);
ImGui.ResetMouseDragDelta(0);
}
// clamp in such a way that we keep some part of the image visible
var min = -(_textureSize * _imageZoom) * 0.8f;
var max = ImGui.GetContentRegionAvail() * 0.8f;
_imagePosition = Num.Vector2.Clamp(_imagePosition, min, max);
ImGui.SetCursorPos(_imagePosition);
var cursorPosImageTopLeft = ImGui.GetCursorScreenPos();
ImGui.Image(_texturePtr, _textureSize * _imageZoom);
for (var i = 0; i < _spriteAtlasData.SourceRects.Count; i++)
{
DrawRect(cursorPosImageTopLeft, _spriteAtlasData.SourceRects[i], i);
DrawOrigin(cursorPosImageTopLeft, _spriteAtlasData.Origins[i], _spriteAtlasData.SourceRects[i]);
}
// now, we draw over the image any controls
if (_texturePtr != IntPtr.Zero)
DrawControlsOverImage();
}
void DrawMenuBar()
{
var newAtlas = false;
var openFile = false;
if (ImGui.BeginMenuBar())
{
if (ImGui.BeginMenu("File"))
{
if (ImGui.MenuItem("New Atlas from Folder"))
newAtlas = true;
if (ImGui.MenuItem("Load Atlas or PNG"))
openFile = true;
if (ImGui.MenuItem("Save Atlas", _spriteAtlasData.SourceRects.Count > 0))
_spriteAtlasData.SaveToFile(_sourceAtlasFile);
ImGui.EndMenu();
}
ImGui.EndMenuBar();
}
if (newAtlas)
ImGui.OpenPopup("new-atlas");
if (openFile)
ImGui.OpenPopup("open-file");
NewAtlasPopup();
OpenFilePopup();
}
void NewAtlasPopup()
{
var isOpen = true;
if (ImGui.BeginPopupModal("new-atlas", ref isOpen, ImGuiWindowFlags.NoTitleBar))
{
var picker = FilePicker.GetFolderPicker(this, new DirectoryInfo(Environment.CurrentDirectory).Parent.FullName);
picker.DontAllowTraverselBeyondRootFolder = false;
if (picker.Draw())
{
GenerateSpriteAtlasFromFolder(picker.SelectedFile);
FilePicker.RemoveFilePicker(this);
}
ImGui.EndPopup();
}
}
void OpenFilePopup()
{
var isOpen = true;
if (ImGui.BeginPopupModal("open-file", ref isOpen, ImGuiWindowFlags.NoTitleBar))
{
var picker = FilePicker.GetFilePicker(this, Path.Combine(Environment.CurrentDirectory, "Content"), ".png|.atlas");
picker.DontAllowTraverselBeyondRootFolder = true;
if (picker.Draw())
{
var file = picker.SelectedFile;
if (file.EndsWith(".png"))
{
_sourceImageFile = file;
_sourceAtlasFile = file.Replace(".png", ".atlas");
}
else
{
_sourceImageFile = file.Replace(".atlas", ".png");
_sourceAtlasFile = file;
}
LoadTextureAndAtlasFiles();
FilePicker.RemoveFilePicker(this);
}
ImGui.EndPopup();
}
}
int _width = 16, _height = 16, _padding = 1, _frames = 10;
void DrawAtlasSlicerPopup()
{
var isOpen = true;
if (ImGui.BeginPopupModal("atlas-slicer", ref isOpen, ImGuiWindowFlags.AlwaysAutoResize))
{
ImGui.InputInt("Width", ref _width);
ImGui.InputInt("Height", ref _height);
ImGui.InputInt("Max Frames", ref _frames);
ImGui.InputInt("Padding", ref _padding);
if (ImGui.Button("Slice"))
GenerateRects(_width, _height, _frames, _padding);
ImGui.SameLine();
if (ImGui.Button("Done"))
ImGui.CloseCurrentPopup();
ImGui.EndPopup();
}
}
void DrawControlsOverImage()
{
ImGui.SetCursorPos(Num.Vector2.Zero);
if (ImGui.Button("Center"))
CenterImage();
// ImGui.SameLine(ImGui.GetWindowWidth() - 70);
ImGui.SameLine();
if (ImGui.Button("Frame"))
FrameImage();
ImGui.SameLine();
if (ImGui.Button("Slice"))
ImGui.OpenPopup("atlas-slicer");
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 160);
ImGui.Checkbox("Show Rect Indexes", ref _showSourceRectIndexes);
DrawAtlasSlicerPopup();
}
void DrawRightPane()
{
if (!_atlasAllowsAnimationEditing)
{
ImGui.PushStyleColor(ImGuiCol.Text, Color.Red.PackedValue);
ImGui.TextWrapped("Edit/Add animations at your own risk! The loaded atlas either does not have contiguous frames or contains animations that are not contiguous.");
ImGui.PopStyleColor();
NezImGui.MediumVerticalSpace();
}
if (NezImGui.CenteredButton("Add Animation", 0.5f))
ImGui.OpenPopup("add-animation");
NezImGui.MediumVerticalSpace();
for (var i = 0; i < _spriteAtlasData.AnimationNames.Count; i++)
{
var isEditable = !_nonEditableAnimations.Contains(i);
ImGui.PushID(i);
var didNotDeleteAnimation = true;
if (ImGui.CollapsingHeader(_spriteAtlasData.AnimationNames[i] + $"###anim{i}", ref didNotDeleteAnimation))
{
var name = _spriteAtlasData.AnimationNames[i];
if (ImGui.InputText("Name", ref name, 25))
_spriteAtlasData.AnimationNames[i] = name;
var fps = _spriteAtlasData.AnimationFps[i];
if (ImGui.SliderInt("Frame Rate", ref fps, 0, 24))
_spriteAtlasData.AnimationFps[i] = fps;
var frames = _spriteAtlasData.AnimationFrames[i];
if (isEditable)
{
if (frames.Count == 0)
{
_startEndInt.Start = _startEndInt.End = 0;
}
else if (frames.Count == 1)
{
_startEndInt.Start = frames[0];
_startEndInt.End = frames[0];
}
else
{
_startEndInt.Start = frames[0];
_startEndInt.End = frames.LastItem();
}
var framesChanged = ImGui.SliderInt("Start Frame", ref _startEndInt.Start, 0, _startEndInt.End);
framesChanged |= ImGui.SliderInt("End Frame", ref _startEndInt.End, _startEndInt.Start, _spriteAtlasData.SourceRects.Count - 1);
if (framesChanged)
{
frames.Clear();
for (var j = _startEndInt.Start; j <= _startEndInt.End; j++)
frames.Add(j);
}
}
if (frames.Count > 0)
{
var secondsPerFrame = 1 / (float)fps;
var iterationDuration = secondsPerFrame * (float)frames.Count;
var currentElapsed = Time.TotalTime % iterationDuration;
var desiredFrame = Mathf.FloorToInt(currentElapsed / secondsPerFrame);
var rect = _spriteAtlasData.SourceRects[frames[desiredFrame]];
var uv0 = rect.Location.ToNumerics() / _textureSize;
var uv1 = rect.GetSize().ToNumerics() / _textureSize;
var size = CalcBestFitRegion(new Num.Vector2(_animationPreviewSize), rect.GetSize().ToNumerics());
ImGui.SetCursorPosX((ImGui.GetWindowContentRegionWidth() - size.X) / 2f);
ImGui.Image(_texturePtr, size, uv0, uv0 + uv1);
}
NezImGui.SmallVerticalSpace();
}
if (!didNotDeleteAnimation)
{
_spriteAtlasData.AnimationNames.RemoveAt(i);
_spriteAtlasData.AnimationFrames.RemoveAt(i);
_spriteAtlasData.AnimationFps.RemoveAt(i);
break;
}
ImGui.PopID();
}
NezImGui.SmallVerticalSpace();
ImGui.SliderInt("Preview Size", ref _animationPreviewSize, 50, 150);
if (ImGui.BeginPopup("add-animation"))
{
ImGui.Text("Animation Name");
ImGui.InputText("##animationName", ref _stringBuffer, 25);
if (ImGui.Button("Cancel"))
{
_stringBuffer = "";
ImGui.CloseCurrentPopup();
}
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.GetItemRectSize().X);
ImGui.PushStyleColor(ImGuiCol.Button, Color.Green.PackedValue);
if (ImGui.Button("Create"))
{
_stringBuffer = _stringBuffer.Length > 0 ? _stringBuffer : Utils.RandomString(8);
_spriteAtlasData.AnimationNames.Add(_stringBuffer);
_spriteAtlasData.AnimationFps.Add(8);
_spriteAtlasData.AnimationFrames.Add(new List<int>());
_stringBuffer = "";
ImGui.CloseCurrentPopup();
}
ImGui.PopStyleColor();
ImGui.EndPopup();
}
}
#endregion
#region Helpers
void DrawRect(Num.Vector2 cursorPos, Rectangle rect, int rectIndex)
{
var topLeftScreen = cursorPos + rect.Location.ToNumerics() * _imageZoom;
ImGui.GetWindowDrawList().AddRect(topLeftScreen, topLeftScreen + rect.GetSize().ToNumerics() * _imageZoom, Color.Red.PackedValue);
if (_showSourceRectIndexes)
ImGui.GetWindowDrawList().AddText(topLeftScreen, Color.Yellow.PackedValue, rectIndex.ToString());
}
void DrawOrigin(Num.Vector2 cursorPos, Vector2 origin, Rectangle rect)
{
var topLeftScreen = cursorPos + rect.Location.ToNumerics() * _imageZoom;
var offsetInImage = origin * rect.GetSize().ToVector2() * _imageZoom;
var center = topLeftScreen + offsetInImage.ToNumerics();
ImGui.GetWindowDrawList().AddCircleFilled(center, 5, Color.Orange.PackedValue, 4);
}
void CenterImage()
{
var size = _textureSize * _imageZoom;
_imagePosition = (ImGui.GetContentRegionAvail() - size) * 0.5f;
}
void FrameImage()
{
var fitSize = CalcFitToScreen();
_imageZoom = fitSize.X / _textureSize.X;
_imagePosition = (ImGui.GetContentRegionAvail() - fitSize) * 0.5f;
}
Num.Vector2 CalcFitToScreen()
{
var availSize = ImGui.GetContentRegionMax();
var autoScale = _textureSize / availSize;
if (autoScale.X > autoScale.Y)
return new Num.Vector2(availSize.X, availSize.X / _textureAspectRatio);
return new Num.Vector2(availSize.Y * _textureAspectRatio, availSize.Y);
}
Num.Vector2 CalcFillScreen()
{
var availSize = ImGui.GetContentRegionAvail();
var autoScale = _textureSize / availSize;
if (autoScale.X < autoScale.Y)
return new Num.Vector2(availSize.X, availSize.X / _textureAspectRatio);
return new Num.Vector2(availSize.Y * _textureAspectRatio, availSize.Y);
}
Num.Vector2 CalcBestFitRegion(Num.Vector2 availSize, Num.Vector2 textureSize)
{
var aspectRatio = textureSize.X / textureSize.Y;
var autoScale = _textureSize / availSize;
if (autoScale.X < autoScale.Y)
return new Num.Vector2(availSize.X, availSize.X / aspectRatio);
return new Num.Vector2(availSize.Y * aspectRatio, availSize.Y);
}
void GenerateRects(int cellWidth, int cellHeight, int totalFrames, int padding, int cellOffset = 0)
{
_spriteAtlasData.Clear();
_hasSlicedContent = true;
var cols = _textureSize.X / cellWidth;
var rows = _textureSize.Y / cellHeight;
var i = 0;
for (var y = 0; y < rows; y++)
{
for (var x = 0; x < cols; x++)
{
// skip everything before the first cellOffset
if (i++ < cellOffset)
continue;
var padX = padding * x;
var padY = padding * y;
_spriteAtlasData.SourceRects.Add(new Rectangle(x * cellWidth + padX, y * cellHeight + padY, cellWidth, cellHeight));
_spriteAtlasData.Names.Add($"F{i}");
_spriteAtlasData.Origins.Add(Vector2Ext.HalfVector());
// once we hit the max number of cells to include bail out. were done.
if (_spriteAtlasData.SourceRects.Count == totalFrames)
return;
}
}
}
#endregion
~SpriteAtlasEditorWindow()
{
if (_texturePtr != IntPtr.Zero)
Core.GetGlobalManager<ImGuiManager>().UnbindTexture(_texturePtr);
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace BrightstarDB.Tests.Sparql11TestSuite {
[TestClass]
public partial class Delete : SparqlTest {
public Delete() : base()
{
}
[TestInitialize]
public void SetUp()
{
CreateStore();
}
[TestCleanup]
public void TearDown()
{
DeleteStore();
}
#region Test Methods
[TestMethod]
public void SimpleDelete1() {
ImportData(@"delete/delete-pre-01.ttl");
ExecuteUpdate(@"delete/delete-01.ru");
ValidateUnamedGraph(@"delete/delete-post-01s.ttl");
}
[TestMethod]
public void SimpleDelete2() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ExecuteUpdate(@"delete/delete-02.ru");
ValidateGraph(@"delete/delete-post-01s.ttl", new Uri(@"http://example.org/g1"));
}
[TestMethod]
public void SimpleDelete3() {
ImportData(@"delete/delete-pre-01.ttl");
ExecuteUpdate(@"delete/delete-03.ru");
ValidateUnamedGraph(@"delete/delete-post-01f.ttl");
}
[TestMethod]
public void SimpleDelete4() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ExecuteUpdate(@"delete/delete-04.ru");
ValidateGraph(@"delete/delete-post-01f.ttl", new Uri(@"http://example.org/g1"));
}
[TestMethod]
public void GraphSpecificDelete1() {
ImportData(@"delete/delete-pre-01.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-05.ru");
ValidateUnamedGraph(@"delete/delete-post-01s.ttl");
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
[TestMethod]
public void GraphSpecificDelete2() {
ImportData(@"delete/delete-pre-01.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-06.ru");
ValidateUnamedGraph(@"delete/delete-post-01f.ttl");
ValidateGraph(@"delete/delete-post-02s.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
[TestMethod]
public void SimpleDelete7() {
ImportData(@"delete/delete-pre-01.ttl");
ExecuteUpdate(@"delete/delete-07.ru");
ValidateUnamedGraph(@"delete/delete-post-01f.ttl");
}
[TestMethod]
public void SimpleDelete1With() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ExecuteUpdate(@"delete/delete-with-01.ru");
ValidateGraph(@"delete/delete-post-01s.ttl", new Uri(@"http://example.org/g1"));
}
[TestMethod]
public void SimpleDelete2With() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ExecuteUpdate(@"delete/delete-with-02.ru");
ValidateGraph(@"delete/delete-post-01s.ttl", new Uri(@"http://example.org/g1"));
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
}
[TestMethod]
public void SimpleDelete3With() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ExecuteUpdate(@"delete/delete-with-03.ru");
ValidateGraph(@"delete/delete-post-01f.ttl", new Uri(@"http://example.org/g1"));
}
[TestMethod]
public void SimpleDelete4With() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ExecuteUpdate(@"delete/delete-with-04.ru");
ValidateGraph(@"delete/delete-post-01f.ttl", new Uri(@"http://example.org/g1"));
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
}
[TestMethod]
public void GraphSpecificDelete1With() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-with-05.ru");
ValidateGraph(@"delete/delete-post-01s2.ttl", new Uri(@"http://example.org/g1"));
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
[TestMethod]
public void GraphSpecificDelete2With() {
ImportData(@"delete/delete-pre-01.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-with-06.ru");
ValidateUnamedGraph(@"delete/delete-post-01f.ttl");
ValidateGraph(@"delete/delete-post-02s.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
[TestMethod]
public void SimpleDelete1Using() {
ImportData(@"delete/delete-pre-01.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ExecuteUpdate(@"delete/delete-using-01.ru");
ValidateUnamedGraph(@"delete/delete-post-01s.ttl");
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
}
[TestMethod]
public void SimpleDelete2Using() {
ImportData(@"delete/delete-pre-01.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-using-02.ru");
ValidateUnamedGraph(@"delete/delete-post-01s.ttl");
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
// KA: Note to self - I think this is failing due to processing of GRAPH algebra in dotNetRdf.
// 28/3/2012 Have emailed Rob to get his thoughts on it
}
[TestMethod]
public void SimpleDelete3Using() {
ImportData(@"delete/delete-pre-01.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ExecuteUpdate(@"delete/delete-using-03.ru");
ValidateUnamedGraph(@"delete/delete-post-01f.ttl");
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
}
[TestMethod]
public void SimpleDelete4Using() {
ImportData(@"delete/delete-pre-03.ttl");
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-using-04.ru");
ValidateUnamedGraph(@"delete/delete-post-03f.ttl");
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
[TestMethod]
public void GraphSpecificDelete1Using() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-using-05.ru");
ValidateGraph(@"delete/delete-post-01s2.ttl", new Uri(@"http://example.org/g1"));
ValidateGraph(@"delete/delete-post-02f.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
[TestMethod]
public void GraphSpecificDelete2Using() {
ImportGraph(@"delete/delete-pre-01.ttl", new Uri(@"http://example.org/g1"));
ImportGraph(@"delete/delete-pre-02.ttl", new Uri(@"http://example.org/g2"));
ImportGraph(@"delete/delete-pre-03.ttl", new Uri(@"http://example.org/g3"));
ExecuteUpdate(@"delete/delete-using-06.ru");
ValidateGraph(@"delete/delete-post-01f.ttl", new Uri(@"http://example.org/g1"));
ValidateGraph(@"delete/delete-post-02s.ttl", new Uri(@"http://example.org/g2"));
ValidateGraph(@"delete/delete-post-03f.ttl", new Uri(@"http://example.org/g3"));
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
public class ArrayIndexOf4
{
private const int c_MIN_SIZE = 64;
private const int c_MAX_SIZE = 1024;
private const int c_MIN_STRLEN = 1;
private const int c_MAX_STRLEN = 1024;
public static int Main()
{
ArrayIndexOf4 ac = new ArrayIndexOf4();
TestLibrary.TestFramework.BeginTestCase("Array.IndexOf(T[] array, T value)");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
TestLibrary.TestFramework.LogInformation("");
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
retVal = NegTest9() && retVal;
retVal = NegTest10() && retVal;
return retVal;
}
public bool PosTest1() { return PosIndexOf<Int64>(1, TestLibrary.Generator.GetInt64(-55), TestLibrary.Generator.GetInt64(-55)); }
public bool PosTest2() { return PosIndexOf<Int32>(2, TestLibrary.Generator.GetInt32(-55), TestLibrary.Generator.GetInt32(-55)); }
public bool PosTest3() { return PosIndexOf<Int16>(3, TestLibrary.Generator.GetInt16(-55), TestLibrary.Generator.GetInt16(-55)); }
public bool PosTest4() { return PosIndexOf<Byte>(4, TestLibrary.Generator.GetByte(-55), TestLibrary.Generator.GetByte(-55)); }
public bool PosTest5() { return PosIndexOf<double>(5, TestLibrary.Generator.GetDouble(-55), TestLibrary.Generator.GetDouble(-55)); }
public bool PosTest6() { return PosIndexOf<float>(6, TestLibrary.Generator.GetSingle(-55), TestLibrary.Generator.GetSingle(-55)); }
public bool PosTest7() { return PosIndexOf<char>(7, TestLibrary.Generator.GetCharLetter(-55), TestLibrary.Generator.GetCharLetter(-55)); }
public bool PosTest8() { return PosIndexOf<char>(8, TestLibrary.Generator.GetCharNumber(-55), TestLibrary.Generator.GetCharNumber(-55)); }
public bool PosTest9() { return PosIndexOf<char>(9, TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55)); }
public bool PosTest10() { return PosIndexOf<string>(10, TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN)); }
public bool PosTest11() { return PosIndexOf2<Int32>(11, 1, 0, 0, 0); }
public bool NegTest1() { return NegIndexOf<Int32>(1, 1); }
// id, defaultValue, length, startIndex, count
public bool NegTest2() { return NegIndexOf2<Int32>( 2, 1, 0, 1, 0); }
public bool NegTest3() { return NegIndexOf2<Int32>( 3, 1, 0, -2, 0); }
public bool NegTest4() { return NegIndexOf2<Int32>( 4, 1, 0, -1, 1); }
public bool NegTest5() { return NegIndexOf2<Int32>( 5, 1, 0, 0, 1); }
public bool NegTest6() { return NegIndexOf2<Int32>( 6, 1, 1, -1, 1); }
public bool NegTest7() { return NegIndexOf2<Int32>( 7, 1, 1, 2, 1); }
public bool NegTest8() { return NegIndexOf2<Int32>( 8, 1, 1, 0, -1); }
public bool NegTest9() { return NegIndexOf2<Int32>( 9, 1, 1, 0, -1); }
public bool NegTest10() { return NegIndexOf2<Int32>(10, 1, 1, 1, 2); }
public bool PosIndexOf<T>(int id, T element, T otherElem)
{
bool retVal = true;
T[] array;
int length;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.IndexOf(T[] array, T value, int startIndex, int count) (T=="+typeof(T)+") where value is found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = new T[length];
// fill the array
for (int i=0; i<array.Length; i++)
{
array[i] = otherElem;
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.IndexOf<T>(array, element, 0, array.Length);
if (index < newIndex)
{
TestLibrary.TestFramework.LogError("000", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (!element.Equals(array[newIndex]))
{
TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + element + ") Actual(" + array[newIndex] + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count)
{
bool retVal = true;
T[] array = null;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.IndexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null");
try
{
array = new T[ length ];
newIndex = Array.IndexOf<T>(array, defaultValue, startIndex, count);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("003", "Unexpected value: Expected(-1) Actual("+newIndex+")");
retVal = false;
}
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegIndexOf<T>(int id, T defaultValue)
{
bool retVal = true;
T[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.IndexOf(T[] array, T value, int startIndex, int count) (T == "+typeof(T)+" where array is null");
try
{
Array.IndexOf<T>(array, defaultValue, 0, 0);
TestLibrary.TestFramework.LogError("005", "Exepction should have been thrown");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count)
{
bool retVal = true;
T[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.IndexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null");
try
{
array = new T[ length ];
Array.IndexOf<T>(array, defaultValue, startIndex, count);
TestLibrary.TestFramework.LogError("007", "Exepction should have been thrown");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// gRPC Channel
/// </summary>
public class Channel
{
static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<Channel>();
readonly object myLock = new object();
readonly AtomicCounter activeCallCounter = new AtomicCounter();
readonly string target;
readonly GrpcEnvironment environment;
readonly ChannelSafeHandle handle;
readonly List<ChannelOption> options;
bool shutdownRequested;
/// <summary>
/// Creates a channel that connects to a specific host.
/// Port will default to 80 for an unsecure channel and to 443 for a secure channel.
/// </summary>
/// <param name="target">Target of the channel.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string target, Credentials credentials, IEnumerable<ChannelOption> options = null)
{
this.target = Preconditions.CheckNotNull(target, "target");
this.environment = GrpcEnvironment.AddRef();
this.options = options != null ? new List<ChannelOption>(options) : new List<ChannelOption>();
EnsureUserAgentChannelOption(this.options);
using (CredentialsSafeHandle nativeCredentials = credentials.ToNativeCredentials())
using (ChannelArgsSafeHandle nativeChannelArgs = ChannelOptions.CreateChannelArgs(this.options))
{
if (nativeCredentials != null)
{
this.handle = ChannelSafeHandle.CreateSecure(nativeCredentials, target, nativeChannelArgs);
}
else
{
this.handle = ChannelSafeHandle.CreateInsecure(target, nativeChannelArgs);
}
}
}
/// <summary>
/// Creates a channel that connects to a specific host and port.
/// </summary>
/// <param name="host">The name or IP address of the host.</param>
/// <param name="port">The port.</param>
/// <param name="credentials">Credentials to secure the channel.</param>
/// <param name="options">Channel options.</param>
public Channel(string host, int port, Credentials credentials, IEnumerable<ChannelOption> options = null) :
this(string.Format("{0}:{1}", host, port), credentials, options)
{
}
/// <summary>
/// Gets current connectivity state of this channel.
/// </summary>
public ChannelState State
{
get
{
return handle.CheckConnectivityState(false);
}
}
/// <summary>
/// Returned tasks completes once channel state has become different from
/// given lastObservedState.
/// If deadline is reached or and error occurs, returned task is cancelled.
/// </summary>
public Task WaitForStateChangedAsync(ChannelState lastObservedState, DateTime? deadline = null)
{
Preconditions.CheckArgument(lastObservedState != ChannelState.FatalFailure,
"FatalFailure is a terminal state. No further state changes can occur.");
var tcs = new TaskCompletionSource<object>();
var deadlineTimespec = deadline.HasValue ? Timespec.FromDateTime(deadline.Value) : Timespec.InfFuture;
var handler = new BatchCompletionDelegate((success, ctx) =>
{
if (success)
{
tcs.SetResult(null);
}
else
{
tcs.SetCanceled();
}
});
handle.WatchConnectivityState(lastObservedState, deadlineTimespec, environment.CompletionQueue, environment.CompletionRegistry, handler);
return tcs.Task;
}
/// <summary>Resolved address of the remote endpoint in URI format.</summary>
public string ResolvedTarget
{
get
{
return handle.GetTarget();
}
}
/// <summary>The original target used to create the channel.</summary>
public string Target
{
get
{
return this.target;
}
}
/// <summary>
/// Allows explicitly requesting channel to connect without starting an RPC.
/// Returned task completes once state Ready was seen. If the deadline is reached,
/// or channel enters the FatalFailure state, the task is cancelled.
/// There is no need to call this explicitly unless your use case requires that.
/// Starting an RPC on a new channel will request connection implicitly.
/// </summary>
public async Task ConnectAsync(DateTime? deadline = null)
{
var currentState = handle.CheckConnectivityState(true);
while (currentState != ChannelState.Ready)
{
if (currentState == ChannelState.FatalFailure)
{
throw new OperationCanceledException("Channel has reached FatalFailure state.");
}
await WaitForStateChangedAsync(currentState, deadline);
currentState = handle.CheckConnectivityState(false);
}
}
/// <summary>
/// Waits until there are no more active calls for this channel and then cleans up
/// resources used by this channel.
/// </summary>
public async Task ShutdownAsync()
{
lock (myLock)
{
Preconditions.CheckState(!shutdownRequested);
shutdownRequested = true;
}
var activeCallCount = activeCallCounter.Count;
if (activeCallCount > 0)
{
Logger.Warning("Channel shutdown was called but there are still {0} active calls for that channel.", activeCallCount);
}
handle.Dispose();
await Task.Run(() => GrpcEnvironment.Release());
}
internal ChannelSafeHandle Handle
{
get
{
return this.handle;
}
}
internal GrpcEnvironment Environment
{
get
{
return this.environment;
}
}
internal void AddCallReference(object call)
{
activeCallCounter.Increment();
bool success = false;
handle.DangerousAddRef(ref success);
Preconditions.CheckState(success);
}
internal void RemoveCallReference(object call)
{
handle.DangerousRelease();
activeCallCounter.Decrement();
}
private static void EnsureUserAgentChannelOption(List<ChannelOption> options)
{
if (!options.Any((option) => option.Name == ChannelOptions.PrimaryUserAgentString))
{
options.Add(new ChannelOption(ChannelOptions.PrimaryUserAgentString, GetUserAgentString()));
}
}
private static string GetUserAgentString()
{
// TODO(jtattermusch): it would be useful to also provide .NET/mono version.
return string.Format("grpc-csharp/{0}", VersionInfo.CurrentVersion);
}
}
}
| |
//#define PACKETDUMP
//#define PROMISEDUMP
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ICSimulator
{
/*
A node can contain the following:
* CPU and CoherentCache (work as a unit)
* coherence directory
* shared cache (only allowed if dir present, and home node must match)
* memory controller
The cache hierarchy is modeled as two levels, the coherent level
(L1 and, in private-cache systems, L2) and the (optional) shared
cache, on top of a collection of memory controllers. Coherence
happens between coherent-level caches, and misses in the
coherent caches go either to the shared cache (if configured) or
directly to memory. The system is thus flexible enough to
support both private and shared cache designs.
*/
public class Interference
{
private CmpCache_Txn _txn;
private Request _request;
private int _requesterID;
private bool valid;
private int interference_cycle;
private int _mshr;
public Interference (Packet pkt)
{
_txn = pkt.txn;
_mshr = pkt.txn.mshr;
_request = pkt.request;
_requesterID = pkt.requesterID;
valid = true;
interference_cycle = pkt.intfCycle;
}
public Interference ()
{
_txn = null;
_request = null;
_requesterID = 0;
valid = false;
interference_cycle = 0;
}
public bool compare (Packet pkt)
{
if (pkt.txn.mshr == _mshr && pkt.requesterID == _requesterID)
return true;
else
return false;
}
public int intfCycle
{
get {return interference_cycle;}
}
}
public class Node
{
Coord m_coord;
NodeMapping m_mapping;
public Coord coord { get { return m_coord; } }
public NodeMapping mapping { get { return m_mapping; } }
public Router router { get { return m_router; } }
public MemCtlr mem { get { return m_mem; } }
public CPU cpu { get { return m_cpu; } }
private CPU m_cpu;
private MemCtlr m_mem;
//private ArrayList m_inheritance_table;
private Dictionary <string, int> m_inheritance_dict;
private Router m_router;
private ulong m_last_retired_synth;
private IPrioPktPool m_inj_pool;
private Queue<Flit> m_injQueue_flit, m_injQueue_evict;
private Queue<Flit> [] m_injQueue_multi_flit;
public Queue<Packet> m_local;
public int RequestQueueLen { get { return m_inj_pool.FlitCount + m_injQueue_flit.Count; } }
RxBufNaive m_rxbuf_naive;
public int get_txn_intf (Packet new_inj_pkt) {
int intfCycle = 0;
string key = new_inj_pkt.requesterID.ToString() + (new_inj_pkt.txn.mshr + Config.N).ToString();
if (m_inheritance_dict.ContainsKey (key)) {
intfCycle = m_inheritance_dict [key];
m_inheritance_dict.Remove (key);
}
/*
foreach (Interference i in m_inheritance_table)
{
if (i.compare(new_inj_pkt))
{
intfCycle = i.intfCycle;
m_inheritance_table.Remove(i);
return intfCycle;
}
}
*/
return intfCycle;
}
public Node(NodeMapping mapping, Coord c)
{
m_coord = c;
m_mapping = mapping;
if (mapping.hasCPU(c.ID))
{
m_cpu = new CPU(this);
}
if (mapping.hasMem(c.ID))
{
Console.WriteLine("Proc/Node.cs : MC locations:{0}", c.ID);
m_mem = new MemCtlr(this);
}
m_inj_pool = Simulator.controller.newPrioPktPool(m_coord.ID);
Simulator.controller.setInjPool(m_coord.ID, m_inj_pool);
m_injQueue_flit = new Queue<Flit>();
m_injQueue_evict = new Queue<Flit>();
m_injQueue_multi_flit = new Queue<Flit> [Config.sub_net];
for (int i=0; i<Config.sub_net; i++)
m_injQueue_multi_flit[i] = new Queue<Flit> ();
m_local = new Queue<Packet>();
//m_inheritance_table = new ArrayList();
m_inheritance_dict = new Dictionary<string, int> ();
m_rxbuf_naive = new RxBufNaive(this,
delegate(Flit f) { m_injQueue_evict.Enqueue(f); },
delegate(Packet p) { receivePacket(p); });
}
public void setRouter(Router r)
{
m_router = r;
}
Coord PickDst ()
{
int dest = m_coord.ID;
Coord c = new Coord (dest);
while (dest == m_coord.ID) { // ensure src != dst
switch (Config.synthPattern) {
case SynthTrafficPattern.UR:
dest = Simulator.rand.Next (Config.N);
c = new Coord (dest);
break;
case SynthTrafficPattern.BC:
dest = ~dest & (Config.N - 1);
c = new Coord (dest);
break;
case SynthTrafficPattern.TR: // TODO: Check if correct
c = new Coord (m_coord.y, m_coord.x);
break;
case SynthTrafficPattern.HS:
Simulator.network.pickHotSpot (); // pick a hot spot when N-1 Mergeable packets destined to hotspot node
if ((Simulator.rand.NextDouble () < Config.hs_rate) &&
// use to control the number of mergable request from each node
(Simulator.network.hsReqPerNode[m_coord.ID] < Config.hotSpotReqPerNode))
{
dest = Simulator.network.hotSpotNode;
Simulator.network.hsReqPerNode [m_coord.ID] ++;
Simulator.network.hotSpotGenCount++; // clear for every Config.N-1 hs packets. Then pick a new hot spot.
Simulator.stats.generate_hs_packet.Add ();
}
else // otherwide generate a normal uniform random packet
dest = Simulator.rand.Next (Config.N);
c = new Coord (dest);
break;
}
}
return c;
}
int PickPktSize (bool mc, bool gather)
{
// decide packet size
int packet_size;
if (Config.uniform_size_enable == true) {
if (Config.topology == Topology.Mesh_Multi)
packet_size = Config.uniform_size * Config.sub_net;
else
packet_size = Config.uniform_size;
}
else
{
if (Simulator.rand.NextDouble () < 0.5)
packet_size = Config.router.addrPacketSize;
else
packet_size = Config.router.dataPacketSize;
}
if (mc == true)
return packet_size * 2; // each packet only contains half of original payload.
else if (gather == true)
return packet_size * 2;
else
return packet_size;
}
Packet packetization ()
{
int oldHsReq;
Coord c = PickDst ();
bool gather = false;
int packet_size;
Packet p;
if (Config.synthPattern == SynthTrafficPattern.HS) {
oldHsReq = Simulator.network.hsReqPerNode [m_coord.ID]; // use to determine if a hot spot packet is generated. Place it before PickDst()
if (Simulator.network.hsReqPerNode [m_coord.ID] == oldHsReq + 1)
gather = true;
packet_size = PickPktSize (false, gather);
if (gather)
p = new Packet (null,0,packet_size,m_coord, c, true);
else
p = new Packet(null,0,packet_size,m_coord, c);
} else {
packet_size = PickPktSize (false, false); // this is a unicast
p = new Packet(null,0,packet_size,m_coord, c);
}
#if PACKETDUMP
Console.WriteLine ("#1 Time {0}, @ node {1} {2}", Simulator.CurrentRound, m_coord.ID, p.ToString());
#endif
return p;
}
void unicastSynthGen (bool mc, bool record)
{
if (m_inj_pool.Count > Config.synthQueueLimit)
Simulator.stats.synth_queue_limit_drop.Add();
else
{
Packet p = packetization ();
queuePacket(p);
//Console.WriteLine ("Packet {0} is generated @ Time {1} Router {2}", p.ID, Simulator.CurrentRound, coord.ID);
ScoreBoard.RegPacket (p.dest.ID, p.ID);
Simulator.stats.generate_packet.Add ();
if (record) {
if (!mc)
Simulator.stats.generate_uc_packet.Add ();
else
Simulator.stats.generate_mc_packet.Add ();
}
}
}
void multicastSynthGenMultiDst ()
{
double mc_rate = Config.mc_rate; // enforcing mc_rate = 0 is equivalent to running unicast
double mc_degree = 1;
List <Coord> sharerList = new List <Coord> ();
int packet_size;
Coord dst;
//Coord[] destArray = new Coord[] { };
if (Simulator.rand.NextDouble () < mc_rate) {
mc_degree = Simulator.rand.Next (Config.mc_degree - 2) + 2; // multicast; generate index 2-15
//Console.WriteLine ("TIME={0} Node {1} send {2} MC_PKT", Simulator.CurrentRound, m_coord.ID, mc_degree);
}
else
mc_degree = 1;
if (mc_degree == 1) {
// This is a unicast packet
packet_size = PickPktSize (false, false);
unicastSynthGen (false, true);
return;
}
while (mc_degree > 0) {
// This is a MC packet
// Generate the destination list
// it will be used for packetization
// Note: it is different from the destination list of a packet,
// which may be a subset, depending on the network size and pakcet format.
dst = PickDst();
if (sharerList.Contains (dst)) // ensure no dst is added twice
continue;
sharerList.Add(dst);
mc_degree--;
}
packet_size = PickPktSize (true, false);
Packet p = new Packet(null,0,packet_size,m_coord, sharerList);
queuePacket(p);
foreach (Coord dest in sharerList) {
ScoreBoard.RegPacket (dest.ID, p.ID);
p.creationTimeMC [dest.ID] = Simulator.CurrentRound; // it will be overriden everytime when replication occur, but only once.
}
Simulator.stats.generate_mc_packet.Add ();
Simulator.stats.generate_packet.Add (sharerList.Count);
}
void multicastSynthGenNaive ()
{
double mc_rate = Config.mc_rate; // enforcing mc_rate = 0 is equivalent to running unicast
double mc_degree = 1;
bool mc;
if (Simulator.rand.NextDouble () < mc_rate) {
mc_degree = Simulator.rand.Next (Config.mc_degree - 2) + 2; // multicast
mc = true;
//Console.WriteLine ("TIME={0} Node {1} send {2} MC_PKT", Simulator.CurrentRound, m_coord.ID, mc_degree);
} else {
mc_degree = 1;
mc = false;
}
while (mc_degree > 0) {
// Naive multicast
// Sending multiple unicast packets
if (mc_degree == 1)
unicastSynthGen (mc, true);
else
unicastSynthGen (mc, false);
mc_degree--;
}
}
void synthGen()
{
double uc_rate = Config.synth_rate;
if (!Config.multicast && Simulator.rand.NextDouble () < uc_rate)
unicastSynthGen (false, true);
// Enable adaptiveInj to make it adaptive
else if (Config.multicast && Simulator.rand.NextDouble () < uc_rate)
{
// Console.WriteLine ("Starvation rate is {0}", m_router.starveCount/(float)Config.starveResetEpoch);
// Using the naive mc method when the starvation rate is higher than the threshold.
if (Config.router.algorithm == RouterAlgorithm.DR_FLIT_SW_OF_MC && Config.scatterEnable
) {
if ((Config.adaptiveMC == true && (m_router.starveCount/(double)Config.starveResetEpoch < Config.starveRateThreshold)) || Config.adaptiveMC == false)
multicastSynthGenMultiDst ();
// else
// THROTTLED HERE, VERY IMPORTANT
// Tried the following, but did not see much difference
//else
// multicastSynthGenNaive ();
}
else
multicastSynthGenNaive ();
}
}
public void doStep()
{
// continue to run until all packets generated prior to stop time are received.
if (Config.synthGen && !Simulator.network.StopSynPktGen())
{
synthGen();
}
while (m_local.Count > 0 &&
m_local.Peek().creationTime < Simulator.CurrentRound)
{
receivePacket(m_local.Dequeue());
}
if (m_cpu != null)
m_cpu.doStep();
if (m_mem != null)
m_mem.doStep();
if (m_inj_pool.FlitInterface) // By Xiyue: ??? why 2 different injection modes?
{
Flit f = m_inj_pool.peekFlit();
if (f != null && m_router.canInjectFlit(f))
{
m_router.InjectFlit(f);
m_inj_pool.takeFlit(); // By Xiyue: ??? No action ???
}
}
else // By Xiyue: Actual injection into network
{
Packet p = m_inj_pool.next();
int selected;
if (Config.topology == Topology.Mesh_Multi) {
if (p != null && p.creationTime <= Simulator.CurrentRound) {
foreach (Flit f in p.flits) {
// serialize packet to flit and select a subnetwork
// assume infinite NI buffer
selected = select_subnet ();
Simulator.stats.subnet_util [m_coord.ID, selected].Add ();
//if (selected % 2 == 0)
// f.routingOrder = true;
m_injQueue_multi_flit [selected].Enqueue (f);
}
}
for (int i = 0 ; i < Config.sub_net; i++)
{
if (m_injQueue_multi_flit[i].Count > 0 && m_router.canInjectFlitMultNet(i, m_injQueue_multi_flit[i].Peek()))
{
Flit f = m_injQueue_multi_flit[i].Dequeue();
m_router.InjectFlitMultNet(i, f);
#if PACKETDUMP
Console.WriteLine("Time {2}: @ node {1} Inject pktID {0} on subnet {3}",
f.packet.ID, coord.ID, Simulator.CurrentRound, i);
#endif
}
}
}
else if (Config.throttle_enable && Config.controller == ControllerType.THROTTLE_QOS)
{
if (p != null)
{
int intfCycle = get_txn_intf(p); // first term: interf. of predecessor, second term: throttled cycle
foreach (Flit f in p.flits)
{
f.intfCycle = intfCycle;
m_injQueue_flit.Enqueue(f);
}
}
if (m_injQueue_evict.Count > 0 && m_router.canInjectFlit(m_injQueue_evict.Peek())) // By Xiyue: ??? What is m_injQueue_evict ?
{
Flit f = m_injQueue_evict.Dequeue();
m_router.InjectFlit(f);
}
else if (m_injQueue_flit.Count > 0 && m_router.canInjectFlit(m_injQueue_flit.Peek())) // By Xiyue: ??? Dif from m_injQueue_evict?
{
Flit f = m_injQueue_flit.Dequeue();
#if PACKETDUMP
if (f.flitNr == 0)
if (m_coord.ID == 0)
Console.WriteLine("start to inject packet {0} at node {1} (cyc {2})",
f.packet, coord, Simulator.CurrentRound);
#endif
m_router.InjectFlit(f); // by Xiyue: inject into a router
// for Ring based Network, inject two flits if possible
for (int i = 0 ; i < Config.RingInjectTrial - 1; i++)
if (m_injQueue_flit.Count > 0 && m_router.canInjectFlit(m_injQueue_flit.Peek()))
{
f = m_injQueue_flit.Dequeue();
m_router.InjectFlit(f);
}
}
}
else
{
if (p != null)
{
foreach (Flit f in p.flits)
m_injQueue_flit.Enqueue(f);
}
//Console.WriteLine ("FlitInjectQ size {0}", m_injQueue_flit.Count);
if (m_injQueue_evict.Count > 0 && m_router.canInjectFlit(m_injQueue_evict.Peek())) // By Xiyue: ??? What is m_injQueue_evict ?
{
Flit f = m_injQueue_evict.Dequeue();
m_router.InjectFlit(f);
}
else if (m_injQueue_flit.Count > 0 && m_router.canInjectFlit(m_injQueue_flit.Peek())) // By Xiyue: ??? Dif from m_injQueue_evict?
{
Flit f = m_injQueue_flit.Dequeue();
#if PACKETDUMP
Console.WriteLine("#2 Time {2}: @ node {1} Inject pktID {0}",
f.packet.ID, coord.ID, Simulator.CurrentRound);
#endif
m_router.InjectFlit(f); // by Xiyue: inject into a router
// for Ring based Network, inject two flits if possible
for (int i = 0 ; i < Config.RingInjectTrial - 1; i++)
if (m_injQueue_flit.Count > 0 && m_router.canInjectFlit(m_injQueue_flit.Peek()))
{
f = m_injQueue_flit.Dequeue();
m_router.InjectFlit(f);
}
}
}
}
}
protected int select_subnet ()
{
int selected = -1;
double util = double.MaxValue;
if (Config.subnet_sel_rand)
selected = Simulator.rand.Next(Config.sub_net);
else
// Inject to the subnet with lower load
for (int i = 0; i < Config.sub_net; i++)
{
if (Simulator.stats.subnet_util[m_coord.ID, i].Count < util)
{
selected = i;
util = Simulator.stats.subnet_util[m_coord.ID, i].Count;
}
}
if (selected == -1 || selected >= Config.sub_net) throw new Exception("no subnet is selected");
return selected;
}
public virtual void receiveFlit(Flit f)
{
if (Config.naive_rx_buf)
m_rxbuf_naive.acceptFlit (f);
else {
if (Config.router.algorithm == RouterAlgorithm.DR_FLIT_SW_OF_MC)
receiveFlit_noBuf_mc (f);
else
receiveFlit_noBuf (f);
}
m_last_retired_synth = Simulator.CurrentRound;
}
void receiveFlit_noBuf_mc (Flit f){
int nrOfarrivedFlit = -1;
if (f.packet.mc) {
f.packet.nrOfArrivedFlitsMC [m_coord.ID]++;
nrOfarrivedFlit = f.packet.nrOfArrivedFlitsMC [m_coord.ID];
} else {
f.packet.nrOfArrivedFlits++;
nrOfarrivedFlit = f.packet.nrOfArrivedFlits;
}
if (nrOfarrivedFlit == f.packet.nrOfFlits) {
receivePacket (f.packet);
}
}
void receiveFlit_noBuf(Flit f)
{
// Register the flit interferece delay
// intfCycle gets updates only at the first and last flit of a packet arrival.
f.packet.nrOfArrivedFlits++;
if (f.packet.nrOfArrivedFlits == 1)
{
// Record the inteference cycle of flits.
f.packet.intfCycle = f.intfCycle; // the interference cycle of head flit
f.packet.first_flit_arrival = Simulator.CurrentRound;
}
if (f.packet.nrOfArrivedFlits == f.packet.nrOfFlits)
{
// Compute the inteference cycle of a pacekt.
f.packet.intfCycle = (int)f.packet.intfCycle + ((int)Simulator.CurrentRound - (int)f.packet.first_flit_arrival - f.packet.nrOfFlits + 1); // assume the flits of will arrive consecutively without interference. In case of control packet, the portion inside of parenthesis is 0.
if (f.packet.intfCycle > 0 && f.packet.requesterID != m_coord.ID && f.packet.critical == true && Config.throttle_enable == true && Config.controller == ControllerType.THROTTLE_QOS)
{
// only log the delay of the packets whose associated request is not generated by the current node
// therefore, they will trigger some packets later.
string inheritance_key = f.packet.requesterID.ToString() + (f.packet.txn.mshr + Config.N).ToString();
m_inheritance_dict.Add(inheritance_key, f.packet.intfCycle);
// m_inheritance_table.Add(intf_entry);
// profile size of the m_inheritance_table
Simulator.stats.inherit_table_size.Add(m_inheritance_dict.Count);
}
receivePacket(f.packet);
}
}
public void evictFlit(Flit f)
{
m_injQueue_evict.Enqueue(f);
}
public void receivePacket(Packet p)
{
#if PACKETDUMP
if (m_coord.ID == 0)
Console.WriteLine("receive packet {0} at node {1} (cyc {2}) (age {3})",
p, coord, Simulator.CurrentRound, Simulator.CurrentRound - p.creationTime);
#endif
// nothing happens for synthetic packet
if (p is RetxPacket) {
p.retx_count++;
p.flow_open = false;
p.flow_close = false;
queuePacket (((RetxPacket)p).pkt);
} else if (p is CachePacket) {
CachePacket cp = p as CachePacket;// TODO: DONT CAST, CREATE NEW ONE
m_cpu.receivePacket (cp); // by Xiyue: Local ejection
}
}
public void queuePacket(Packet p) // By Xiyue: called by CmpCache::send_noc()
{
if (p.dest.ID == m_coord.ID && p.mc == false) // local traffic: do not go to net (will confuse router) // by Xiyue: just hijack the packet if it only access the shared cache at the local node.
{
m_local.Enqueue(p); // this is filter out
return;
}
if (Config.idealnet && p.mc == false) // ideal network: deliver immediately to dest
Simulator.network.nodes[p.dest.ID].m_local.Enqueue(p);
else // otherwise: enqueue on injection queue
{
m_inj_pool.addPacket(p); //By Xiyue: Actual Injection.
}
}
public void sendRetx(Packet p)
{
p.nrOfArrivedFlits = 0;
RetxPacket pkt = new RetxPacket(p.dest, p.src, p);
queuePacket(pkt);
}
public bool Finished
{ get { return (m_cpu != null) ? m_cpu.Finished : false; } }
public bool Livelocked
{ get { return (m_cpu != null) ? m_cpu.Livelocked :
(Simulator.CurrentRound - m_last_retired_synth) > Config.livelock_thresh; }
}
public void visitFlits(Flit.Visitor fv)
{
// visit in-buffer (inj and reassembly) flits too?
}
}
}
| |
#region Copyright
//
// This framework is based on log4j see http://jakarta.apache.org/log4j
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.Collections;
namespace log4net.spi
{
/// <summary>
/// A strongly-typed collection of <see cref="Level"/> objects.
/// </summary>
#if !NETCF
[Serializable]
#endif
public class LevelCollection : ICollection, IList, IEnumerable, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="LevelCollection"/>.
/// </summary>
public interface ILevelCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
Level Current {get;}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private Level[] m_array;
private int m_count = 0;
#if !NETCF
[NonSerialized]
#endif
private int m_version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a synchronized (thread-safe) wrapper for a
/// <c>LevelCollection</c> instance.
/// </summary>
/// <returns>
/// A <c>LevelCollection</c> wrapper that is synchronized (thread-safe).
/// </returns>
public static LevelCollection Synchronized(LevelCollection list)
{
if(list==null)
throw new ArgumentNullException("list");
return new SyncLevelCollection(list);
}
/// <summary>
/// Creates a read-only wrapper for a
/// <c>LevelCollection</c> instance.
/// </summary>
/// <returns>
/// A <c>LevelCollection</c> wrapper that is read-only.
/// </returns>
public static LevelCollection ReadOnly(LevelCollection list)
{
if(list==null)
throw new ArgumentNullException("list");
return new ReadOnlyLevelCollection(list);
}
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public LevelCollection()
{
m_array = new Level[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>LevelCollection</c> is initially capable of storing.
/// </param>
public LevelCollection(int capacity)
{
m_array = new Level[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <c>LevelCollection</c>.
/// </summary>
/// <param name="c">The <c>LevelCollection</c> whose elements are copied to the new collection.</param>
public LevelCollection(LevelCollection c)
{
m_array = new Level[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <see cref="Level"/> array.
/// </summary>
/// <param name="a">The <see cref="Level"/> array whose elements are copied to the new list.</param>
public LevelCollection(Level[] a)
{
m_array = new Level[a.Length];
AddRange(a);
}
/// <summary>
/// Initializes a new instance of the <c>LevelCollection</c> class
/// that contains elements copied from the specified <see cref="Level"/> collection.
/// </summary>
/// <param name="col">The <see cref="Level"/> collection whose elements are copied to the new list.</param>
public LevelCollection(ICollection col)
{
m_array = new Level[col.Count];
AddRange(col);
}
/// <summary>
/// Type visible only to our subclasses
/// Used to access protected constructor
/// </summary>
protected enum Tag
{
/// <summary>
/// A value
/// </summary>
Default
}
/// <summary>
/// Allow subclasses to avoid our default constructors
/// </summary>
/// <param name="t"></param>
protected LevelCollection(Tag t)
{
m_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>LevelCollection</c>.
/// </summary>
public virtual int Count
{
get { return m_count; }
}
/// <summary>
/// Copies the entire <c>LevelCollection</c> to a one-dimensional
/// <see cref="Level"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param>
public virtual void CopyTo(Level[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>LevelCollection</c> to a one-dimensional
/// <see cref="Level"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Level"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(Level[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
throw new System.ArgumentException("Destination array was not long enough.");
Array.Copy(m_array, 0, array, start, m_count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</value>
public virtual bool IsSynchronized
{
get { return m_array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return m_array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="Level"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual Level this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="Level"/> to the end of the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(Level item)
{
if (m_count == m_array.Length)
EnsureCapacity(m_count + 1);
m_array[m_count] = item;
m_version++;
return m_count++;
}
/// <summary>
/// Removes all elements from the <c>LevelCollection</c>.
/// </summary>
public virtual void Clear()
{
++m_version;
m_array = new Level[DEFAULT_CAPACITY];
m_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="LevelCollection"/>.
/// </summary>
public virtual object Clone()
{
LevelCollection newColl = new LevelCollection(m_count);
Array.Copy(m_array, 0, newColl.m_array, 0, m_count);
newColl.m_count = m_count;
newColl.m_version = m_version;
return newColl;
}
/// <summary>
/// Determines whether a given <see cref="Level"/> is in the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>LevelCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(Level item)
{
for (int i=0; i != m_count; ++i)
if (m_array[i].Equals(item))
return true;
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="Level"/>
/// in the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to locate in the <c>LevelCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>LevelCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(Level item)
{
for (int i=0; i != m_count; ++i)
if (m_array[i].Equals(item))
return i;
return -1;
}
/// <summary>
/// Inserts an element into the <c>LevelCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="Level"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, Level item)
{
ValidateIndex(index, true); // throws
if (m_count == m_array.Length)
EnsureCapacity(m_count + 1);
if (index < m_count)
{
Array.Copy(m_array, index, m_array, index + 1, m_count - index);
}
m_array[index] = item;
m_count++;
m_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="Level"/> from the <c>LevelCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Level"/> to remove from the <c>LevelCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="Level"/> was not found in the <c>LevelCollection</c>.
/// </exception>
public virtual void Remove(Level item)
{
int i = IndexOf(item);
if (i < 0)
throw new System.ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
++m_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>LevelCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
m_count--;
if (index < m_count)
{
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
Level[] temp = new Level[1];
Array.Copy(temp, 0, m_array, m_count, 1);
m_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the IList is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>LevelCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>LevelCollection</c>.</returns>
public virtual ILevelCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>LevelCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get { return m_array.Length; }
set
{
if (value < m_count)
value = m_count;
if (value != m_array.Length)
{
if (value > 0)
{
Level[] temp = new Level[value];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
else
{
m_array = new Level[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>LevelCollection</c> to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="x">The <c>LevelCollection</c> whose elements should be added to the end of the current <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(LevelCollection x)
{
if (m_count + x.Count >= m_array.Length)
EnsureCapacity(m_count + x.Count);
Array.Copy(x.m_array, 0, m_array, m_count, x.Count);
m_count += x.Count;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="Level"/> array to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="x">The <see cref="Level"/> array whose elements should be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(Level[] x)
{
if (m_count + x.Length >= m_array.Length)
EnsureCapacity(m_count + x.Length);
Array.Copy(x, 0, m_array, m_count, x.Length);
m_count += x.Length;
m_version++;
return m_count;
}
/// <summary>
/// Adds the elements of a <see cref="Level"/> collection to the current <c>LevelCollection</c>.
/// </summary>
/// <param name="col">The <see cref="Level"/> collection whose elements should be added to the end of the <c>LevelCollection</c>.</param>
/// <returns>The new <see cref="LevelCollection.Count"/> of the <c>LevelCollection</c>.</returns>
public virtual int AddRange(ICollection col)
{
if (m_count + col.Count >= m_array.Length)
EnsureCapacity(m_count + col.Count);
foreach(object item in col)
{
Add((Level)item);
}
return m_count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
this.Capacity = m_count;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="LevelCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd)?(m_count):(m_count-1);
if (i < 0 || i > max)
throw new System.ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection. [" + (object)i + "] Specified argument was out of the range of valid values.");
}
private void EnsureCapacity(int min)
{
int newCapacity = ((m_array.Length == 0) ? DEFAULT_CAPACITY : m_array.Length * 2);
if (newCapacity < min)
newCapacity = min;
this.Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
Array.Copy(m_array, 0, array, start, m_count);
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return (object)this[i]; }
set { this[i] = (Level)value; }
}
int IList.Add(object x)
{
return this.Add((Level)x);
}
bool IList.Contains(object x)
{
return this.Contains((Level)x);
}
int IList.IndexOf(object x)
{
return this.IndexOf((Level)x);
}
void IList.Insert(int pos, object x)
{
this.Insert(pos, (Level)x);
}
void IList.Remove(object x)
{
this.Remove((Level)x);
}
void IList.RemoveAt(int pos)
{
this.RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="LevelCollection"/>.
/// </summary>
private class Enumerator : IEnumerator, ILevelCollectionEnumerator
{
#region Implementation (data)
private LevelCollection m_collection;
private int m_index;
private int m_version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(LevelCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public Level Current
{
get { return m_collection[m_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
throw new System.InvalidOperationException("Collection was modified; enumeration operation may not execute.");
++m_index;
return (m_index < m_collection.Count) ? true : false;
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
m_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return (object)(this.Current); }
}
#endregion
}
#endregion
#region Nested Syncronized Wrapper class
private class SyncLevelCollection : LevelCollection
{
#region Implementation (data)
private LevelCollection m_collection;
private object m_root;
#endregion
#region Construction
internal SyncLevelCollection(LevelCollection list) : base(Tag.Default)
{
m_root = list.SyncRoot;
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(Level[] array)
{
lock(this.m_root)
m_collection.CopyTo(array);
}
public override void CopyTo(Level[] array, int start)
{
lock(this.m_root)
m_collection.CopyTo(array,start);
}
public override int Count
{
get
{
lock(this.m_root)
return m_collection.Count;
}
}
public override bool IsSynchronized
{
get { return true; }
}
public override object SyncRoot
{
get { return this.m_root; }
}
#endregion
#region Type-safe IList
public override Level this[int i]
{
get
{
lock(this.m_root)
return m_collection[i];
}
set
{
lock(this.m_root)
m_collection[i] = value;
}
}
public override int Add(Level x)
{
lock(this.m_root)
return m_collection.Add(x);
}
public override void Clear()
{
lock(this.m_root)
m_collection.Clear();
}
public override bool Contains(Level x)
{
lock(this.m_root)
return m_collection.Contains(x);
}
public override int IndexOf(Level x)
{
lock(this.m_root)
return m_collection.IndexOf(x);
}
public override void Insert(int pos, Level x)
{
lock(this.m_root)
m_collection.Insert(pos,x);
}
public override void Remove(Level x)
{
lock(this.m_root)
m_collection.Remove(x);
}
public override void RemoveAt(int pos)
{
lock(this.m_root)
m_collection.RemoveAt(pos);
}
public override bool IsFixedSize
{
get {return m_collection.IsFixedSize;}
}
public override bool IsReadOnly
{
get {return m_collection.IsReadOnly;}
}
#endregion
#region Type-safe IEnumerable
public override ILevelCollectionEnumerator GetEnumerator()
{
lock(m_root)
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get
{
lock(this.m_root)
return m_collection.Capacity;
}
set
{
lock(this.m_root)
m_collection.Capacity = value;
}
}
public override int AddRange(LevelCollection x)
{
lock(this.m_root)
return m_collection.AddRange(x);
}
public override int AddRange(Level[] x)
{
lock(this.m_root)
return m_collection.AddRange(x);
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
private class ReadOnlyLevelCollection : LevelCollection
{
#region Implementation (data)
private LevelCollection m_collection;
#endregion
#region Construction
internal ReadOnlyLevelCollection(LevelCollection list) : base(Tag.Default)
{
m_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(Level[] array)
{
m_collection.CopyTo(array);
}
public override void CopyTo(Level[] array, int start)
{
m_collection.CopyTo(array,start);
}
public override int Count
{
get {return m_collection.Count;}
}
public override bool IsSynchronized
{
get { return m_collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return this.m_collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override Level this[int i]
{
get { return m_collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(Level x)
{
return m_collection.Contains(x);
}
public override int IndexOf(Level x)
{
return m_collection.IndexOf(x);
}
public override void Insert(int pos, Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(Level x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get {return true;}
}
public override bool IsReadOnly
{
get {return true;}
}
#endregion
#region Type-safe IEnumerable
public override ILevelCollectionEnumerator GetEnumerator()
{
return m_collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return m_collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(LevelCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(Level[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Models;
namespace Umbraco.Tests.PublishedContent
{
/// <summary>
/// Tests the methods on IPublishedContent using the DefaultPublishedContentStore
/// </summary>
[TestFixture]
public class PublishedContentTests : PublishedContentTestBase
{
private PluginManager _pluginManager;
public override void Initialize()
{
// required so we can access property.Value
//PropertyValueConvertersResolver.Current = new PropertyValueConvertersResolver();
base.Initialize();
// this is so the model factory looks into the test assembly
_pluginManager = PluginManager.Current;
PluginManager.Current = new PluginManager(new ActivatorServiceProvider(), CacheHelper.RuntimeCache, ProfilingLogger, false)
{
AssembliesToScan = _pluginManager.AssembliesToScan
.Union(new[] { typeof(PublishedContentTests).Assembly })
};
// need to specify a custom callback for unit tests
// AutoPublishedContentTypes generates properties automatically
// when they are requested, but we must declare those that we
// explicitely want to be here...
var propertyTypes = new[]
{
// AutoPublishedContentType will auto-generate other properties
new PublishedPropertyType("umbracoNaviHide", 0, Constants.PropertyEditors.TrueFalseAlias),
new PublishedPropertyType("selectedNodes", 0, "?"),
new PublishedPropertyType("umbracoUrlAlias", 0, "?"),
new PublishedPropertyType("content", 0, Constants.PropertyEditors.TinyMCEAlias),
new PublishedPropertyType("testRecursive", 0, "?"),
};
var compositionAliases = new[] {"MyCompositionAlias"};
var type = new AutoPublishedContentType(0, "anything", compositionAliases, propertyTypes);
PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
}
public override void TearDown()
{
PluginManager.Current = _pluginManager;
ApplicationContext.Current.DisposeIfDisposable();
ApplicationContext.Current = null;
}
protected override void FreezeResolution()
{
var types = PluginManager.Current.ResolveTypes<PublishedContentModel>();
PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver(
new PublishedContentModelFactory(types));
base.FreezeResolution();
}
protected override string GetXmlContent(int templateId)
{
return @"<?xml version=""1.0"" encoding=""utf-8""?>
<!DOCTYPE root[
<!ELEMENT Home ANY>
<!ATTLIST Home id ID #REQUIRED>
<!ELEMENT CustomDocument ANY>
<!ATTLIST CustomDocument id ID #REQUIRED>
]>
<root id=""-1"">
<Home id=""1046"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""home"" writerName=""admin"" creatorName=""admin"" path=""-1,1046"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoUrlAlias><![CDATA[this/is/my/alias, anotheralias]]></umbracoUrlAlias>
<umbracoNaviHide>1</umbracoNaviHide>
<testRecursive><![CDATA[This is the recursive val]]></testRecursive>
<Home id=""1173"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""sub1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173"" isDoc="""">
<content><![CDATA[<div>This is some content</div>]]></content>
<umbracoUrlAlias><![CDATA[page2/alias, 2ndpagealias]]></umbracoUrlAlias>
<testRecursive><![CDATA[]]></testRecursive>
<Home id=""1174"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""sub2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1174"" isDoc="""">
<content><![CDATA[]]></content>
<umbracoUrlAlias><![CDATA[only/one/alias]]></umbracoUrlAlias>
<creatorName><![CDATA[Custom data with same property name as the member name]]></creatorName>
<testRecursive><![CDATA[]]></testRecursive>
</Home>
<CustomDocument id=""1177"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""custom sub 1"" urlName=""custom-sub-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1177"" isDoc="""" />
<CustomDocument id=""1178"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-16T14:23:35"" nodeName=""custom sub 2"" urlName=""custom-sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1178"" isDoc="""" />
<Home id=""1176"" parentID=""1173"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""4"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""sub-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1173,1176"" isDoc="""" key=""CDB83BBC-A83B-4BA6-93B8-AADEF67D3C09"">
<content><![CDATA[]]></content>
<umbracoNaviHide>1</umbracoNaviHide>
</Home>
</Home>
<Home id=""1175"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""sub-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,1175"" isDoc=""""><content><![CDATA[]]></content>
</Home>
<CustomDocument id=""4444"" parentID=""1046"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""3"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1046,4444"" isDoc="""">
<selectedNodes><![CDATA[1172,1176,1173]]></selectedNodes>
</CustomDocument>
</Home>
<CustomDocument id=""1172"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""test-page"" writerName=""admin"" creatorName=""admin"" path=""-1,1172"" isDoc="""" />
</root>";
}
internal IPublishedContent GetNode(int id)
{
var ctx = GetUmbracoContext("/test", 1234);
var doc = ctx.ContentCache.GetById(id);
Assert.IsNotNull(doc);
return doc;
}
[Test]
[Ignore("IPublishedContent currently (6.1 as of april 25, 2013) has bugs")]
public void Fails()
{
var content = GetNode(1173);
var c1 = content.Children.First(x => x.Id == 1177);
Assert.IsFalse(c1.IsFirst());
var c2 = content.Children.Where(x => x.DocumentTypeAlias == "CustomDocument").First(x => x.Id == 1177);
Assert.IsTrue(c2.IsFirst());
// First is not implemented
var c2a = content.Children.First(x => x.DocumentTypeAlias == "CustomDocument" && x.Id == 1177);
Assert.IsTrue(c2a.IsFirst()); // so here it's luck
c1 = content.Children.First(x => x.Id == 1177);
Assert.IsFalse(c1.IsFirst()); // and here it fails
// but even using supported (where) method...
// do not replace by First(x => ...) here since it's not supported at the moment
c1 = content.Children.Where(x => x.Id == 1177).First();
c2 = content.Children.Where(x => x.DocumentTypeAlias == "CustomDocument" && x.Id == 1177).First();
Assert.IsFalse(c1.IsFirst()); // here it fails because c2 has corrupted it
// so there's only 1 IPublishedContent instance
// which keeps changing collection, ie being modified
// which is *bad* from a cache point of vue
// and from a consistency point of vue...
// => we want clones!
}
[Test]
public void Is_Last_From_Where_Filter_Dynamic_Linq()
{
var doc = GetNode(1173);
var items = doc.Children.Where("Visible").ToContentSet();
foreach (var item in items)
{
if (item.Id != 1178)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Is_Last_From_Where_Filter()
{
var doc = GetNode(1173);
var items = doc
.Children
.Where(x => x.IsVisible())
.ToContentSet();
Assert.AreEqual(3, items.Count());
foreach (var d in items)
{
switch (d.Id)
{
case 1174:
Assert.IsTrue(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 1177:
Assert.IsFalse(d.IsFirst());
Assert.IsFalse(d.IsLast());
break;
case 1178:
Assert.IsFalse(d.IsFirst());
Assert.IsTrue(d.IsLast());
break;
default:
Assert.Fail("Invalid id.");
break;
}
}
}
[PublishedContentModel("Home")]
internal class Home : PublishedContentModel
{
public Home(IPublishedContent content)
: base(content)
{}
}
[Test]
[Ignore("Fails as long as PublishedContentModel is internal.")] // fixme
public void Is_Last_From_Where_Filter2()
{
var doc = GetNode(1173);
var items = doc.Children
.Select(x => x.CreateModel()) // linq, returns IEnumerable<IPublishedContent>
// only way around this is to make sure every IEnumerable<T> extension
// explicitely returns a PublishedContentSet, not an IEnumerable<T>
.OfType<Home>() // ours, return IEnumerable<Home> (actually a PublishedContentSet<Home>)
.Where(x => x.IsVisible()) // so, here it's linq again :-(
.ToContentSet() // so, we need that one for the test to pass
.ToArray();
Assert.AreEqual(1, items.Count());
foreach (var d in items)
{
switch (d.Id)
{
case 1174:
Assert.IsTrue(d.IsFirst());
Assert.IsTrue(d.IsLast());
break;
default:
Assert.Fail("Invalid id.");
break;
}
}
}
[Test]
public void Is_Last_From_Take()
{
var doc = GetNode(1173);
var items = doc.Children.Take(3).ToContentSet();
foreach (var item in items)
{
if (item.Id != 1178)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Is_Last_From_Skip()
{
var doc = GetNode(1173);
foreach (var d in doc.Children.Skip(1))
{
if (d.Id != 1176)
{
Assert.IsFalse(d.IsLast());
}
else
{
Assert.IsTrue(d.IsLast());
}
}
}
[Test]
public void Is_Last_From_Concat()
{
var doc = GetNode(1173);
var items = doc.Children
.Concat(new[] { GetNode(1175), GetNode(4444) })
.ToContentSet();
foreach (var item in items)
{
if (item.Id != 4444)
{
Assert.IsFalse(item.IsLast());
}
else
{
Assert.IsTrue(item.IsLast());
}
}
}
[Test]
public void Descendants_Ordered_Properly()
{
var doc = GetNode(1046);
var expected = new[] {1046, 1173, 1174, 1177, 1178, 1176, 1175, 4444, 1172};
var exindex = 0;
// must respect the XPath descendants-or-self axis!
foreach (var d in doc.DescendantsOrSelf())
Assert.AreEqual(expected[exindex++], d.Id);
}
[Test]
public void Test_Get_Recursive_Val()
{
var doc = GetNode(1174);
var rVal = doc.GetRecursiveValue("testRecursive");
var nullVal = doc.GetRecursiveValue("DoNotFindThis");
Assert.AreEqual("This is the recursive val", rVal);
Assert.AreEqual("", nullVal);
}
[Test]
public void Get_Property_Value_Uses_Converter()
{
var doc = GetNode(1173);
var propVal = doc.GetPropertyValue("content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal);
Assert.AreEqual("<div>This is some content</div>", propVal.ToString());
var propVal2 = doc.GetPropertyValue<IHtmlString>("content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal2);
Assert.AreEqual("<div>This is some content</div>", propVal2.ToString());
var propVal3 = doc.GetPropertyValue("Content");
Assert.IsInstanceOf(typeof(IHtmlString), propVal3);
Assert.AreEqual("<div>This is some content</div>", propVal3.ToString());
}
[Test]
public void Complex_Linq()
{
var doc = GetNode(1173);
var result = doc.Ancestors().OrderBy(x => x.Level)
.Single()
.Descendants()
.FirstOrDefault(x => x.GetPropertyValue<string>("selectedNodes", "").Split(',').Contains("1173"));
Assert.IsNotNull(result);
}
[Test]
public void Index()
{
var doc = GetNode(1173);
Assert.AreEqual(0, doc.Index());
doc = GetNode(1176);
Assert.AreEqual(3, doc.Index());
doc = GetNode(1177);
Assert.AreEqual(1, doc.Index());
doc = GetNode(1178);
Assert.AreEqual(2, doc.Index());
}
[Test]
public void Is_First()
{
var doc = GetNode(1046); //test root nodes
Assert.IsTrue(doc.IsFirst());
doc = GetNode(1172);
Assert.IsFalse(doc.IsFirst());
doc = GetNode(1173); //test normal nodes
Assert.IsTrue(doc.IsFirst());
doc = GetNode(1175);
Assert.IsFalse(doc.IsFirst());
}
[Test]
public void Is_Not_First()
{
var doc = GetNode(1046); //test root nodes
Assert.IsFalse(doc.IsNotFirst());
doc = GetNode(1172);
Assert.IsTrue(doc.IsNotFirst());
doc = GetNode(1173); //test normal nodes
Assert.IsFalse(doc.IsNotFirst());
doc = GetNode(1175);
Assert.IsTrue(doc.IsNotFirst());
}
[Test]
public void Is_Position()
{
var doc = GetNode(1046); //test root nodes
Assert.IsTrue(doc.IsPosition(0));
doc = GetNode(1172);
Assert.IsTrue(doc.IsPosition(1));
doc = GetNode(1173); //test normal nodes
Assert.IsTrue(doc.IsPosition(0));
doc = GetNode(1175);
Assert.IsTrue(doc.IsPosition(1));
}
[Test]
public void Children_GroupBy_DocumentTypeAlias()
{
var doc = GetNode(1046);
var found1 = doc.Children.GroupBy("DocumentTypeAlias");
Assert.AreEqual(2, found1.Count());
Assert.AreEqual(2, found1.Single(x => x.Key.ToString() == "Home").Count());
Assert.AreEqual(1, found1.Single(x => x.Key.ToString() == "CustomDocument").Count());
}
[Test]
public void Children_Where_DocumentTypeAlias()
{
var doc = GetNode(1046);
var found1 = doc.Children.Where("DocumentTypeAlias == \"CustomDocument\"");
var found2 = doc.Children.Where("DocumentTypeAlias == \"Home\"");
Assert.AreEqual(1, found1.Count());
Assert.AreEqual(2, found2.Count());
}
[Test]
public void Children_Order_By_Update_Date()
{
var doc = GetNode(1173);
var ordered = doc.Children.OrderBy("UpdateDate");
var correctOrder = new[] { 1178, 1177, 1174, 1176 };
for (var i = 0; i < correctOrder.Length; i++)
{
Assert.AreEqual(correctOrder[i], ordered.ElementAt(i).Id);
}
}
[Test]
public void FirstChild()
{
var doc = GetNode(1173); // has child nodes
Assert.IsNotNull(doc.FirstChild());
Assert.IsNotNull(doc.FirstChild(x => true));
Assert.IsNotNull(doc.FirstChild<IPublishedContent>());
doc = GetNode(1175); // does not have child nodes
Assert.IsNull(doc.FirstChild());
Assert.IsNull(doc.FirstChild(x => true));
Assert.IsNull(doc.FirstChild<IPublishedContent>());
}
[Test]
public void IsComposedOf()
{
var doc = GetNode(1173);
var isComposedOf = doc.IsComposedOf("MyCompositionAlias");
Assert.IsTrue(isComposedOf);
}
[Test]
public void HasProperty()
{
var doc = GetNode(1173);
var hasProp = doc.HasProperty(Constants.Conventions.Content.UrlAlias);
Assert.IsTrue(hasProp);
}
[Test]
public void HasValue()
{
var doc = GetNode(1173);
var hasValue = doc.HasValue(Constants.Conventions.Content.UrlAlias);
var noValue = doc.HasValue("blahblahblah");
Assert.IsTrue(hasValue);
Assert.IsFalse(noValue);
}
[Test]
public void Ancestors_Where_Visible()
{
var doc = GetNode(1174);
var whereVisible = doc.Ancestors().Where("Visible");
Assert.AreEqual(1, whereVisible.Count());
}
[Test]
public void Visible()
{
var hidden = GetNode(1046);
var visible = GetNode(1173);
Assert.IsFalse(hidden.IsVisible());
Assert.IsTrue(visible.IsVisible());
}
[Test]
public void Ancestor_Or_Self()
{
var doc = GetNode(1173);
var result = doc.AncestorOrSelf();
Assert.IsNotNull(result);
// ancestor-or-self has to be self!
Assert.AreEqual(1173, result.Id);
}
[Test]
public void U4_4559()
{
var doc = GetNode(1174);
var result = doc.AncestorOrSelf(1);
Assert.IsNotNull(result);
Assert.AreEqual(1046, result.Id);
}
[Test]
public void Ancestors_Or_Self()
{
var doc = GetNode(1174);
var result = doc.AncestorsOrSelf();
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1174, 1173, 1046 }));
}
[Test]
public void Ancestors()
{
var doc = GetNode(1174);
var result = doc.Ancestors();
Assert.IsNotNull(result);
Assert.AreEqual(2, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1046 }));
}
[Test]
public void Descendants_Or_Self()
{
var doc = GetNode(1046);
var result = doc.DescendantsOrSelf();
Assert.IsNotNull(result);
Assert.AreEqual(8, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1046, 1173, 1174, 1176, 1175 }));
}
[Test]
public void Descendants()
{
var doc = GetNode(1046);
var result = doc.Descendants();
Assert.IsNotNull(result);
Assert.AreEqual(7, result.Count());
Assert.IsTrue(result.Select(x => ((dynamic)x).Id).ContainsAll(new dynamic[] { 1173, 1174, 1176, 1175, 4444 }));
}
[Test]
public void Up()
{
var doc = GetNode(1173);
var result = doc.Up();
Assert.IsNotNull(result);
Assert.AreEqual((int)1046, (int)result.Id);
}
[Test]
public void Down()
{
var doc = GetNode(1173);
var result = doc.Down();
Assert.IsNotNull(result);
Assert.AreEqual((int)1174, (int)result.Id);
}
[Test]
public void Next()
{
var doc = GetNode(1173);
var result = doc.Next();
Assert.IsNotNull(result);
Assert.AreEqual((int)1175, (int)result.Id);
}
[Test]
public void Next_Without_Sibling()
{
var doc = GetNode(1176);
Assert.IsNull(doc.Next());
}
[Test]
public void Previous_Without_Sibling()
{
var doc = GetNode(1173);
Assert.IsNull(doc.Previous());
}
[Test]
public void Previous()
{
var doc = GetNode(1176);
var result = doc.Previous();
Assert.IsNotNull(result);
Assert.AreEqual((int)1178, (int)result.Id);
}
[Test]
public void GetKey()
{
var key = Guid.Parse("CDB83BBC-A83B-4BA6-93B8-AADEF67D3C09");
// doc is Home (a model) and GetKey unwraps and works
var doc = GetNode(1176);
Assert.IsInstanceOf<Home>(doc);
Assert.AreEqual(key, doc.GetKey());
// wrapped is PublishedContentWrapped and WithKey unwraps
var wrapped = new TestWrapped(doc);
Assert.AreEqual(key, wrapped.GetKey());
}
class TestWrapped : PublishedContentWrapped
{
public TestWrapped(IPublishedContent content)
: base(content)
{ }
}
[Test]
public void DetachedProperty1()
{
var type = new PublishedPropertyType("detached", Constants.PropertyEditors.IntegerAlias);
var prop = PublishedProperty.GetDetached(type.Detached(), "5548");
Assert.IsInstanceOf<int>(prop.Value);
Assert.AreEqual(5548, prop.Value);
}
public void CreateDetachedContentSample()
{
bool previewing = false;
var t = PublishedContentType.Get(PublishedItemType.Content, "detachedSomething");
var values = new Dictionary<string, object>();
var properties = t.PropertyTypes.Select(x =>
{
object value;
if (values.TryGetValue(x.PropertyTypeAlias, out value) == false) value = null;
return PublishedProperty.GetDetached(x.Detached(), value, previewing);
});
// and if you want some sort of "model" it's up to you really...
var c = new DetachedContent(properties);
}
public void CreatedDetachedContentInConverterSample()
{
// the converter args
PublishedPropertyType argPropertyType = null;
object argSource = null;
bool argPreview = false;
var pt1 = new PublishedPropertyType("legend", 0, Constants.PropertyEditors.TextboxAlias);
var pt2 = new PublishedPropertyType("image", 0, Constants.PropertyEditors.MediaPickerAlias);
string val1 = "";
int val2 = 0;
var c = new ImageWithLegendModel(
PublishedProperty.GetDetached(pt1.Nested(argPropertyType), val1, argPreview),
PublishedProperty.GetDetached(pt2.Nested(argPropertyType), val2, argPreview));
}
class ImageWithLegendModel
{
private IPublishedProperty _legendProperty;
private IPublishedProperty _imageProperty;
public ImageWithLegendModel(IPublishedProperty legendProperty, IPublishedProperty imageProperty)
{
_legendProperty = legendProperty;
_imageProperty = imageProperty;
}
public string Legend { get { return _legendProperty.GetValue<string>(); } }
public IPublishedContent Image { get { return _imageProperty.GetValue<IPublishedContent>(); } }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.AspNetCore.Mvc.Formatters.Xml;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.WebUtilities;
namespace Microsoft.AspNetCore.Mvc.Formatters
{
/// <summary>
/// This class handles deserialization of input XML data
/// to strongly-typed objects using <see cref="XmlSerializer"/>
/// </summary>
public class XmlSerializerInputFormatter : TextInputFormatter, IInputFormatterExceptionPolicy
{
private const int DefaultMemoryThreshold = 1024 * 30;
private readonly ConcurrentDictionary<Type, object> _serializerCache = new ConcurrentDictionary<Type, object>();
private readonly XmlDictionaryReaderQuotas _readerQuotas = FormattingUtilities.GetDefaultXmlReaderQuotas();
private readonly MvcOptions _options;
/// <summary>
/// Initializes a new instance of <see cref="XmlSerializerInputFormatter"/>.
/// </summary>
/// <param name="options">The <see cref="MvcOptions"/>.</param>
public XmlSerializerInputFormatter(MvcOptions options)
{
_options = options;
SupportedEncodings.Add(UTF8EncodingWithoutBOM);
SupportedEncodings.Add(UTF16EncodingLittleEndian);
SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationXml);
SupportedMediaTypes.Add(MediaTypeHeaderValues.TextXml);
SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyXmlSyntax);
WrapperProviderFactories = new List<IWrapperProviderFactory>
{
new SerializableErrorWrapperProviderFactory(),
};
}
/// <summary>
/// Gets the list of <see cref="IWrapperProviderFactory"/> to
/// provide the wrapping type for de-serialization.
/// </summary>
public IList<IWrapperProviderFactory> WrapperProviderFactories { get; }
/// <summary>
/// Indicates the acceptable input XML depth.
/// </summary>
public int MaxDepth
{
get { return _readerQuotas.MaxDepth; }
set { _readerQuotas.MaxDepth = value; }
}
/// <summary>
/// The quotas include - DefaultMaxDepth, DefaultMaxStringContentLength, DefaultMaxArrayLength,
/// DefaultMaxBytesPerRead, DefaultMaxNameTableCharCount
/// </summary>
public XmlDictionaryReaderQuotas XmlDictionaryReaderQuotas => _readerQuotas;
/// <inheritdoc />
public virtual InputFormatterExceptionPolicy ExceptionPolicy
{
get
{
if (GetType() == typeof(XmlSerializerInputFormatter))
{
return InputFormatterExceptionPolicy.MalformedInputExceptions;
}
return InputFormatterExceptionPolicy.AllExceptions;
}
}
/// <inheritdoc />
public override async Task<InputFormatterResult> ReadRequestBodyAsync(
InputFormatterContext context,
Encoding encoding)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
var request = context.HttpContext.Request;
Stream readStream = new NonDisposableStream(request.Body);
var disposeReadStream = false;
if (readStream.CanSeek)
{
// The most common way of getting here is the user has request buffering on.
// However, request buffering isn't eager, and consequently it will peform pass-thru synchronous
// reads as part of the deserialization.
// To avoid this, drain and reset the stream.
var position = request.Body.Position;
await readStream.DrainAsync(CancellationToken.None);
readStream.Position = position;
}
else if (!_options.SuppressInputFormatterBuffering)
{
// XmlSerializer does synchronous reads. In order to avoid blocking on the stream, we asynchronously
// read everything into a buffer, and then seek back to the beginning.
var memoryThreshold = DefaultMemoryThreshold;
var contentLength = request.ContentLength.GetValueOrDefault();
if (contentLength > 0 && contentLength < memoryThreshold)
{
// If the Content-Length is known and is smaller than the default buffer size, use it.
memoryThreshold = (int)contentLength;
}
readStream = new FileBufferingReadStream(request.Body, memoryThreshold);
// Ensure the file buffer stream is always disposed at the end of a request.
request.HttpContext.Response.RegisterForDispose(readStream);
await readStream.DrainAsync(CancellationToken.None);
readStream.Seek(0L, SeekOrigin.Begin);
disposeReadStream = true;
}
try
{
var type = GetSerializableType(context.ModelType);
using var xmlReader = CreateXmlReader(readStream, encoding, type);
var serializer = GetCachedSerializer(type);
var deserializedObject = serializer.Deserialize(xmlReader);
// Unwrap only if the original type was wrapped.
if (type != context.ModelType)
{
if (deserializedObject is IUnwrappable unwrappable)
{
deserializedObject = unwrappable.Unwrap(declaredType: context.ModelType);
}
}
return InputFormatterResult.Success(deserializedObject);
}
// XmlSerializer wraps actual exceptions (like FormatException or XmlException) into an InvalidOperationException
// https://github.com/dotnet/corefx/blob/master/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs#L652
catch (InvalidOperationException exception) when (exception.InnerException != null &&
exception.InnerException.InnerException == null &&
string.Equals("Microsoft.GeneratedCode", exception.InnerException.Source, StringComparison.InvariantCulture))
{
// Know this was an XML parsing error because the inner Exception was thrown in the (generated)
// assembly the XmlSerializer uses for parsing. The problem did not arise lower in the stack i.e. it's
// not (for example) an out-of-memory condition.
throw new InputFormatterException(Resources.ErrorDeserializingInputData, exception.InnerException);
}
catch (InvalidOperationException exception) when (exception.InnerException is FormatException ||
exception.InnerException is XmlException)
{
throw new InputFormatterException(Resources.ErrorDeserializingInputData, exception.InnerException);
}
finally
{
if (disposeReadStream)
{
await readStream.DisposeAsync();
}
}
}
/// <inheritdoc />
protected override bool CanReadType(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
return GetCachedSerializer(GetSerializableType(type)) != null;
}
/// <summary>
/// Gets the type to which the XML will be deserialized.
/// </summary>
/// <param name="declaredType">The declared type.</param>
/// <returns>The type to which the XML will be deserialized.</returns>
protected virtual Type GetSerializableType(Type declaredType)
{
if (declaredType == null)
{
throw new ArgumentNullException(nameof(declaredType));
}
var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(
new WrapperProviderContext(declaredType, isSerialization: false));
return wrapperProvider?.WrappingType ?? declaredType;
}
/// <summary>
/// Called during deserialization to get the <see cref="XmlReader"/>.
/// </summary>
/// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
/// <param name="encoding">The <see cref="Encoding"/> used to read the stream.</param>
/// <param name="type">The <see cref="Type"/> that is to be deserialized.</param>
/// <returns>The <see cref="XmlReader"/> used during deserialization.</returns>
protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding, Type type)
{
return CreateXmlReader(readStream, encoding);
}
/// <summary>
/// Called during deserialization to get the <see cref="XmlReader"/>.
/// </summary>
/// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
/// <param name="encoding">The <see cref="Encoding"/> used to read the stream.</param>
/// <returns>The <see cref="XmlReader"/> used during deserialization.</returns>
protected virtual XmlReader CreateXmlReader(Stream readStream, Encoding encoding)
{
if (readStream == null)
{
throw new ArgumentNullException(nameof(readStream));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
return XmlDictionaryReader.CreateTextReader(readStream, encoding, _readerQuotas, onClose: null);
}
/// <summary>
/// Called during deserialization to get the <see cref="XmlSerializer"/>.
/// </summary>
/// <returns>The <see cref="XmlSerializer"/> used during deserialization.</returns>
protected virtual XmlSerializer? CreateSerializer(Type type)
{
try
{
// If the serializer does not support this type it will throw an exception.
return new XmlSerializer(type);
}
catch (Exception)
{
// We do not surface the caught exception because if CanRead returns
// false, then this Formatter is not picked up at all.
return null;
}
}
/// <summary>
/// Gets the cached serializer or creates and caches the serializer for the given type.
/// </summary>
/// <returns>The <see cref="XmlSerializer"/> instance.</returns>
protected virtual XmlSerializer GetCachedSerializer(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (!_serializerCache.TryGetValue(type, out var serializer))
{
serializer = CreateSerializer(type);
if (serializer != null)
{
_serializerCache.TryAdd(type, serializer);
}
}
return (XmlSerializer)serializer!;
}
}
}
| |
// Copyright (c) 2017 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using Palaso.IO;
namespace LfMerge.AutomatedSRTests
{
public class MongoHelper : IDisposable
{
private bool _keepDatabase;
public static void Initialize()
{
var modelVersionDirectories = Directory.GetDirectories(Settings.DataDir, "70*");
foreach (var modelVersionDirectory in modelVersionDirectories)
{
var modelVersion = Path.GetFileName(modelVersionDirectory);
Initialize(modelVersion);
}
}
public static void Initialize(string modelVersion, int? version = null)
{
// we use a git repo to store the JSON files that we'll import into Mongo. Storing
// the JSON files as patch files allows to easily see (e.g. on GitHub) the changes
// between two versions; recreating the git repo at test run time makes it easier to
// switch between versions.
var mongoSourceDir = GetMongoSourceDir(modelVersion);
InitSourceDir(mongoSourceDir);
var patchFiles = Directory.GetFiles(GetMongoPatchDir(modelVersion), "*.patch");
Array.Sort(patchFiles);
foreach (var file in patchFiles)
{
var patchNoStr = Path.GetFileName(file).Substring(0, 4);
var patchNo = int.Parse(patchNoStr);
if (version.HasValue && patchNo > version.Value)
break;
Run("git", $"am {file}", mongoSourceDir);
Run("git", $"tag r{patchNo}", mongoSourceDir);
}
}
public MongoHelper(string dbName, bool keepDatabase = false, bool removeDatabase = true)
{
_keepDatabase = keepDatabase;
DbName = dbName;
if (removeDatabase)
RemoveDatabase();
}
#region Dispose functionality
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_keepDatabase)
RemoveDatabase();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MongoHelper()
{
Dispose(false);
}
#endregion
public void RestoreDatabase(string tag, int modelVersion)
{
RestoreDatabase(tag, modelVersion.ToString());
}
public void RestoreDatabase(string tag, string modelVersion)
{
var mongoSourceDir = GetMongoSourceDir(modelVersion);
Run("git", $"checkout {tag}", mongoSourceDir);
var projectEntryFile = Path.Combine(mongoSourceDir, DbName + ".json");
if (!File.Exists(projectEntryFile))
{
throw new FileNotFoundException($"Can't find file {projectEntryFile}");
}
var tempFile = ReadJson(projectEntryFile);
Run("mongoimport",
$"--host {Settings.MongoHostName}:{Settings.MongoPort} --db scriptureforge " +
$"--collection projects --file {tempFile}",
GetMongoPatchDir(modelVersion));
File.Delete(tempFile);
ImportCollection("activity", modelVersion);
ImportCollection("lexicon", modelVersion);
ImportCollection("optionlists", modelVersion);
}
public void SaveDatabase(string patchDir, string modelVersion, string msg, int startNumber)
{
var mongoSourceDir = GetMongoSourceDir(modelVersion);
InitSourceDir(mongoSourceDir);
var project = DbName.StartsWith("sf_") ? DbName.Substring(3) : DbName;
var file = Path.Combine(mongoSourceDir, $"{DbName}.json");
var content = Run("mongoexport",
$"--host {Settings.MongoHostName}:{Settings.MongoPort} " +
$"--db scriptureforge --collection projects --query '{{ \"projectName\" : \"{project}\" }}'",
mongoSourceDir);
WriteJson(file, content);
Run("git", $"add {file}", mongoSourceDir);
ExportCollection("activity", modelVersion);
ExportCollection("lexicon", modelVersion);
ExportCollection("optionlists", modelVersion);
AddCollectionToGit("activity", modelVersion);
AddCollectionToGit("lexicon", modelVersion);
AddCollectionToGit("optionlists", modelVersion);
Run("git", $"commit -a -m \"{msg}\"", mongoSourceDir);
Run("git", $"format-patch -1 -o {patchDir} --start-number {startNumber}", mongoSourceDir);
}
private static void WriteJson(string file, string content)
{
File.WriteAllText(file, content.Replace("}", "}\n"));
}
private static string ReadJson(string file)
{
var tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, File.ReadAllText(file).Replace("}\n", "}"));
return tempFile;
}
private void ImportCollection(string collection, string modelVersion)
{
var mongoSourceDir = GetMongoSourceDir(modelVersion);
var file = Path.Combine(mongoSourceDir, $"{DbName}.{collection}.json");
var tempFile = ReadJson(file);
Run("mongoimport",
$"--host {Settings.MongoHostName}:{Settings.MongoPort} --db {DbName} " +
$"--drop --collection {collection} --file {tempFile}",
mongoSourceDir);
File.Delete(tempFile);
}
private void ExportCollection(string collection, string modelVersion)
{
var mongoSourceDir = GetMongoSourceDir(modelVersion);
var file = Path.Combine(mongoSourceDir, $"{DbName}.{collection}.json");
var content = Run("mongoexport",
$"--host {Settings.MongoHostName}:{Settings.MongoPort} --db {DbName} " +
$"--collection {collection}",
mongoSourceDir);
WriteJson(file, content);
}
private void AddCollectionToGit(string collection, string modelVersion)
{
var mongoSourceDir = GetMongoSourceDir(modelVersion);
var file = Path.Combine(mongoSourceDir, $"{DbName}.{collection}.json");
Run("git", $"add {file}", mongoSourceDir);
}
public static string GetMongoPatchDir(string modelVersion)
{
return Path.Combine(Settings.DataDir, modelVersion, "mongo");
}
private static string GetMongoSourceDir(string modelVersion)
{
return Path.Combine(Settings.TempDir, "source", modelVersion);
}
private static void InitSourceDir(string gitDir)
{
Directory.CreateDirectory(gitDir);
Run("git", "init .", gitDir);
Run("git", "config user.email \"you@example.com\"", gitDir);
Run("git", "config user.name \"Your Name\"", gitDir);
}
public static void Cleanup()
{
DirectoryUtilities.DeleteDirectoryRobust(Path.Combine(Settings.TempDir, "patches"));
}
private string DbName { get; }
private static string Run(string command, string args, string workDir, bool throwException = true, bool ignoreErrors = false)
{
//Console.WriteLine();
//Console.WriteLine($"Running command: {command} {args}");
using (var process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WorkingDirectory = workDir;
process.StartInfo.FileName = command;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
var output = new StringBuilder();
var stderr = new StringBuilder();
using (var outputWaitHandle = new AutoResetEvent(false))
using (var errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
outputWaitHandle.Set();
else
output.AppendLine(e.Data);
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
errorWaitHandle.Set();
else
stderr.AppendLine(e.Data);
};
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
errorWaitHandle.WaitOne();
outputWaitHandle.WaitOne();
//Console.WriteLine($"Output: {output}");
//Console.WriteLine($"Stderr: {stderr}");
if (process.ExitCode == 0)
return output.ToString();
if (ignoreErrors)
return string.Empty;
var msg = $"Running '{command} {args}'\nreturned {process.ExitCode}.\nStderr:\n{stderr}\nOutput:\n{output}";
if (throwException)
throw new ApplicationException(msg);
Console.WriteLine(msg);
return stderr.ToString();
}
}
}
private void RemoveDatabase()
{
var projectCode = DbName.StartsWith("sf_") ? DbName.Substring(3) : DbName;
var workDir = Path.Combine(Settings.TempDir, "patches");
Run("mongo", $"{DbName} --eval 'db.dropDatabase()'", workDir, false, true);
Run("mongo",
$"--host {Settings.MongoHostName} --port {Settings.MongoPort} " +
$"scriptureforge --eval 'db.projects.remove({{ \"projectName\" : \"{projectCode}\" }})'",
workDir, false, true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SSL encapsulated over TDS transport. During SSL handshake, SSL packets are
/// transported in TDS packet type 0x12. Once SSL handshake has completed, SSL
/// packets are sent transparently.
/// </summary>
internal sealed class SslOverTdsStream : Stream
{
private readonly Stream _stream;
private int _packetBytes = 0;
private bool _encapsulate;
private const int PACKET_SIZE_WITHOUT_HEADER = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE - TdsEnums.HEADER_LEN;
private const int PRELOGIN_PACKET_TYPE = 0x12;
/// <summary>
/// Constructor
/// </summary>
/// <param name="stream">Underlying stream</param>
public SslOverTdsStream(Stream stream)
{
_stream = stream;
_encapsulate = true;
}
/// <summary>
/// Finish SSL handshake. Stop encapsulating in TDS.
/// </summary>
public void FinishHandshake()
{
_encapsulate = false;
}
/// <summary>
/// Read buffer
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="offset">Offset</param>
/// <param name="count">Byte count</param>
/// <returns>Bytes read</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int readBytes;
byte[] scratch = new byte[count < TdsEnums.HEADER_LEN ? TdsEnums.HEADER_LEN : count];
if (_encapsulate)
{
if (_packetBytes == 0)
{
readBytes = _stream.Read(scratch, 0, TdsEnums.HEADER_LEN);
_packetBytes = scratch[2] * 0x100;
_packetBytes += scratch[3];
_packetBytes -= TdsEnums.HEADER_LEN;
}
if (count > _packetBytes)
{
count = _packetBytes;
}
}
readBytes = _stream.Read(scratch, 0, count);
if (_encapsulate)
{
_packetBytes -= readBytes;
}
Buffer.BlockCopy(scratch, 0, buffer, offset, readBytes);
return readBytes;
}
/// <summary>
/// Write buffer
/// </summary>
/// <param name="buffer">Buffer</param>
/// <param name="offset">Offset</param>
/// <param name="count">Byte count</param>
public override void Write(byte[] buffer, int offset, int count)
{
int currentCount = 0;
int currentOffset = offset;
while (count > 0)
{
// During the SSL negotiation phase, SSL is tunnelled over TDS packet type 0x12. After
// negotiation, the underlying socket only sees SSL frames.
//
if (_encapsulate)
{
if (count > PACKET_SIZE_WITHOUT_HEADER)
{
currentCount = PACKET_SIZE_WITHOUT_HEADER;
}
else
{
currentCount = count;
}
count -= currentCount;
// Prepend buffer data with TDS prelogin header
byte[] combinedBuffer = new byte[TdsEnums.HEADER_LEN + currentCount];
// We can only send 4088 bytes in one packet. Header[1] is set to 1 if this is a
// partial packet (whether or not count != 0).
//
combinedBuffer[0] = PRELOGIN_PACKET_TYPE;
combinedBuffer[1] = (byte)(count > 0 ? 0 : 1);
combinedBuffer[2] = (byte)((currentCount + TdsEnums.HEADER_LEN) / 0x100);
combinedBuffer[3] = (byte)((currentCount + TdsEnums.HEADER_LEN) % 0x100);
combinedBuffer[4] = 0;
combinedBuffer[5] = 0;
combinedBuffer[6] = 0;
combinedBuffer[7] = 0;
for(int i = TdsEnums.HEADER_LEN; i < combinedBuffer.Length; i++)
{
combinedBuffer[i] = buffer[currentOffset + (i - TdsEnums.HEADER_LEN)];
}
_stream.Write(combinedBuffer, 0, combinedBuffer.Length);
}
else
{
currentCount = count;
count = 0;
_stream.Write(buffer, currentOffset, currentCount);
}
_stream.Flush();
currentOffset += currentCount;
}
}
/// <summary>
/// Set stream length.
/// </summary>
/// <param name="value">Length</param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// Flush stream
/// </summary>
public override void Flush()
{
_stream.Flush();
}
/// <summary>
/// Get/set stream position
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Seek in stream
/// </summary>
/// <param name="offset">Offset</param>
/// <param name="origin">Origin</param>
/// <returns>Position</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Check if stream can be read from
/// </summary>
public override bool CanRead
{
get { return _stream.CanRead; }
}
/// <summary>
/// Check if stream can be written to
/// </summary>
public override bool CanWrite
{
get { return _stream.CanWrite; }
}
/// <summary>
/// Check if stream can be seeked
/// </summary>
public override bool CanSeek
{
get { return false; } // Seek not supported
}
/// <summary>
/// Get stream length
/// </summary>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyComplex
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Polymorphism operations.
/// </summary>
public partial class Polymorphism : IServiceOperations<AutoRestComplexTestService>, IPolymorphism
{
/// <summary>
/// Initializes a new instance of the Polymorphism class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Polymorphism(AutoRestComplexTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestComplexTestService
/// </summary>
public AutoRestComplexTestService Client { get; private set; }
/// <summary>
/// Get complex types that are polymorphic
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Fish>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic
/// </summary>
/// <param name='complexBody'>
/// Please put a salmon that looks like this:
/// {
/// 'fishtype':'Salmon',
/// 'location':'alaska',
/// 'iswild':true,
/// 'species':'king',
/// 'length':1.0,
/// 'siblings':[
/// {
/// 'fishtype':'Shark',
/// 'age':6,
/// 'birthday': '2012-01-05T01:00:00Z',
/// 'length':20.0,
/// 'species':'predator',
/// },
/// {
/// 'fishtype':'Sawshark',
/// 'age':105,
/// 'birthday': '1900-01-05T01:00:00Z',
/// 'length':10.0,
/// 'picture': new Buffer([255, 255, 255, 255,
/// 254]).toString('base64'),
/// 'species':'dangerous',
/// },
/// {
/// 'fishtype': 'goblin',
/// 'age': 1,
/// 'birthday': '2015-08-08T00:00:00Z',
/// 'length': 30.0,
/// 'species': 'scary',
/// 'jawsize': 5
/// }
/// ]
/// };
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that are polymorphic, attempting to omit required
/// 'birthday' field - the request should not be allowed from the client
/// </summary>
/// <param name='complexBody'>
/// Please attempt put a sawshark that looks like this, the client should not
/// allow this data to be sent:
/// {
/// "fishtype": "sawshark",
/// "species": "snaggle toothed",
/// "length": 18.5,
/// "age": 2,
/// "birthday": "2013-06-01T01:00:00Z",
/// "location": "alaska",
/// "picture": base64(FF FF FF FF FE),
/// "siblings": [
/// {
/// "fishtype": "shark",
/// "species": "predator",
/// "birthday": "2012-01-05T01:00:00Z",
/// "length": 20,
/// "age": 6
/// },
/// {
/// "fishtype": "sawshark",
/// "species": "dangerous",
/// "picture": base64(FF FF FF FF FE),
/// "length": 10,
/// "age": 105
/// }
/// ]
/// }
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
if (complexBody != null)
{
complexBody.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure.PipeWriterHelpers
{
/// <summary>
/// Wraps a PipeWriter so you can start appending more data to the pipe prior to the previous flush completing.
/// </summary>
internal sealed class ConcurrentPipeWriter : PipeWriter
{
// The following constants were copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs
// and the associated StreamPipeWriterOptions defaults.
private const int InitialSegmentPoolSize = 4; // 16K
private const int MaxSegmentPoolSize = 256; // 1MB
private const int MinimumBufferSize = 4096; // 4K
private static readonly Exception _successfullyCompletedSentinel = new Exception();
private readonly object _sync;
private readonly PipeWriter _innerPipeWriter;
private readonly MemoryPool<byte> _pool;
private readonly BufferSegmentStack _bufferSegmentPool = new BufferSegmentStack(InitialSegmentPoolSize);
private BufferSegment? _head;
private BufferSegment? _tail;
private Memory<byte> _tailMemory;
private int _tailBytesBuffered;
private long _bytesBuffered;
// When _currentFlushTcs is null and _head/_tail is also null, the ConcurrentPipeWriter is in passthrough mode.
// When the ConcurrentPipeWriter is not in passthrough mode, that could be for one of two reasons:
//
// 1. A flush of the _innerPipeWriter is in progress.
// 2. Or the last flush of the _innerPipeWriter completed between external calls to GetMemory/Span() and Advance().
//
// In either case, we need to manually append buffer segments until the loop in the current or next call to FlushAsync()
// flushes all the buffers putting the ConcurrentPipeWriter back into passthrough mode.
// The manual buffer appending logic is borrowed from corefx's StreamPipeWriter.
private TaskCompletionSource<FlushResult>? _currentFlushTcs;
private bool _bufferedWritePending;
// We're trusting the Http2FrameWriter and Http1OutputProducer to not call into the PipeWriter after calling Abort() or Complete().
// If an Abort() is called while a flush is in progress, we clean up after the next flush completes, and don't flush again.
private bool _aborted;
// If an Complete() is called while a flush is in progress, we clean up after the flush loop completes, and call Complete() on the inner PipeWriter.
private Exception? _completeException;
public ConcurrentPipeWriter(PipeWriter innerPipeWriter, MemoryPool<byte> pool, object sync)
{
_innerPipeWriter = innerPipeWriter;
_pool = pool;
_sync = sync;
}
public void Reset()
{
Debug.Assert(_currentFlushTcs == null, "There should not be a pending flush.");
_aborted = false;
_completeException = null;
}
public override Memory<byte> GetMemory(int sizeHint = 0)
{
if (_currentFlushTcs == null && _head == null)
{
return _innerPipeWriter.GetMemory(sizeHint);
}
AllocateMemoryUnsynchronized(sizeHint);
return _tailMemory;
}
public override Span<byte> GetSpan(int sizeHint = 0)
{
if (_currentFlushTcs == null && _head == null)
{
return _innerPipeWriter.GetSpan(sizeHint);
}
AllocateMemoryUnsynchronized(sizeHint);
return _tailMemory.Span;
}
public override void Advance(int bytes)
{
if (_currentFlushTcs == null && _head == null)
{
_innerPipeWriter.Advance(bytes);
return;
}
if ((uint)bytes > (uint)_tailMemory.Length)
{
ThrowArgumentOutOfRangeException(nameof(bytes));
}
_tailBytesBuffered += bytes;
_bytesBuffered += bytes;
_tailMemory = _tailMemory.Slice(bytes);
_bufferedWritePending = false;
}
public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default)
{
if (_currentFlushTcs != null)
{
return new ValueTask<FlushResult>(_currentFlushTcs.Task);
}
if (_bytesBuffered > 0)
{
CopyAndReturnSegmentsUnsynchronized();
}
var flushTask = _innerPipeWriter.FlushAsync(cancellationToken);
if (flushTask.IsCompletedSuccessfully)
{
if (_currentFlushTcs != null)
{
CompleteFlushUnsynchronized(flushTask.GetAwaiter().GetResult(), null);
}
return flushTask;
}
// Use a TCS instead of something custom so it can be awaited by multiple awaiters.
_currentFlushTcs = new TaskCompletionSource<FlushResult>(TaskCreationOptions.RunContinuationsAsynchronously);
var result = new ValueTask<FlushResult>(_currentFlushTcs.Task);
// FlushAsyncAwaited clears the TCS prior to completing. Make sure to construct the ValueTask
// from the TCS before calling FlushAsyncAwaited in case FlushAsyncAwaited completes inline.
_ = FlushAsyncAwaited(flushTask, cancellationToken);
return result;
}
private async Task FlushAsyncAwaited(ValueTask<FlushResult> flushTask, CancellationToken cancellationToken)
{
try
{
// This while (true) does look scary, but the real continuation condition is at the start of the loop
// after the await, so the _sync lock can be acquired.
while (true)
{
var flushResult = await flushTask;
lock (_sync)
{
if (_bytesBuffered == 0 || _aborted)
{
CompleteFlushUnsynchronized(flushResult, null);
return;
}
if (flushResult.IsCanceled)
{
Debug.Assert(_currentFlushTcs != null);
// Complete anyone currently awaiting a flush with the canceled FlushResult since CancelPendingFlush() was called.
_currentFlushTcs.SetResult(flushResult);
// Reset _currentFlushTcs, so we don't enter passthrough mode while we're still flushing.
_currentFlushTcs = new TaskCompletionSource<FlushResult>(TaskCreationOptions.RunContinuationsAsynchronously);
}
CopyAndReturnSegmentsUnsynchronized();
flushTask = _innerPipeWriter.FlushAsync(cancellationToken);
}
}
}
catch (Exception ex)
{
lock (_sync)
{
CompleteFlushUnsynchronized(default, ex);
}
}
}
public override void CancelPendingFlush()
{
// FlushAsyncAwaited never ignores a canceled FlushResult.
_innerPipeWriter.CancelPendingFlush();
}
// To return all the segments without completing the inner pipe, call Abort().
public override void Complete(Exception? exception = null)
{
// Store the exception or sentinel in a field so that if a flush is ongoing, we call the
// inner Complete() method with the correct exception or lack thereof once the flush loop ends.
_completeException = exception ?? _successfullyCompletedSentinel;
if (_currentFlushTcs == null)
{
if (_bytesBuffered > 0)
{
CopyAndReturnSegmentsUnsynchronized();
}
CleanupSegmentsUnsynchronized();
_innerPipeWriter.Complete(exception);
}
}
public void Abort()
{
_aborted = true;
// If we're flushing, the cleanup will happen after the flush.
if (_currentFlushTcs == null)
{
CleanupSegmentsUnsynchronized();
}
}
private void CleanupSegmentsUnsynchronized()
{
BufferSegment? segment = _head;
while (segment != null)
{
BufferSegment returnSegment = segment;
segment = segment.NextSegment;
returnSegment.ResetMemory();
}
_head = null;
_tail = null;
_tailMemory = null;
}
private void CopyAndReturnSegmentsUnsynchronized()
{
Debug.Assert(_tail != null);
// Update any buffered data
_tail.End += _tailBytesBuffered;
_tailBytesBuffered = 0;
var segment = _head;
while (segment != null)
{
_innerPipeWriter.Write(segment.Memory.Span);
var returnSegment = segment;
segment = segment.NextSegment;
// We haven't reached the tail of the linked list yet, so we can always return the returnSegment.
if (segment != null)
{
returnSegment.ResetMemory();
ReturnSegmentUnsynchronized(returnSegment);
}
}
if (_bufferedWritePending)
{
// If an advance is pending, so is a flush, so the _tail segment should still get returned eventually.
_head = _tail;
}
else
{
_tail.ResetMemory();
ReturnSegmentUnsynchronized(_tail);
_head = _tail = null;
}
// Even if a non-passthrough call to Advance is pending, there a 0 bytes currently buffered.
_bytesBuffered = 0;
}
private void CompleteFlushUnsynchronized(FlushResult flushResult, Exception? flushEx)
{
// Ensure all blocks are returned prior to the last call to FlushAsync() completing.
if (_completeException != null || _aborted)
{
CleanupSegmentsUnsynchronized();
}
if (ReferenceEquals(_completeException, _successfullyCompletedSentinel))
{
_innerPipeWriter.Complete();
}
else if (_completeException != null)
{
_innerPipeWriter.Complete(_completeException);
}
Debug.Assert(_currentFlushTcs != null);
if (flushEx != null)
{
_currentFlushTcs.SetException(flushEx);
}
else
{
_currentFlushTcs.SetResult(flushResult);
}
_currentFlushTcs = null;
}
// The methods below were copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.IO.Pipelines/src/System/IO/Pipelines/StreamPipeWriter.cs
private void AllocateMemoryUnsynchronized(int sizeHint)
{
_bufferedWritePending = true;
if (_head == null)
{
// We need to allocate memory to write since nobody has written before
BufferSegment newSegment = AllocateSegmentUnsynchronized(sizeHint);
// Set all the pointers
_head = _tail = newSegment;
_tailBytesBuffered = 0;
}
else
{
int bytesLeftInBuffer = _tailMemory.Length;
if (bytesLeftInBuffer == 0 || bytesLeftInBuffer < sizeHint)
{
Debug.Assert(_tail != null);
if (_tailBytesBuffered > 0)
{
// Flush buffered data to the segment
_tail.End += _tailBytesBuffered;
_tailBytesBuffered = 0;
}
BufferSegment newSegment = AllocateSegmentUnsynchronized(sizeHint);
_tail.SetNext(newSegment);
_tail = newSegment;
}
}
}
private BufferSegment AllocateSegmentUnsynchronized(int minSize)
{
BufferSegment newSegment = CreateSegmentUnsynchronized();
if (minSize <= _pool.MaxBufferSize)
{
// Use the specified pool if it fits
newSegment.SetOwnedMemory(_pool.Rent(GetSegmentSize(minSize, _pool.MaxBufferSize)));
}
else
{
// We can't use the recommended pool so use the ArrayPool
newSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(minSize));
}
_tailMemory = newSegment.AvailableMemory;
return newSegment;
}
private BufferSegment CreateSegmentUnsynchronized()
{
if (_bufferSegmentPool.TryPop(out var segment))
{
return segment;
}
return new BufferSegment();
}
private void ReturnSegmentUnsynchronized(BufferSegment segment)
{
if (_bufferSegmentPool.Count < MaxSegmentPoolSize)
{
_bufferSegmentPool.Push(segment);
}
}
private static int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue)
{
// First we need to handle case where hint is smaller than minimum segment size
sizeHint = Math.Max(MinimumBufferSize, sizeHint);
// After that adjust it to fit into pools max buffer size
var adjustedToMaximumSize = Math.Min(maxBufferSize, sizeHint);
return adjustedToMaximumSize;
}
// Copied from https://github.com/dotnet/corefx/blob/de3902bb56f1254ec1af4bf7d092fc2c048734cc/src/System.Memory/src/System/ThrowHelper.cs
private static void ThrowArgumentOutOfRangeException(string argumentName) { throw CreateArgumentOutOfRangeException(argumentName); }
[MethodImpl(MethodImplOptions.NoInlining)]
private static Exception CreateArgumentOutOfRangeException(string argumentName) { return new ArgumentOutOfRangeException(argumentName); }
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type MailFolderMessagesCollectionRequest.
/// </summary>
public partial class MailFolderMessagesCollectionRequest : BaseRequest, IMailFolderMessagesCollectionRequest
{
/// <summary>
/// Constructs a new MailFolderMessagesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public MailFolderMessagesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Message to the collection via POST.
/// </summary>
/// <param name="message">The Message to add.</param>
/// <returns>The created Message.</returns>
public System.Threading.Tasks.Task<Message> AddAsync(Message message)
{
return this.AddAsync(message, CancellationToken.None);
}
/// <summary>
/// Adds the specified Message to the collection via POST.
/// </summary>
/// <param name="message">The Message to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Message.</returns>
public System.Threading.Tasks.Task<Message> AddAsync(Message message, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Message>(message, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IMailFolderMessagesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IMailFolderMessagesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<MailFolderMessagesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Expand(Expression<Func<Message, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Select(Expression<Func<Message, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IMailFolderMessagesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetTapePartitionFailuresSpectraS3Request : Ds3Request
{
private string _errorMessage;
public string ErrorMessage
{
get { return _errorMessage; }
set { WithErrorMessage(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _partitionId;
public string PartitionId
{
get { return _partitionId; }
set { WithPartitionId(value); }
}
private TapePartitionFailureType? _type;
public TapePartitionFailureType? Type
{
get { return _type; }
set { WithType(value); }
}
public GetTapePartitionFailuresSpectraS3Request WithErrorMessage(string errorMessage)
{
this._errorMessage = errorMessage;
if (errorMessage != null)
{
this.QueryParams.Add("error_message", errorMessage);
}
else
{
this.QueryParams.Remove("error_message");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithPartitionId(Guid? partitionId)
{
this._partitionId = partitionId.ToString();
if (partitionId != null)
{
this.QueryParams.Add("partition_id", partitionId.ToString());
}
else
{
this.QueryParams.Remove("partition_id");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithPartitionId(string partitionId)
{
this._partitionId = partitionId;
if (partitionId != null)
{
this.QueryParams.Add("partition_id", partitionId);
}
else
{
this.QueryParams.Remove("partition_id");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request WithType(TapePartitionFailureType? type)
{
this._type = type;
if (type != null)
{
this.QueryParams.Add("type", type.ToString());
}
else
{
this.QueryParams.Remove("type");
}
return this;
}
public GetTapePartitionFailuresSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/tape_partition_failure";
}
}
}
}
| |
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 AccessTokenMvcApiService.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 (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// InheritanceOperations operations.
/// </summary>
internal partial class InheritanceOperations : IServiceOperations<AzureCompositeModel>, IInheritanceOperations
{
/// <summary>
/// Initializes a new instance of the InheritanceOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal InheritanceOperations(AzureCompositeModel client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the AzureCompositeModel
/// </summary>
public AzureCompositeModel Client { get; private set; }
/// <summary>
/// Get complex types that extend others
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Siamese>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Siamese>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Siamese>(_responseContent, Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put complex types that extend others
/// </summary>
/// <param name='complexBody'>
/// Please put a siamese with id=2, name="Siameee", color=green, breed=persion,
/// which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato",
/// and the 2nd one named "Tomato" with id=-1 and food="french fries".
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Siamese complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (complexBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "complexBody");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("complexBody", complexBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/inheritance/valid").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(complexBody != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, Client.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright 2007-2012 Alfresco Software Limited.
*
* 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.
*
* This file is part of an unsupported extension to Alfresco.
*
* [BRIEF DESCRIPTION OF FILE CONTENTS]
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
namespace AlfrescoWord2003
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public partial class AlfrescoPane : Form
{
private const int INTERNET_OPTION_END_BROWSER_SESSION = 42;
private Word.Application m_WordApplication;
private ServerDetails m_ServerDetails;
private string m_TemplateRoot = "";
private bool m_ShowPaneOnActivate = false;
private bool m_ManuallyHidden = false;
private bool m_LastWebPageSuccessful = true;
private bool m_DebugMode = false;
private bool m_ClearSession = false;
private bool m_SupportsDocx = false;
// Win32 SDK functions
[DllImport("user32.dll")]
public static extern int SetFocus(int hWnd);
[DllImport("wininet.dll")]
public static extern int InternetSetOption(int hInternet, int lOption, string sBuffer, int lBufferLength);
public Word.Application WordApplication
{
set
{
m_WordApplication = value;
m_SupportsDocx = (Convert.ToDecimal(m_WordApplication.Version, System.Globalization.CultureInfo.InvariantCulture) > 11);
}
}
public string DefaultTemplate
{
set
{
m_TemplateRoot = value;
}
}
public ServerDetails CurrentServer
{
get
{
return m_ServerDetails;
}
}
public AlfrescoPane()
{
InitializeComponent();
m_ServerDetails = new ServerDetails();
LoadSettings();
}
~AlfrescoPane()
{
m_ServerDetails.saveWindowPosition(this);
}
public void OnDocumentChanged()
{
bool bHaveDocument = (m_WordApplication.Documents.Count > 0);
try
{
if (bHaveDocument)
{
this.showDocumentDetails();
if (!m_ManuallyHidden)
{
this.Show();
}
}
else
{
m_ServerDetails.DocumentPath = "";
// this.showHome(false);
}
}
catch
{
}
}
delegate void OnWindowActivateCallback();
public void OnWindowActivate()
{
if (m_ShowPaneOnActivate && !m_ManuallyHidden)
{
if (this.InvokeRequired)
{
OnWindowActivateCallback callback = new OnWindowActivateCallback(OnWindowActivate);
this.Invoke(callback);
}
else
{
this.Show();
m_WordApplication.Activate();
}
}
}
delegate void OnWindowDeactivateCallback();
public void OnWindowDeactivate()
{
if (this.InvokeRequired)
{
OnWindowDeactivateCallback callback = new OnWindowDeactivateCallback(OnWindowDeactivate);
this.Invoke(callback);
}
else
{
m_ShowPaneOnActivate = true;
this.Hide();
}
}
public void OnDocumentBeforeClose()
{
m_ServerDetails.DocumentPath = "";
if (m_WordApplication.Documents.Count == 1)
{
// Closing last document, but might also be closing app
this.showHome(true);
}
}
public void OnToggleVisible()
{
m_ManuallyHidden = !m_ManuallyHidden;
if (m_ManuallyHidden)
{
this.Hide();
}
else
{
this.Show();
m_WordApplication.Activate();
}
}
public void showHome(bool isClosing)
{
// Do we have a valid web server address?
if (m_ServerDetails.WebClientURL == "")
{
// No - show the configuration UI
PanelMode = PanelModes.Configuration;
}
else
{
// Yes - navigate to the home template
string theURI = string.Format(@"{0}{1}myAlfresco?p=&e=doc", m_ServerDetails.WebClientURL, m_TemplateRoot);
// We don't prompt the user if the document is closing
string strAuthTicket = m_ServerDetails.getAuthenticationTicket(!isClosing);
/**
* Long ticket fix - the encoded ticket is 2426 characters long, therefore has to be sent
* as an HTTP header to avoid the IE6 and IE7 2048 character limit on a GET URL
*/
string strAuthHeader = "";
if ((strAuthTicket != "") && (strAuthTicket != "ntlm"))
{
if ((Uri.EscapeDataString(strAuthTicket).Length + theURI.Length) > 1024)
{
strAuthHeader = "ticket: " + strAuthTicket;
}
else
{
theURI += "&ticket=" + strAuthTicket;
}
}
if ((strAuthTicket == "") && !isClosing)
{
PanelMode = PanelModes.Configuration;
return;
}
if (m_ClearSession)
{
m_ClearSession = false;
InternetSetOption(0, INTERNET_OPTION_END_BROWSER_SESSION, null, 0);
}
if (!isClosing || (strAuthTicket != ""))
{
webBrowser.ObjectForScripting = this;
UriBuilder uriBuilder = new UriBuilder(theURI);
webBrowser.Navigate(uriBuilder.Uri.AbsoluteUri, null, null, strAuthHeader);
PanelMode = PanelModes.WebBrowser;
}
}
}
public void showDocumentDetails()
{
string relativePath = "";
// Do we have a valid web server address?
if (m_ServerDetails.WebClientURL == "")
{
// No - show the configuration UI
PanelMode = PanelModes.Configuration;
}
else
{
m_ServerDetails.DocumentPath = m_WordApplication.ActiveDocument.FullName;
relativePath = m_ServerDetails.DocumentPath;
if (relativePath.Length > 0)
{
if (!relativePath.StartsWith("/"))
{
relativePath = "/" + relativePath;
}
// Strip off any additional parameters
int paramPos = relativePath.IndexOf("?");
if (paramPos != -1)
{
relativePath = relativePath.Substring(0, paramPos);
}
}
string theURI = string.Format(@"{0}{1}documentDetails?p={2}&e=doc", m_ServerDetails.WebClientURL, m_TemplateRoot, relativePath);
string strAuthTicket = m_ServerDetails.getAuthenticationTicket(true);
/**
* Long ticket fix - the encoded ticket is 2426 characters long, therefore has to be sent
* as an HTTP header to avoid the IE6 and IE7 2048 character limit on a GET URL
*/
string strAuthHeader = "";
if ((strAuthTicket != "") && (strAuthTicket != "ntlm"))
{
if ((Uri.EscapeDataString(strAuthTicket).Length + theURI.Length) > 1024)
{
strAuthHeader = "ticket: " + strAuthTicket;
}
else
{
theURI += "&ticket=" + strAuthTicket;
}
}
if (strAuthTicket == "")
{
PanelMode = PanelModes.Configuration;
return;
}
if (m_ClearSession)
{
m_ClearSession = false;
InternetSetOption(0, INTERNET_OPTION_END_BROWSER_SESSION, null, 0);
}
webBrowser.ObjectForScripting = this;
UriBuilder uriBuilder = new UriBuilder(theURI);
webBrowser.Navigate(uriBuilder.Uri.AbsoluteUri, null, null, strAuthHeader);
PanelMode = PanelModes.WebBrowser;
}
}
public void openDocument(string documentPath)
{
object missingValue = Type.Missing;
// WebDAV or CIFS?
string strFullPath = m_ServerDetails.getFullPath(documentPath, "", false);
object file = strFullPath;
try
{
if (m_DebugMode)
{
MessageBox.Show("Document path=\n" + strFullPath, "Open Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Word.Document doc = m_WordApplication.Documents.Open(
ref file, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);
}
catch (Exception e)
{
MessageBox.Show(Properties.Resources.UnableToOpen + ": " + e.Message, Properties.Resources.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void compareDocument(string relativeURL)
{
object missingValue = Type.Missing;
if (relativeURL.StartsWith("/"))
{
relativeURL = relativeURL.Substring(1);
}
if (m_DebugMode)
{
MessageBox.Show("Document path=\n" + m_ServerDetails.WebClientURL + relativeURL, "Compare Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
m_WordApplication.ActiveDocument.Compare(
m_ServerDetails.WebClientURL + relativeURL, ref missingValue, ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue);
}
public void insertDocument(string relativePath, string nodeRef)
{
object missingValue = Type.Missing;
object trueValue = true;
object falseValue = false;
try
{
// Create a new document if no document currently open
if (m_WordApplication.Selection == null)
{
m_WordApplication.Documents.Add(ref missingValue, ref missingValue, ref missingValue, ref missingValue);
}
object range = m_WordApplication.Selection.Range;
// WebDAV or CIFS?
string strFullPath = m_ServerDetails.getFullPath(relativePath, m_WordApplication.ActiveDocument.FullName, true);
string strExtn = Path.GetExtension(relativePath).ToLower();
string fileName = Path.GetFileName(relativePath);
string nativeExtn = ".doc" + (m_SupportsDocx ? "x" : "");
// If we're using WebDAV, then download file locally before inserting
if (strFullPath.StartsWith("http"))
{
// Need to unescape the the original path to get the filename
fileName = Path.GetFileName(Uri.UnescapeDataString(relativePath));
string strTempFile = Path.GetTempPath() + fileName;
if (File.Exists(strTempFile))
{
try
{
File.Delete(strTempFile);
}
catch (Exception)
{
strTempFile = Path.GetTempFileName();
}
}
WebClient fileReader = new WebClient();
string url = m_ServerDetails.WebClientURL + "download/direct/" + nodeRef.Replace(":/", "") + "/" + Path.GetFileName(relativePath);
fileReader.Headers.Add("Cookie: " + webBrowser.Document.Cookie);
fileReader.DownloadFile(url, strTempFile);
strFullPath = strTempFile;
}
if (".bmp .gif .jpg .jpeg .png".IndexOf(strExtn) != -1)
{
if (m_DebugMode)
{
MessageBox.Show("Image path=\n" + strFullPath, "Insert Image", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
m_WordApplication.ActiveDocument.InlineShapes.AddPicture(strFullPath, ref falseValue, ref trueValue, ref range);
}
else if (nativeExtn.IndexOf(strExtn) != -1)
{
if (m_DebugMode)
{
MessageBox.Show("Document path=\n" + strFullPath, "Insert Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
m_WordApplication.Selection.InsertFile(strFullPath, ref missingValue, ref trueValue, ref missingValue, ref missingValue);
}
else
{
object filename = strFullPath;
object iconFilename = Type.Missing;
object iconIndex = Type.Missing;
object iconLabel = fileName;
string defaultIcon = Util.DefaultIcon(strExtn);
if (defaultIcon.Contains(","))
{
string[] iconData = defaultIcon.Split(new char[] { ',' });
iconFilename = iconData[0];
iconIndex = iconData[1];
}
if (m_DebugMode)
{
MessageBox.Show("Object path=\n" + strFullPath, "Insert OLE Object", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
m_WordApplication.ActiveDocument.InlineShapes.AddOLEObject(ref missingValue, ref filename, ref falseValue, ref trueValue,
ref iconFilename, ref iconIndex, ref iconLabel, ref range);
}
}
catch (Exception e)
{
MessageBox.Show(Properties.Resources.UnableToInsert + ": " + e.Message, Properties.Resources.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public bool docHasExtension()
{
string name = m_WordApplication.ActiveDocument.Name;
return (name.EndsWith(".doc") || name.EndsWith(".docx"));
}
public void saveToAlfresco(string documentPath)
{
saveToAlfrescoAs(documentPath, m_WordApplication.ActiveDocument.Name);
}
public void saveToAlfrescoAs(string relativeDirectory, string documentName)
{
object missingValue = Type.Missing;
string currentDocPath = m_WordApplication.ActiveDocument.FullName;
// Ensure last separator is present
if (relativeDirectory == null)
{
relativeDirectory = "/";
}
else if (!relativeDirectory.EndsWith("/"))
{
relativeDirectory += "/";
}
// Have the correct file extension already?
if (!documentName.EndsWith(".doc"))
{
documentName += ".doc";
}
// Add the Word filename
relativeDirectory += documentName;
// CIFS or WebDAV path?
string savePath = m_ServerDetails.getFullPath(relativeDirectory, currentDocPath, false);
// Box into object - Word requirement
object file = savePath;
try
{
if (m_DebugMode)
{
MessageBox.Show("Save path=\n" + savePath, "Save Document", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
m_WordApplication.ActiveDocument.SaveAs(
ref file, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue, ref missingValue);
this.OnDocumentChanged();
}
catch (Exception e)
{
MessageBox.Show(Properties.Resources.UnableToSave + ": " + e.Message, Properties.Resources.MessageBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void showSettingsPanel()
{
PanelMode = PanelModes.Configuration;
}
private enum PanelModes
{
WebBrowser,
Configuration
}
private PanelModes PanelMode
{
set
{
pnlWebBrowser.Visible = (value == PanelModes.WebBrowser);
pnlConfiguration.Visible = (value == PanelModes.Configuration);
}
}
#region Settings Management
/// <summary>
/// Settings Management
/// </summary>
private bool m_SettingsChanged = false;
private string m_WebDAVURL = "";
private void LoadSettings()
{
m_ServerDetails.LoadFromRegistry();
txtWebClientURL.Text = m_ServerDetails.WebClientURL;
m_WebDAVURL = m_ServerDetails.WebDAVURL;
txtCIFSServer.Text = m_ServerDetails.CIFSServer;
chkUseCIFS.Checked = (m_ServerDetails.CIFSServer != "");
chkUseCIFS_CheckedChanged(null, null);
if (m_ServerDetails.Username != "")
{
txtUsername.Text = m_ServerDetails.Username;
txtPassword.Text = m_ServerDetails.Password;
chkRememberAuth.Checked = true;
}
else
{
txtUsername.Text = "";
txtPassword.Text = "";
chkRememberAuth.Checked = false;
}
m_SettingsChanged = false;
}
private void AlfrescoPane_Load(object sender, EventArgs e)
{
m_ServerDetails.loadWindowPosition(this);
}
private void AlfrescoPane_FormClosing(object sender, FormClosingEventArgs e)
{
m_ServerDetails.saveWindowPosition(this);
// Override the close box
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
m_ManuallyHidden = true;
this.Hide();
}
}
private void btnDetailsOK_Click(object sender, EventArgs e)
{
m_DebugMode = (Control.ModifierKeys == (Keys.Control | Keys.Shift));
if (m_SettingsChanged)
{
m_ServerDetails.WebClientURL = txtWebClientURL.Text;
m_ServerDetails.WebDAVURL = m_WebDAVURL;
m_ServerDetails.CIFSServer = chkUseCIFS.Checked ? txtCIFSServer.Text : "";
if (chkRememberAuth.Checked)
{
m_ServerDetails.Username = txtUsername.Text;
m_ServerDetails.Password = txtPassword.Text;
}
else
{
m_ServerDetails.Username = "";
m_ServerDetails.Password = "";
}
m_ServerDetails.SaveToRegistry();
m_ClearSession = true;
}
this.OnDocumentChanged();
}
private void btnDetailsCancel_Click(object sender, EventArgs e)
{
LoadSettings();
}
private void txtWebClientURL_TextChanged(object sender, EventArgs e)
{
m_SettingsChanged = true;
// Build WebDAV URL
try
{
string strWebDAV = txtWebClientURL.Text;
if (!strWebDAV.EndsWith("/"))
{
strWebDAV += "/";
}
m_WebDAVURL = strWebDAV + "webdav/";
}
catch
{
}
// Build autocomplete string for the CIFS textbox
try
{
Uri clientUri = new Uri(txtWebClientURL.Text);
string strCIFS = "\\\\" + clientUri.Host + "a\\alfresco\\";
txtCIFSServer.AutoCompleteCustomSource.Clear();
txtCIFSServer.AutoCompleteCustomSource.Add(strCIFS);
}
catch
{
}
}
private void chkUseCIFS_CheckedChanged(object sender, EventArgs e)
{
m_SettingsChanged = true;
txtCIFSServer.Enabled = chkUseCIFS.Checked;
}
private void txtCIFSServer_TextChanged(object sender, EventArgs e)
{
m_SettingsChanged = true;
}
private void txtUsername_TextChanged(object sender, EventArgs e)
{
m_SettingsChanged = true;
}
private void txtPassword_TextChanged(object sender, EventArgs e)
{
m_SettingsChanged = true;
}
private void lnkBackToBrowser_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
PanelMode = PanelModes.WebBrowser;
}
private void lnkShowConfiguration_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
PanelMode = PanelModes.Configuration;
}
#endregion
private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (webBrowser.Url.ToString().EndsWith("login.jsp"))
{
m_ServerDetails.clearAuthenticationTicket();
bool bLastPageOK = m_LastWebPageSuccessful;
m_LastWebPageSuccessful = false;
if (bLastPageOK)
{
showHome(true);
}
}
else
{
if (!m_LastWebPageSuccessful)
{
m_LastWebPageSuccessful = true;
this.OnDocumentChanged();
}
}
}
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * 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 Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class ParameterDeclaration : Node, INodeWithAttributes
{
protected string _name;
protected TypeReference _type;
protected ParameterModifiers _modifiers;
protected AttributeCollection _attributes;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ParameterDeclaration CloneNode()
{
return (ParameterDeclaration)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public ParameterDeclaration CleanClone()
{
return (ParameterDeclaration)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.ParameterDeclaration; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnParameterDeclaration(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( ParameterDeclaration)node;
if (_name != other._name) return NoMatch("ParameterDeclaration._name");
if (!Node.Matches(_type, other._type)) return NoMatch("ParameterDeclaration._type");
if (_modifiers != other._modifiers) return NoMatch("ParameterDeclaration._modifiers");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("ParameterDeclaration._attributes");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_type == existing)
{
this.Type = (TypeReference)newNode;
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
ParameterDeclaration clone = (ParameterDeclaration)FormatterServices.GetUninitializedObject(typeof(ParameterDeclaration));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._name = _name;
if (null != _type)
{
clone._type = _type.Clone() as TypeReference;
clone._type.InitializeParent(clone);
}
clone._modifiers = _modifiers;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _type)
{
_type.ClearTypeSystemBindings();
}
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlAttribute]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public string Name
{
get { return _name; }
set { _name = value; }
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference Type
{
get { return _type; }
set
{
if (_type != value)
{
_type = value;
if (null != _type)
{
_type.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlAttribute,
System.ComponentModel.DefaultValue(ParameterModifiers.None)]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ParameterModifiers Modifiers
{
get { return _modifiers; }
set { _modifiers = value; }
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Attribute))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public AttributeCollection Attributes
{
get { return _attributes ?? (_attributes = new AttributeCollection(this)); }
set
{
if (_attributes != value)
{
_attributes = value;
if (null != _attributes)
{
_attributes.InitializeParent(this);
}
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
namespace OrchardCore.ResourceManagement
{
public class RequireSettings
{
private Dictionary<string, string> _attributes;
public string BasePath { get; set; }
public string Type { get; set; }
public string Name { get; set; }
public string Culture { get; set; }
public bool DebugMode { get; set; }
public bool CdnMode { get; set; }
public string CdnBaseUrl { get; set; }
public ResourceLocation Location { get; set; }
public string Condition { get; set; }
public string Version { get; set; }
public bool? AppendVersion { get; set; }
public List<string> Dependencies { get; set; }
public Action<ResourceDefinition> InlineDefinition { get; set; }
public Dictionary<string, string> Attributes
{
get => _attributes ?? (_attributes = new Dictionary<string, string>());
private set { _attributes = value; }
}
public RequireSettings()
{
}
public RequireSettings(ResourceManagementOptions options)
{
CdnMode = options.UseCdn;
DebugMode = options.DebugMode;
Culture = options.Culture;
CdnBaseUrl = options.CdnBaseUrl;
AppendVersion = options.AppendVersion;
}
public bool HasAttributes
{
get { return _attributes != null && _attributes.Any(a => a.Value != null); }
}
/// <summary>
/// The resource will be displayed in the head of the page
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings AtHead()
{
return AtLocation(ResourceLocation.Head);
}
/// <summary>
/// The resource will be displayed at the foot of the page
/// </summary>
/// <returns></returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings AtFoot()
{
return AtLocation(ResourceLocation.Foot);
}
/// <summary>
/// The resource will be displayed at the specified location
/// </summary>
/// <param name="location">The location where the resource should be displayed</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings AtLocation(ResourceLocation location)
{
// if head is specified it takes precedence since it's safer than foot
Location = (ResourceLocation)Math.Max((int)Location, (int)location);
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseCulture(string cultureName)
{
if (!String.IsNullOrEmpty(cultureName))
{
Culture = cultureName;
}
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseDebugMode()
{
return UseDebugMode(true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseDebugMode(bool debugMode)
{
DebugMode |= debugMode;
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseCdn()
{
return UseCdn(true);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseCdn(bool cdn)
{
CdnMode |= cdn;
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseCdnBaseUrl(string cdnBaseUrl)
{
CdnBaseUrl = cdnBaseUrl;
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings WithBasePath(string basePath)
{
BasePath = basePath;
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseCondition(string condition)
{
Condition = Condition ?? condition;
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings UseVersion(string version)
{
if (!String.IsNullOrEmpty(version))
{
Version = version;
}
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings ShouldAppendVersion(bool? appendVersion)
{
AppendVersion = appendVersion;
return this;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RequireSettings SetDependencies(params string[] dependencies)
{
if (Dependencies == null)
{
Dependencies = new List<string>();
}
Dependencies.AddRange(dependencies);
return this;
}
public RequireSettings Define(Action<ResourceDefinition> resourceDefinition)
{
if (resourceDefinition != null)
{
var previous = InlineDefinition;
if (previous != null)
{
InlineDefinition = r =>
{
previous(r);
resourceDefinition(r);
};
}
else
{
InlineDefinition = resourceDefinition;
}
}
return this;
}
public RequireSettings SetAttribute(string name, string value)
{
if (_attributes == null)
{
_attributes = new Dictionary<string, string>();
}
_attributes[name] = value;
return this;
}
private Dictionary<string, string> MergeAttributes(RequireSettings other)
{
// efficiently merge the two dictionaries, taking into account that one or both may not exist
// and that attributes in 'other' should overridde attributes in this, even if the value is null.
if (_attributes == null)
{
return other._attributes == null ? null : new Dictionary<string, string>(other._attributes);
}
if (other._attributes == null)
{
return new Dictionary<string, string>(_attributes);
}
var mergedAttributes = new Dictionary<string, string>(_attributes);
foreach (var pair in other._attributes)
{
mergedAttributes[pair.Key] = pair.Value;
}
return mergedAttributes;
}
public RequireSettings Combine(RequireSettings other)
{
var settings = (new RequireSettings
{
Name = Name,
Type = Type,
}).AtLocation(Location).AtLocation(other.Location)
.WithBasePath(BasePath).WithBasePath(other.BasePath)
.UseCdn(CdnMode).UseCdn(other.CdnMode)
.UseCdnBaseUrl(CdnBaseUrl).UseCdnBaseUrl(other.CdnBaseUrl)
.UseDebugMode(DebugMode).UseDebugMode(other.DebugMode)
.UseCulture(Culture).UseCulture(other.Culture)
.UseCondition(Condition).UseCondition(other.Condition)
.UseVersion(Version).UseVersion(other.Version)
.ShouldAppendVersion(AppendVersion).ShouldAppendVersion(other.AppendVersion)
.Define(InlineDefinition).Define(other.InlineDefinition);
settings._attributes = MergeAttributes(other);
return settings;
}
}
}
| |
#if WITH_REPLICATION
namespace Volante.Impl
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Volante;
public class ReplicationSlaveDatabaseImpl : DatabaseImpl, ReplicationSlaveDatabase
{
public ReplicationSlaveDatabaseImpl(int port)
{
this.port = port;
}
public override void Open(IFile file, int cacheSizeInBytes)
{
acceptor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
acceptor.Bind(new IPEndPoint(IPAddress.Any, port));
acceptor.Listen(ListenQueueSize);
if (file.Length > 0)
{
byte[] rootPage = new byte[Page.pageSize];
try
{
file.Read(0, rootPage);
prevIndex = rootPage[DB_HDR_CURR_INDEX_OFFSET];
initialized = rootPage[DB_HDR_INITIALIZED_OFFSET] != 0;
}
catch (DatabaseException)
{
initialized = false;
prevIndex = -1;
}
}
else
{
prevIndex = -1;
initialized = false;
}
this.file = file;
lck = new PersistentResource();
init = new object();
done = new object();
commit = new object();
listening = true;
connect();
pool = new PagePool(cacheSizeInBytes / Page.pageSize);
pool.open(file);
thread = new Thread(new ThreadStart(run));
thread.Name = "ReplicationSlaveStorageImpl";
thread.Start();
WaitInitializationCompletion();
base.Open(file, cacheSizeInBytes);
}
/// <summary>
/// Check if socket is connected to the master host
/// @return <code>true</code> if connection between slave and master is sucessfully established
/// </summary>
public bool IsConnected()
{
return socket != null;
}
public override void BeginThreadTransaction(TransactionMode mode)
{
if (mode != TransactionMode.ReplicationSlave)
{
throw new ArgumentException("Illegal transaction mode");
}
lck.SharedLock();
Page pg = pool.getPage(0);
header.unpack(pg.data);
pool.unfix(pg);
currIndex = 1 - header.curr;
currIndexSize = header.root[1 - currIndex].indexUsed;
committedIndexSize = currIndexSize;
usedSize = header.root[currIndex].size;
}
public override void EndThreadTransaction(int maxDelay)
{
lck.Unlock();
}
protected void WaitInitializationCompletion()
{
lock (init)
{
while (!initialized)
{
Monitor.Wait(init);
}
}
}
/// <summary>
/// Wait until database is modified by master
/// This method blocks current thread until master node commits trasanction and
/// this transanction is completely delivered to this slave node
/// </summary>
public void WaitForModification()
{
lock (commit)
{
if (socket != null)
{
Monitor.Wait(commit);
}
}
}
const int DB_HDR_CURR_INDEX_OFFSET = 0;
const int DB_HDR_DIRTY_OFFSET = 1;
const int DB_HDR_INITIALIZED_OFFSET = 2;
const int PAGE_DATA_OFFSET = 8;
public static int ListenQueueSize = 10;
public static int LingerTime = 10; // linger parameter for the socket
private void connect()
{
try
{
socket = acceptor.Accept();
}
catch (SocketException)
{
socket = null;
}
}
/// <summary>
/// When overriden by base class this method perfroms socket error handling
/// @return <code>true</code> if host should be reconnected and attempt to send data to it should be
/// repeated, <code>false</code> if no more attmpts to communicate with this host should be performed
/// </summary>
public virtual bool HandleError()
{
return (Listener != null) ? Listener.ReplicationError(null) : false;
}
public void run()
{
byte[] buf = new byte[Page.pageSize + PAGE_DATA_OFFSET];
while (listening)
{
int offs = 0;
do
{
int rc;
try
{
rc = socket.Receive(buf, offs, buf.Length - offs, SocketFlags.None);
}
catch (SocketException)
{
rc = -1;
}
lock (done)
{
if (!listening)
{
return;
}
}
if (rc < 0)
{
if (HandleError())
{
connect();
}
else
{
return;
}
}
else
{
offs += rc;
}
} while (offs < buf.Length);
long pos = Bytes.unpack8(buf, 0);
bool transactionCommit = false;
if (pos == 0)
{
if (replicationAck)
{
try
{
socket.Send(buf, 0, 1, SocketFlags.None);
}
catch (SocketException)
{
HandleError();
}
}
if (buf[PAGE_DATA_OFFSET + DB_HDR_CURR_INDEX_OFFSET] != prevIndex)
{
prevIndex = buf[PAGE_DATA_OFFSET + DB_HDR_CURR_INDEX_OFFSET];
lck.ExclusiveLock();
transactionCommit = true;
}
}
else if (pos < 0)
{
lock (commit)
{
hangup();
Monitor.PulseAll(commit);
}
return;
}
Page pg = pool.putPage(pos);
Array.Copy(buf, PAGE_DATA_OFFSET, pg.data, 0, Page.pageSize);
pool.unfix(pg);
if (pos == 0)
{
if (!initialized && buf[PAGE_DATA_OFFSET + DB_HDR_INITIALIZED_OFFSET] != 0)
{
lock (init)
{
initialized = true;
Monitor.Pulse(init);
}
}
if (transactionCommit)
{
lck.Unlock();
lock (commit)
{
Monitor.PulseAll(commit);
}
pool.flush();
}
}
}
}
public override void Close()
{
lock (done)
{
listening = false;
}
thread.Interrupt();
thread.Join();
hangup();
pool.flush();
base.Close();
}
private void hangup()
{
if (socket != null)
{
try
{
socket.Close();
}
catch (SocketException) { }
socket = null;
}
}
protected override bool isDirty()
{
return false;
}
protected Socket socket;
protected int port;
protected IFile file;
protected bool initialized;
protected bool listening;
protected object init;
protected object done;
protected object commit;
protected int prevIndex;
protected IResource lck;
protected Socket acceptor;
protected Thread thread;
}
}
#endif
| |
// * **************************************************************************
// * Copyright (c) Clinton Sheppard <sheppard@cs.unm.edu>
// *
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// *
// * source repository: https://github.com/handcraftsman/Afluistic
// * **************************************************************************
using System;
using System.IO;
using System.Linq;
using Afluistic.Extensions;
using Afluistic.Tests.TestObjects;
using FluentAssert;
using NUnit.Framework;
namespace Afluistic.Tests.Extensions
{
public class StringExtensionsTests
{
public class When_asked_to_convert_a_message_text_to_a_regex
{
[TestFixture]
public class Given_a_message_text_containing_a_start_multiple_match_character_special_character
{
[Test]
public void Should_escape_the_character_with_a_backslash()
{
const string messageText = "the [0] is round";
var regexText = messageText.MessageTextToRegex();
regexText.ShouldBeEqualTo(@"the \[0] is round");
}
}
[TestFixture]
public class Given_a_message_text_containing_multiple_string_format_placeholders
{
[Test]
public void Should_convert_the_placeholders_to_a_regex_match()
{
const string messageText = "the {0} is {1}";
var regexText = messageText.MessageTextToRegex();
regexText.ShouldBeEqualTo("the .* is .*");
}
}
[TestFixture]
public class Given_a_message_text_containing_one_string_format_placeholder
{
[Test]
public void Should_convert_the_placeholder_to_a_regex_match()
{
const string messageText = "the {0} is round";
var regexText = messageText.MessageTextToRegex();
regexText.ShouldBeEqualTo("the .* is round");
}
}
}
public class When_asked_to_convert_a_path_to_a_statement_path
{
[TestFixture]
public class Given_a_path_that_cannot_be_converted_to_an_absolute_path
{
[Test]
public void Should_return_an_error_notification()
{
const string path = "?";
var result = path.ToStatementPath();
result.HasErrors.ShouldBeTrue();
}
}
[TestFixture]
public class Given_a_path_that_resolves_to_a_directory
{
[Test]
public void Should_return_a_path_created_by_combining_the_directory_with_the_default_file_name()
{
const string path = @".";
var result = path.ToStatementPath();
result.HasErrors.ShouldBeFalse();
result.Item.ShouldBeEqualTo(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, Constants.DefaultStatementFileName)));
}
}
[TestFixture]
public class Given_a_path_that_resolves_to_a_file
{
[Test]
public void Should_return_the_absolute_path_to_the_file()
{
const string path = @".\Afluistic.pdb";
var result = path.ToStatementPath();
result.HasErrors.ShouldBeFalse();
result.Item.ShouldBeEqualTo(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, path)));
}
}
}
public class When_asked_to_convert_a_path_to_an_absolute_path
{
[TestFixture]
public class Given_a_dot_dot_path
{
[Test]
public void Should_return_the_current_directory_combined_with_the_input()
{
const string path = @"..\foo";
var absolutePath = path.ToAbsolutePath();
absolutePath.Item.ShouldBeEqualTo(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, path)));
}
}
[TestFixture]
public class Given_a_path_containing_a_drive_designation
{
[Test]
public void Should_return_the_input()
{
const string path = @"c:\foo";
var absolutePath = path.ToAbsolutePath();
absolutePath.Item.ShouldBeEqualTo(path);
}
}
[TestFixture]
public class Given_dot
{
[Test]
public void Should_return_the_current_directory()
{
const string path = ".";
var absolutePath = path.ToAbsolutePath();
absolutePath.Item.ShouldBeEqualTo(Environment.CurrentDirectory);
}
}
[TestFixture]
public class Given_dot_slash_foo
{
[Test]
public void Should_return_the_current_directory_combined_with_the_input()
{
const string path = @".\foo";
var absolutePath = path.ToAbsolutePath();
absolutePath.Item.ShouldBeEqualTo(Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, path)));
}
}
}
public class When_asked_to_pluralize_a_string
{
[TestFixture]
public class Given_an_input_that_does_not_end_with__y_or_s
{
[Test]
public void Should_return_the_input_with_suffix__s()
{
const string input = "cat";
var result = input.Pluralize();
result.ShouldBeEqualTo("cats");
}
}
[TestFixture]
public class Given_an_input_that_ends_with__s
{
[Test]
public void Should_return_the_input_with_suffix__es()
{
const string input = "boss";
var result = input.Pluralize();
result.ShouldBeEqualTo("bosses");
}
}
[TestFixture]
public class Given_an_input_that_ends_with__y
{
[Test]
public void Should_return_the_input_with_the_trailing_y_replaced_with__ies()
{
const string input = "category";
var result = input.Pluralize();
result.ShouldBeEqualTo("categories");
}
}
}
public class When_asked_to_replace_Type_references_with_UI_descriptions
{
[TestFixture]
public class Given_a_string_with_a_Type_reference_at_the_beginning
{
[Test]
public void Should_return_the_string_with_the_Type_reference_replaced_by_its_singular_UI_description()
{
var input = "$" + typeof(ObjectWithDescription).Name + " world";
var result = input.ReplaceTypeReferencesWithUIDescriptions(false);
result.ShouldBeEqualTo(typeof(ObjectWithDescription).GetSingularUIDescription() + " world");
}
}
[TestFixture]
public class Given_a_string_with_a_Type_reference_at_the_end
{
[Test]
public void Should_return_the_string_with_the_Type_reference_replaced_by_its_singular_UI_description()
{
var input = "Hello $" + typeof(ObjectWithDescription).Name;
var result = input.ReplaceTypeReferencesWithUIDescriptions(false);
result.ShouldBeEqualTo("Hello " + typeof(ObjectWithDescription).GetSingularUIDescription());
}
}
[TestFixture]
public class Given_a_string_with_a_Type_references_marker_not_followed_by_a_Type_name
{
[Test]
public void Should_return_the_original_string()
{
var input = "Hello $world";
var result = input.ReplaceTypeReferencesWithUIDescriptions(false);
result.ShouldBeEqualTo("Hello $world");
}
}
[TestFixture]
public class Given_a_string_with_multiple_Type_references
{
[Test]
public void Should_return_the_string_with_all_Type_references_replaced_by_their_singular_UI_descriptions()
{
var input = "Hello $" + typeof(ObjectWithDescription).Name + " world $" + typeof(TestObject).Name + " again";
var result = input.ReplaceTypeReferencesWithUIDescriptions(false);
result.ShouldBeEqualTo("Hello " + typeof(ObjectWithDescription).GetSingularUIDescription() + " world " + typeof(TestObject).GetSingularUIDescription() + " again");
}
}
[TestFixture]
public class Given_a_string_with_one_Type_reference
{
[Test]
public void Should_return_the_string_with_the_Type_reference_replaced_by_its_singular_UI_description()
{
var input = "Hello $" + typeof(ObjectWithDescription).Name + " world";
var result = input.ReplaceTypeReferencesWithUIDescriptions(false);
result.ShouldBeEqualTo("Hello " + typeof(ObjectWithDescription).GetSingularUIDescription() + " world");
}
}
[TestFixture]
public class Given_a_string_without_Type_references
{
[Test]
public void Should_return_the_original_string()
{
const string input = "Hello world";
var result = input.ReplaceTypeReferencesWithUIDescriptions(false);
result.ShouldBeEqualTo(input);
}
}
}
public class When_asked_to_split_on_transition_to_capital_letter
{
[TestFixture]
public class Given__AnotherUI
{
[Test]
public void Should_return_the_words__Another_UI()
{
const string input = "AnotherUI";
var result = input.SplitOnTransitionToCapitalLetter();
result.Length.ShouldBeEqualTo(2);
result.First().ShouldBeEqualTo("Another");
result.Last().ShouldBeEqualTo("UI");
}
}
[TestFixture]
public class Given__HelloWorld
{
[Test]
public void Should_return_the_words__Hello_World()
{
const string input = "HelloWorld";
var result = input.SplitOnTransitionToCapitalLetter();
result.Length.ShouldBeEqualTo(2);
result.First().ShouldBeEqualTo("Hello");
result.Last().ShouldBeEqualTo("World");
}
}
[TestFixture]
public class Given__Init
{
[Test]
public void Should_return_the_word__Init()
{
const string input = "Init";
var result = input.SplitOnTransitionToCapitalLetter();
result.Length.ShouldBeEqualTo(1);
result.First().ShouldBeEqualTo(input);
}
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Bot.Connector
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
/// <summary>
/// Conversations operations.
/// </summary>
public partial interface IConversations
{
/// <summary>
/// CreateConversation
/// </summary>
/// Create a new Conversation.
///
/// POST to this method with a
/// * Bot being the bot creating the conversation
/// * IsGroup set to true if this is not a direct message (default is
/// false)
/// * Members array containing the members you want to have be in the
/// conversation.
///
/// The return value is a ResourceResponse which contains a
/// conversation id which is suitable for use
/// in the message payload and REST API uris.
///
/// Most channels only support the semantics of bots initiating a
/// direct message conversation. An example of how to do that would
/// be:
///
/// ```
/// var resource = await
/// connector.conversations.CreateConversation(new ConversationParameters(){
/// Bot = bot, members = new ChannelAccount[] { new
/// ChannelAccount("user1") } );
/// await connect.Conversations.SendToConversationAsync(resource.Id,
/// new Activity() ... ) ;
///
/// ```
/// <param name='parameters'>
/// Parameters to create the conversation from
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> CreateConversationWithHttpMessagesAsync(ConversationParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// SendToConversation
/// </summary>
/// This method allows you to send an activity to the end of a
/// conversation.
///
/// This is slightly different from ReplyToActivity().
/// * SendToConverstion(conversationId) - will append the activity to
/// the end of the conversation according to the timestamp or
/// semantics of the channel.
/// * ReplyToActivity(conversationId,ActivityId) - adds the activity
/// as a reply to another activity, if the channel supports it. If
/// the channel does not support nested replies, ReplyToActivity
/// falls back to SendToConversation.
///
/// Use ReplyToActivity when replying to a specific activity in the
/// conversation.
///
/// Use SendToConversation in all other cases.
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> SendToConversationWithHttpMessagesAsync(Activity activity, string conversationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// UpdateActivity
/// </summary>
/// Edit an existing activity.
///
/// Some channels allow you to edit an existing activity to reflect
/// the new state of a bot conversation.
///
/// For example, you can remove buttons after someone has clicked
/// "Approve" button.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// activityId to update
/// </param>
/// <param name='activity'>
/// replacement Activity
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> UpdateActivityWithHttpMessagesAsync(string conversationId, string activityId, Activity activity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// ReplyToActivity
/// </summary>
/// This method allows you to reply to an activity.
///
/// This is slightly different from SendToConversation().
/// * SendToConverstion(conversationId) - will append the activity to
/// the end of the conversation according to the timestamp or
/// semantics of the channel.
/// * ReplyToActivity(conversationId,ActivityId) - adds the activity
/// as a reply to another activity, if the channel supports it. If
/// the channel does not support nested replies, ReplyToActivity
/// falls back to SendToConversation.
///
/// Use ReplyToActivity when replying to a specific activity in the
/// conversation.
///
/// Use SendToConversation in all other cases.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// activityId the reply is to (OPTIONAL)
/// </param>
/// <param name='activity'>
/// Activity to send
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> ReplyToActivityWithHttpMessagesAsync(string conversationId, string activityId, Activity activity, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// DeleteActivity
/// </summary>
/// Delete an existing activity.
///
/// Some channels allow you to delete an existing activity, and if
/// successful this method will remove the specified activity.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// activityId to delete
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<ErrorResponse>> DeleteActivityWithHttpMessagesAsync(string conversationId, string activityId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// GetConversationMembers
/// </summary>
/// Enumerate the members of a converstion.
///
/// This REST API takes a ConversationId and returns an array of
/// ChannelAccount objects representing the members of the
/// conversation.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> GetConversationMembersWithHttpMessagesAsync(string conversationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// GetActivityMembers
/// </summary>
/// Enumerate the members of an activity.
///
/// This REST API takes a ConversationId and a ActivityId, returning
/// an array of ChannelAccount objects representing the members of
/// the particular activity in the conversation.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='activityId'>
/// Activity ID
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> GetActivityMembersWithHttpMessagesAsync(string conversationId, string activityId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// UploadAttachment
/// </summary>
/// Upload an attachment directly into a channel's blob storage.
///
/// This is useful because it allows you to store data in a compliant
/// store when dealing with enterprises.
///
/// The response is a ResourceResponse which contains an AttachmentId
/// which is suitable for using with the attachments API.
/// <param name='conversationId'>
/// Conversation ID
/// </param>
/// <param name='attachmentUpload'>
/// Attachment data
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<object>> UploadAttachmentWithHttpMessagesAsync(string conversationId, AttachmentData attachmentUpload, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// OutputWindow.cs
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace TvdbLib.SharpZipLib.Zip.Compression.Streams
{
/// <summary>
/// Contains the output from the Inflation process.
/// We need to have a window so that we can refer backwards into the output stream
/// to repeat stuff.<br/>
/// Author of the original java version : John Leuner
/// </summary>
public class OutputWindow
{
#region Constants
const int WindowSize = 1 << 15;
const int WindowMask = WindowSize - 1;
#endregion
#region Instance Fields
byte[] window = new byte[WindowSize]; //The window is 2^15 bytes
int windowEnd;
int windowFilled;
#endregion
/// <summary>
/// Write a byte to this output window
/// </summary>
/// <param name="value">value to write</param>
/// <exception cref="InvalidOperationException">
/// if window is full
/// </exception>
public void Write(int value)
{
if (windowFilled++ == WindowSize) {
throw new InvalidOperationException("Window full");
}
window[windowEnd++] = (byte) value;
windowEnd &= WindowMask;
}
private void SlowRepeat(int repStart, int length, int distance)
{
while (length-- > 0) {
window[windowEnd++] = window[repStart++];
windowEnd &= WindowMask;
repStart &= WindowMask;
}
}
/// <summary>
/// Append a byte pattern already in the window itself
/// </summary>
/// <param name="length">length of pattern to copy</param>
/// <param name="distance">distance from end of window pattern occurs</param>
/// <exception cref="InvalidOperationException">
/// If the repeated data overflows the window
/// </exception>
public void Repeat(int length, int distance)
{
if ((windowFilled += length) > WindowSize) {
throw new InvalidOperationException("Window full");
}
int repStart = (windowEnd - distance) & WindowMask;
int border = WindowSize - length;
if ( (repStart <= border) && (windowEnd < border) ) {
if (length <= distance) {
System.Array.Copy(window, repStart, window, windowEnd, length);
windowEnd += length;
} else {
// We have to copy manually, since the repeat pattern overlaps.
while (length-- > 0) {
window[windowEnd++] = window[repStart++];
}
}
} else {
SlowRepeat(repStart, length, distance);
}
}
/// <summary>
/// Copy from input manipulator to internal window
/// </summary>
/// <param name="input">source of data</param>
/// <param name="length">length of data to copy</param>
/// <returns>the number of bytes copied</returns>
public int CopyStored(StreamManipulator input, int length)
{
length = Math.Min(Math.Min(length, WindowSize - windowFilled), input.AvailableBytes);
int copied;
int tailLen = WindowSize - windowEnd;
if (length > tailLen) {
copied = input.CopyBytes(window, windowEnd, tailLen);
if (copied == tailLen) {
copied += input.CopyBytes(window, 0, length - tailLen);
}
} else {
copied = input.CopyBytes(window, windowEnd, length);
}
windowEnd = (windowEnd + copied) & WindowMask;
windowFilled += copied;
return copied;
}
/// <summary>
/// Copy dictionary to window
/// </summary>
/// <param name="dictionary">source dictionary</param>
/// <param name="offset">offset of start in source dictionary</param>
/// <param name="length">length of dictionary</param>
/// <exception cref="InvalidOperationException">
/// If window isnt empty
/// </exception>
public void CopyDict(byte[] dictionary, int offset, int length)
{
if ( dictionary == null ) {
throw new ArgumentNullException("dictionary");
}
if (windowFilled > 0) {
throw new InvalidOperationException();
}
if (length > WindowSize) {
offset += length - WindowSize;
length = WindowSize;
}
System.Array.Copy(dictionary, offset, window, 0, length);
windowEnd = length & WindowMask;
}
/// <summary>
/// Get remaining unfilled space in window
/// </summary>
/// <returns>Number of bytes left in window</returns>
public int GetFreeSpace()
{
return WindowSize - windowFilled;
}
/// <summary>
/// Get bytes available for output in window
/// </summary>
/// <returns>Number of bytes filled</returns>
public int GetAvailable()
{
return windowFilled;
}
/// <summary>
/// Copy contents of window to output
/// </summary>
/// <param name="output">buffer to copy to</param>
/// <param name="offset">offset to start at</param>
/// <param name="len">number of bytes to count</param>
/// <returns>The number of bytes copied</returns>
/// <exception cref="InvalidOperationException">
/// If a window underflow occurs
/// </exception>
public int CopyOutput(byte[] output, int offset, int len)
{
int copyEnd = windowEnd;
if (len > windowFilled) {
len = windowFilled;
} else {
copyEnd = (windowEnd - windowFilled + len) & WindowMask;
}
int copied = len;
int tailLen = len - copyEnd;
if (tailLen > 0) {
System.Array.Copy(window, WindowSize - tailLen, output, offset, tailLen);
offset += tailLen;
len = copyEnd;
}
System.Array.Copy(window, copyEnd - len, output, offset, len);
windowFilled -= copied;
if (windowFilled < 0) {
throw new InvalidOperationException();
}
return copied;
}
/// <summary>
/// Reset by clearing window so <see cref="GetAvailable">GetAvailable</see> returns 0
/// </summary>
public void Reset()
{
windowFilled = windowEnd = 0;
}
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G09_Region_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G09_Region_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G08_Region"/> collection.
/// </remarks>
[Serializable]
public partial class G09_Region_ReChild : BusinessBase<G09_Region_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Region_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Cities Child Name");
/// <summary>
/// Gets or sets the Cities Child Name.
/// </summary>
/// <value>The Cities Child Name.</value>
public string Region_Child_Name
{
get { return GetProperty(Region_Child_NameProperty); }
set { SetProperty(Region_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G09_Region_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G09_Region_ReChild"/> object.</returns>
internal static G09_Region_ReChild NewG09_Region_ReChild()
{
return DataPortal.CreateChild<G09_Region_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G09_Region_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="region_ID2">The Region_ID2 parameter of the G09_Region_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G09_Region_ReChild"/> object.</returns>
internal static G09_Region_ReChild GetG09_Region_ReChild(int region_ID2)
{
return DataPortal.FetchChild<G09_Region_ReChild>(region_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G09_Region_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G09_Region_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G09_Region_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G09_Region_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="region_ID2">The Region ID2.</param>
protected void Child_Fetch(int region_ID2)
{
var args = new DataPortalHookArgs(region_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
var data = dal.Fetch(region_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G09_Region_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Region_Child_NameProperty, dr.GetString("Region_Child_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G09_Region_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Insert(
parent.Region_ID,
Region_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G09_Region_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G08_Region parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Update(
parent.Region_ID,
Region_Child_Name
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="G09_Region_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G08_Region parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IG09_Region_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.Region_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using Microsoft.Scripting;
using MSAst = System.Linq.Expressions;
using System.Linq.Expressions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
namespace IronPython.Compiler.Ast {
using Ast = MSAst.Expression;
using AstUtils = Microsoft.Scripting.Ast.Utils;
public abstract class Node : MSAst.Expression {
private ScopeStatement _parent;
private IndexSpan _span;
internal static readonly MSAst.BlockExpression EmptyBlock = Ast.Block(AstUtils.Empty());
internal static readonly MSAst.Expression[] EmptyExpression = new MSAst.Expression[0];
internal static MSAst.ParameterExpression FunctionStackVariable = Ast.Variable(typeof(List<FunctionStack>), "$funcStack");
internal static readonly MSAst.LabelTarget GeneratorLabel = Ast.Label(typeof(object), "$generatorLabel");
private static MSAst.ParameterExpression _lineNumberUpdated = Ast.Variable(typeof(bool), "$lineUpdated");
private static readonly MSAst.ParameterExpression _lineNoVar = Ast.Parameter(typeof(int), "$lineNo");
protected Node() {
}
#region Public API
public ScopeStatement Parent {
get { return _parent; }
set { _parent = value; }
}
public void SetLoc(PythonAst globalParent, int start, int end) {
_span = new IndexSpan(start, end > start ? end - start : start);
_parent = globalParent;
}
public void SetLoc(PythonAst globalParent, IndexSpan span) {
_span = span;
_parent = globalParent;
}
public IndexSpan IndexSpan {
get {
return _span;
}
set {
_span = value;
}
}
public SourceLocation Start {
get {
return GlobalParent.IndexToLocation(StartIndex);
}
}
public SourceLocation End {
get {
return GlobalParent.IndexToLocation(EndIndex);
}
}
public int EndIndex {
get {
return _span.End;
}
set {
_span = new IndexSpan(_span.Start, value - _span.Start);
}
}
public int StartIndex {
get {
return _span.Start;
}
set {
_span = new IndexSpan(value, 0);
}
}
internal SourceLocation IndexToLocation(int index) {
if (index == -1) {
return SourceLocation.Invalid;
}
var locs = GlobalParent._lineLocations;
int match = Array.BinarySearch(locs, index);
if (match < 0) {
// If our index = -1, it means we're on the first line.
if (match == -1) {
return new SourceLocation(index, 1, index + 1);
}
// If we couldn't find an exact match for this line number, get the nearest
// matching line number less than this one
match = ~match - 1;
}
return new SourceLocation(index, match + 2, index - locs[match] + 1);
}
public SourceSpan Span {
get {
return new SourceSpan(Start, End);
}
}
public abstract void Walk(PythonWalker walker);
public virtual string NodeName {
get {
return GetType().Name;
}
}
#endregion
#region Base Class Overrides
/// <summary>
/// Returns true if the node can throw, false otherwise. Used to determine
/// whether or not we need to update the current dynamic stack info.
/// </summary>
internal virtual bool CanThrow {
get {
return true;
}
}
public override bool CanReduce {
get {
return true;
}
}
public override MSAst.ExpressionType NodeType {
get {
return MSAst.ExpressionType.Extension;
}
}
public override string ToString() {
return GetType().Name;
}
#endregion
#region Internal APIs
internal PythonAst GlobalParent {
get {
Node cur = this;
while (!(cur is PythonAst)) {
Debug.Assert(cur != null);
cur = cur.Parent;
}
return (PythonAst)cur;
}
}
internal bool EmitDebugSymbols {
get {
return GlobalParent.EmitDebugSymbols;
}
}
internal bool StripDocStrings {
get {
return GlobalParent.PyContext.PythonOptions.StripDocStrings;
}
}
internal bool Optimize {
get {
return GlobalParent.PyContext.PythonOptions.Optimize;
}
}
internal virtual string GetDocumentation(Statement/*!*/ stmt) {
if (StripDocStrings) {
return null;
}
return stmt.Documentation;
}
#endregion
#region Transformation Helpers
internal static MSAst.Expression[] ToObjectArray(IList<Expression> expressions) {
MSAst.Expression[] to = new MSAst.Expression[expressions.Count];
for (int i = 0; i < expressions.Count; i++) {
to[i] = AstUtils.Convert(expressions[i], typeof(object));
}
return to;
}
internal static MSAst.Expression TransformOrConstantNull(Expression expression, Type/*!*/ type) {
if (expression == null) {
return AstUtils.Constant(null, type);
} else {
return AstUtils.Convert(expression, type);
}
}
internal MSAst.Expression TransformAndDynamicConvert(Expression expression, Type/*!*/ type) {
Debug.Assert(expression != null);
MSAst.Expression res = expression;
// Do we need conversion?
if (!CanAssign(type, expression.Type)) {
// ensure we're reduced before we check for dynamic expressions.
var reduced = expression.Reduce();
if (reduced is LightDynamicExpression) {
reduced = reduced.Reduce();
}
// Add conversion step to the AST
MSAst.DynamicExpression ae = reduced as MSAst.DynamicExpression;
ReducableDynamicExpression rde = reduced as ReducableDynamicExpression;
if ((ae != null && ae.Binder is PythonBinaryOperationBinder) ||
(rde != null && rde.Binder is PythonBinaryOperationBinder)) {
// create a combo site which does the conversion
PythonBinaryOperationBinder binder;
IList<MSAst.Expression> args;
if (ae != null) {
binder = (PythonBinaryOperationBinder)ae.Binder;
args = ArrayUtils.ToArray(ae.Arguments);
} else {
binder = (PythonBinaryOperationBinder)rde.Binder;
args = rde.Args;
}
ParameterMappingInfo[] infos = new ParameterMappingInfo[args.Count];
for (int i = 0; i < infos.Length; i++) {
infos[i] = ParameterMappingInfo.Parameter(i);
}
res = DynamicExpression.Dynamic(
GlobalParent.PyContext.BinaryOperationRetType(
binder,
GlobalParent.PyContext.Convert(
type,
ConversionResultKind.ExplicitCast
)
),
type,
args
);
} else {
res = GlobalParent.Convert(
type,
ConversionResultKind.ExplicitCast,
reduced
);
}
}
return res;
}
internal static bool CanAssign(Type/*!*/ to, Type/*!*/ from) {
return to.IsAssignableFrom(from) && (to.IsValueType == from.IsValueType);
}
internal static MSAst.Expression/*!*/ ConvertIfNeeded(MSAst.Expression/*!*/ expression, Type/*!*/ type) {
Debug.Assert(expression != null);
// Do we need conversion?
if (!CanAssign(type, expression.Type)) {
// Add conversion step to the AST
expression = AstUtils.Convert(expression, type);
}
return expression;
}
internal static MSAst.Expression TransformMaybeSingleLineSuite(Statement body, SourceLocation prevStart) {
if (body.GlobalParent.IndexToLocation(body.StartIndex).Line != prevStart.Line) {
return body;
}
MSAst.Expression res = body.Reduce();
res = RemoveDebugInfo(prevStart.Line, res);
if (res.Type != typeof(void)) {
res = AstUtils.Void(res);
}
return res;
}
internal static MSAst.Expression RemoveDebugInfo(int prevStart, MSAst.Expression res) {
if (res is BlockExpression block && block.Expressions.Count > 0) {
// body on the same line as an if, don't generate a 2nd sequence point
if (block.Expressions[0] is DebugInfoExpression dbgInfo && dbgInfo.StartLine == prevStart) {
// we remove the debug info based upon how it's generated in DebugStatement.AddDebugInfo which is
// the helper method which adds the debug info.
if (block.Type == typeof(void)) {
Debug.Assert(block.Expressions.Count == 3);
Debug.Assert(block.Expressions[2] is MSAst.DebugInfoExpression && ((MSAst.DebugInfoExpression)block.Expressions[2]).IsClear);
res = block.Expressions[1];
} else {
Debug.Assert(block.Expressions.Count == 4);
Debug.Assert(block.Expressions[3] is MSAst.DebugInfoExpression && ((MSAst.DebugInfoExpression)block.Expressions[2]).IsClear);
Debug.Assert(block.Expressions[1] is MSAst.BinaryExpression && ((MSAst.BinaryExpression)block.Expressions[2]).NodeType == MSAst.ExpressionType.Assign);
res = ((MSAst.BinaryExpression)block.Expressions[1]).Right;
}
}
}
return res;
}
/// <summary>
/// Creates a method frame for tracking purposes and enforces recursion
/// </summary>
internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) {
return new FramedCodeExpression(localContext, codeObject, body);
}
/// <summary>
/// Removes the frames from generated code for when we're compiling the tracing delegate
/// which will track the frames it's self.
/// </summary>
internal static MSAst.Expression RemoveFrame(MSAst.Expression expression) {
return new FramedCodeVisitor().Visit(expression);
}
class FramedCodeVisitor : ExpressionVisitor {
public override MSAst.Expression Visit(MSAst.Expression node) {
if (node is FramedCodeExpression framedCode) {
return framedCode.Body;
}
return base.Visit(node);
}
}
sealed class FramedCodeExpression : MSAst.Expression {
private readonly MSAst.Expression _localContext, _codeObject, _body;
public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) {
_localContext = localContext;
_codeObject = codeObject;
_body = body;
}
public override ExpressionType NodeType {
get {
return ExpressionType.Extension;
}
}
public MSAst.Expression Body {
get {
return _body;
}
}
public override MSAst.Expression Reduce() {
return AstUtils.Try(
Ast.Assign(
FunctionStackVariable,
Ast.Call(
AstMethods.PushFrame,
_localContext,
_codeObject
)
),
_body
).Finally(
Ast.Call(
FunctionStackVariable,
typeof(List<FunctionStack>).GetMethod("RemoveAt"),
Ast.Add(
Ast.Property(
FunctionStackVariable,
"Count"
),
Ast.Constant(-1)
)
)
);
}
public override Type Type {
get {
return _body.Type;
}
}
public override bool CanReduce {
get {
return true;
}
}
protected override MSAst.Expression VisitChildren(ExpressionVisitor visitor) {
var localContext = visitor.Visit(_localContext);
var codeObject = visitor.Visit(_codeObject);
var body = visitor.Visit(_body);
if (localContext != _localContext || _codeObject != codeObject || body != _body) {
return new FramedCodeExpression(localContext, codeObject, body);
}
return this;
}
}
internal static MSAst.Expression/*!*/ MakeAssignment(MSAst.ParameterExpression/*!*/ variable, MSAst.Expression/*!*/ right) {
return Ast.Assign(variable, AstUtils.Convert(right, variable.Type));
}
internal MSAst.Expression MakeAssignment(MSAst.ParameterExpression variable, MSAst.Expression right, SourceSpan span) {
return GlobalParent.AddDebugInfoAndVoid(Ast.Assign(variable, AstUtils.Convert(right, variable.Type)), span);
}
internal static MSAst.Expression/*!*/ AssignValue(MSAst.Expression/*!*/ expression, MSAst.Expression value) {
Debug.Assert(expression != null);
Debug.Assert(value != null);
if (expression is IPythonVariableExpression pyGlobal) {
return pyGlobal.Assign(value);
}
return Ast.Assign(expression, value);
}
internal static MSAst.Expression/*!*/ Delete(MSAst.Expression/*!*/ expression) {
if (expression is IPythonVariableExpression pyGlobal) {
return pyGlobal.Delete();
}
return Ast.Assign(expression, Ast.Field(null, typeof(Uninitialized).GetField("Instance")));
}
#endregion
#region Basic Line Number Infrastructure
/// <summary>
/// A temporary variable to track if the current line number has been emitted via the fault update block.
///
/// For example consider:
///
/// try:
/// raise Exception()
/// except Exception, e:
/// # do something here
/// raise
///
/// At "do something here" we need to have already emitted the line number, when we re-raise we shouldn't add it
/// again. If we handled the exception then we should have set the bool back to false.
///
/// We also sometimes directly check _lineNoUpdated to avoid creating this unless we have nested exceptions.
/// </summary>
internal static MSAst.ParameterExpression/*!*/ LineNumberUpdated {
get {
return _lineNumberUpdated;
}
}
internal static MSAst.Expression UpdateLineNumber(int line) {
return Ast.Assign(LineNumberExpression, AstUtils.Constant(line));
}
internal static MSAst.Expression UpdateLineUpdated(bool updated) {
return Ast.Assign(LineNumberUpdated, AstUtils.Constant(updated));
}
internal static MSAst.Expression PushLineUpdated(bool updated, MSAst.ParameterExpression saveCurrent) {
return MSAst.Expression.Block(
Ast.Assign(saveCurrent, LineNumberUpdated),
Ast.Assign(LineNumberUpdated, AstUtils.Constant(updated))
);
}
internal static MSAst.Expression PopLineUpdated(MSAst.ParameterExpression saveCurrent) {
return Ast.Assign(LineNumberUpdated, saveCurrent);
}
/// <summary>
/// A temporary variable to track the current line number
/// </summary>
internal static MSAst.ParameterExpression/*!*/ LineNumberExpression {
get {
return _lineNoVar;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
namespace NDatabase.TypeResolution
{
/// <summary>
/// Provides access to a central registry of aliased <see cref="System.Type"/>s.
/// </summary>
/// <remarks>
/// <p>
/// Simplifies configuration by allowing aliases to be used instead of
/// fully qualified type names.
/// </p>
/// <p>
/// Comes 'pre-loaded' with a number of convenience alias' for the more
/// common types; an example would be the '<c>int</c>' (or '<c>Integer</c>'
/// for Visual Basic.NET developers) alias for the <see cref="System.Int32"/>
/// type.
/// </p>
/// </remarks>
internal static class TypeRegistry
{
/// <summary>
/// The alias around the 'int' type.
/// </summary>
private const string Int32Alias = "int";
/// <summary>
/// The alias around the 'int[]' array type.
/// </summary>
private const string Int32ArrayAlias = "int[]";
/// <summary>
/// The alias around the 'decimal' type.
/// </summary>
private const string DecimalAlias = "decimal";
/// <summary>
/// The alias around the 'decimal[]' array type.
/// </summary>
private const string DecimalArrayAlias = "decimal[]";
/// <summary>
/// The alias around the 'char' type.
/// </summary>
private const string CharAlias = "char";
/// <summary>
/// The alias around the 'char[]' array type.
/// </summary>
private const string CharArrayAlias = "char[]";
/// <summary>
/// The alias around the 'long' type.
/// </summary>
private const string Int64Alias = "long";
/// <summary>
/// The alias around the 'long[]' array type.
/// </summary>
private const string Int64ArrayAlias = "long[]";
/// <summary>
/// The alias around the 'short' type.
/// </summary>
private const string Int16Alias = "short";
/// <summary>
/// The alias around the 'short[]' array type.
/// </summary>
private const string Int16ArrayAlias = "short[]";
/// <summary>
/// The alias around the 'unsigned int' type.
/// </summary>
private const string UInt32Alias = "uint";
/// <summary>
/// The alias around the 'unsigned long' type.
/// </summary>
private const string UInt64Alias = "ulong";
/// <summary>
/// The alias around the 'ulong[]' array type.
/// </summary>
private const string UInt64ArrayAlias = "ulong[]";
/// <summary>
/// The alias around the 'uint[]' array type.
/// </summary>
private const string UInt32ArrayAlias = "uint[]";
/// <summary>
/// The alias around the 'unsigned short' type.
/// </summary>
private const string UInt16Alias = "ushort";
/// <summary>
/// The alias around the 'ushort[]' array type.
/// </summary>
private const string UInt16ArrayAlias = "ushort[]";
/// <summary>
/// The alias around the 'double' type.
/// </summary>
private const string DoubleAlias = "double";
/// <summary>
/// The alias around the 'double[]' array type.
/// </summary>
private const string DoubleArrayAlias = "double[]";
/// <summary>
/// The alias around the 'float' type.
/// </summary>
private const string FloatAlias = "float";
/// <summary>
/// The alias around the 'Single' type (Visual Basic.NET style).
/// </summary>
private const string SingleAlias = "Single";
/// <summary>
/// The alias around the 'float[]' array type.
/// </summary>
private const string FloatArrayAlias = "float[]";
/// <summary>
/// The alias around the 'DateTime' type.
/// </summary>
private const string DateTimeAlias = "DateTime";
/// <summary>
/// The alias around the 'DateTime' type (C# style).
/// </summary>
private const string DateAlias = "date";
/// <summary>
/// The alias around the 'DateTime[]' array type.
/// </summary>
private const string DateTimeArrayAlias = "DateTime[]";
/// <summary>
/// The alias around the 'DateTime[]' array type.
/// </summary>
private const string DateTimeArrayAliasCSharp = "date[]";
/// <summary>
/// The alias around the 'bool' type.
/// </summary>
private const string BoolAlias = "bool";
/// <summary>
/// The alias around the 'bool[]' array type.
/// </summary>
private const string BoolArrayAlias = "bool[]";
/// <summary>
/// The alias around the 'string' type.
/// </summary>
private const string StringAlias = "string";
/// <summary>
/// The alias around the 'string[]' array type.
/// </summary>
private const string StringArrayAlias = "string[]";
/// <summary>
/// The alias around the 'object' type.
/// </summary>
private const string ObjectAlias = "object";
/// <summary>
/// The alias around the 'object[]' array type.
/// </summary>
private const string ObjectArrayAlias = "object[]";
/// <summary>
/// The alias around the 'int?' type.
/// </summary>
private const string NullableInt32Alias = "int?";
/// <summary>
/// The alias around the 'int?[]' array type.
/// </summary>
private const string NullableInt32ArrayAlias = "int?[]";
/// <summary>
/// The alias around the 'decimal?' type.
/// </summary>
private const string NullableDecimalAlias = "decimal?";
/// <summary>
/// The alias around the 'decimal?[]' array type.
/// </summary>
private const string NullableDecimalArrayAlias = "decimal?[]";
/// <summary>
/// The alias around the 'char?' type.
/// </summary>
private const string NullableCharAlias = "char?";
/// <summary>
/// The alias around the 'char?[]' array type.
/// </summary>
private const string NullableCharArrayAlias = "char?[]";
/// <summary>
/// The alias around the 'long?' type.
/// </summary>
private const string NullableInt64Alias = "long?";
/// <summary>
/// The alias around the 'long?[]' array type.
/// </summary>
private const string NullableInt64ArrayAlias = "long?[]";
/// <summary>
/// The alias around the 'short?' type.
/// </summary>
private const string NullableInt16Alias = "short?";
/// <summary>
/// The alias around the 'short?[]' array type.
/// </summary>
private const string NullableInt16ArrayAlias = "short?[]";
/// <summary>
/// The alias around the 'unsigned int?' type.
/// </summary>
private const string NullableUInt32Alias = "uint?";
/// <summary>
/// The alias around the 'unsigned long?' type.
/// </summary>
private const string NullableUInt64Alias = "ulong?";
/// <summary>
/// The alias around the 'ulong?[]' array type.
/// </summary>
private const string NullableUInt64ArrayAlias = "ulong?[]";
/// <summary>
/// The alias around the 'uint?[]' array type.
/// </summary>
private const string NullableUInt32ArrayAlias = "uint?[]";
/// <summary>
/// The alias around the 'unsigned short?' type.
/// </summary>
private const string NullableUInt16Alias = "ushort?";
/// <summary>
/// The alias around the 'ushort?[]' array type.
/// </summary>
private const string NullableUInt16ArrayAlias = "ushort?[]";
/// <summary>
/// The alias around the 'double?' type.
/// </summary>
private const string NullableDoubleAlias = "double?";
/// <summary>
/// The alias around the 'double?[]' array type.
/// </summary>
private const string NullableDoubleArrayAlias = "double?[]";
/// <summary>
/// The alias around the 'float?' type.
/// </summary>
private const string NullableFloatAlias = "float?";
/// <summary>
/// The alias around the 'float?[]' array type.
/// </summary>
private const string NullableFloatArrayAlias = "float?[]";
/// <summary>
/// The alias around the 'bool?' type.
/// </summary>
private const string NullableBoolAlias = "bool?";
/// <summary>
/// The alias around the 'bool?[]' array type.
/// </summary>
private const string NullableBoolArrayAlias = "bool?[]";
private static readonly IDictionary<string, Type> Types = new Dictionary<string, Type>();
/// <summary>
/// Registers standard and user-configured type aliases.
/// </summary>
static TypeRegistry()
{
Types["Int32"] = typeof (Int32);
Types[Int32Alias] = typeof (Int32);
Types[Int32ArrayAlias] = typeof (Int32[]);
Types["UInt32"] = typeof (UInt32);
Types[UInt32Alias] = typeof (UInt32);
Types[UInt32ArrayAlias] = typeof (UInt32[]);
Types["Int16"] = typeof (Int16);
Types[Int16Alias] = typeof (Int16);
Types[Int16ArrayAlias] = typeof (Int16[]);
Types["UInt16"] = typeof (UInt16);
Types[UInt16Alias] = typeof (UInt16);
Types[UInt16ArrayAlias] = typeof (UInt16[]);
Types["Int64"] = typeof (Int64);
Types[Int64Alias] = typeof (Int64);
Types[Int64ArrayAlias] = typeof (Int64[]);
Types["UInt64"] = typeof (UInt64);
Types[UInt64Alias] = typeof (UInt64);
Types[UInt64ArrayAlias] = typeof (UInt64[]);
Types[DoubleAlias] = typeof (double);
Types[DoubleArrayAlias] = typeof (double[]);
Types[FloatAlias] = typeof (float);
Types[SingleAlias] = typeof (float);
Types[FloatArrayAlias] = typeof (float[]);
Types[DateTimeAlias] = typeof (DateTime);
Types[DateAlias] = typeof (DateTime);
Types[DateTimeArrayAlias] = typeof (DateTime[]);
Types[DateTimeArrayAliasCSharp] = typeof (DateTime[]);
Types[BoolAlias] = typeof (bool);
Types[BoolArrayAlias] = typeof (bool[]);
Types[DecimalAlias] = typeof (decimal);
Types[DecimalArrayAlias] = typeof (decimal[]);
Types[CharAlias] = typeof (char);
Types[CharArrayAlias] = typeof (char[]);
Types[StringAlias] = typeof (string);
Types[StringArrayAlias] = typeof (string[]);
Types[ObjectAlias] = typeof (object);
Types[ObjectArrayAlias] = typeof (object[]);
Types[NullableInt32Alias] = typeof (int?);
Types[NullableInt32ArrayAlias] = typeof (int?[]);
Types[NullableDecimalAlias] = typeof (decimal?);
Types[NullableDecimalArrayAlias] = typeof (decimal?[]);
Types[NullableCharAlias] = typeof (char?);
Types[NullableCharArrayAlias] = typeof (char?[]);
Types[NullableInt64Alias] = typeof (long?);
Types[NullableInt64ArrayAlias] = typeof (long?[]);
Types[NullableInt16Alias] = typeof (short?);
Types[NullableInt16ArrayAlias] = typeof (short?[]);
Types[NullableUInt32Alias] = typeof (uint?);
Types[NullableUInt32ArrayAlias] = typeof (uint?[]);
Types[NullableUInt64Alias] = typeof (ulong?);
Types[NullableUInt64ArrayAlias] = typeof (ulong?[]);
Types[NullableUInt16Alias] = typeof (ushort?);
Types[NullableUInt16ArrayAlias] = typeof (ushort?[]);
Types[NullableDoubleAlias] = typeof (double?);
Types[NullableDoubleArrayAlias] = typeof (double?[]);
Types[NullableFloatAlias] = typeof (float?);
Types[NullableFloatArrayAlias] = typeof (float?[]);
Types[NullableBoolAlias] = typeof (bool?);
Types[NullableBoolArrayAlias] = typeof (bool?[]);
}
/// <summary>
/// Resolves the supplied <paramref name="alias"/> to a <see cref="System.Type"/>.
/// </summary>
/// <param name="alias">
/// The alias to resolve.
/// </param>
/// <returns>
/// The <see cref="System.Type"/> the supplied <paramref name="alias"/> was
/// associated with, or <see lang="null"/> if no <see cref="System.Type"/>
/// was previously registered for the supplied <paramref name="alias"/>.
/// </returns>
/// <exception cref="System.ArgumentNullException">
/// If the supplied <paramref name="alias"/> is <see langword="null"/> or
/// contains only whitespace character(s).
/// </exception>
public static Type ResolveType(string alias)
{
if (string.IsNullOrEmpty(alias))
throw new ArgumentNullException("alias");
Type type;
Types.TryGetValue(alias, out type);
return type;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using Abp.Collections.Extensions;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Reflection;
namespace Abp.Runtime.Validation.Interception
{
/// <summary>
/// This class is used to validate a method call (invocation) for method arguments.
/// </summary>
public class MethodInvocationValidator : ITransientDependency
{
protected MethodInfo Method { get; private set; }
protected object[] ParameterValues { get; private set; }
protected ParameterInfo[] Parameters { get; private set; }
protected List<ValidationResult> ValidationErrors { get; }
protected List<IShouldNormalize> ObjectsToBeNormalized { get; }
private readonly IValidationConfiguration _configuration;
private readonly IIocResolver _iocResolver;
/// <summary>
/// Creates a new <see cref="MethodInvocationValidator"/> instance.
/// </summary>
public MethodInvocationValidator(IValidationConfiguration configuration, IIocResolver iocResolver)
{
_configuration = configuration;
_iocResolver = iocResolver;
ValidationErrors = new List<ValidationResult>();
ObjectsToBeNormalized = new List<IShouldNormalize>();
}
/// <param name="method">Method to be validated</param>
/// <param name="parameterValues">List of arguments those are used to call the <paramref name="method"/>.</param>
public virtual void Initialize(MethodInfo method, object[] parameterValues)
{
if (method == null)
{
throw new ArgumentNullException(nameof(method));
}
if (parameterValues == null)
{
throw new ArgumentNullException(nameof(parameterValues));
}
Method = method;
ParameterValues = parameterValues;
Parameters = method.GetParameters();
}
/// <summary>
/// Validates the method invocation.
/// </summary>
public void Validate()
{
CheckInitialized();
if (!Method.IsPublic)
{
return;
}
if (IsValidationDisabled())
{
return;
}
if (Parameters.IsNullOrEmpty())
{
return;
}
if (Parameters.Length != ParameterValues.Length)
{
throw new Exception("Method parameter count does not match with argument count!");
}
for (var i = 0; i < Parameters.Length; i++)
{
ValidateMethodParameter(Parameters[i], ParameterValues[i]);
}
if (ValidationErrors.Any())
{
throw new AbpValidationException(
"Method arguments are not valid! See ValidationErrors for details.",
ValidationErrors
);
}
foreach (var objectToBeNormalized in ObjectsToBeNormalized)
{
objectToBeNormalized.Normalize();
}
}
private void CheckInitialized()
{
if (Method == null)
{
throw new AbpException("This object has not been initialized. Call Initialize method first.");
}
}
protected virtual bool IsValidationDisabled()
{
if (Method.IsDefined(typeof(EnableValidationAttribute), true))
{
return false;
}
return ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<DisableValidationAttribute>(Method) != null;
}
/// <summary>
/// Validates given parameter for given value.
/// </summary>
/// <param name="parameterInfo">Parameter of the method to validate</param>
/// <param name="parameterValue">Value to validate</param>
protected virtual void ValidateMethodParameter(ParameterInfo parameterInfo, object parameterValue)
{
if (parameterValue == null)
{
if (!parameterInfo.IsOptional &&
!parameterInfo.IsOut &&
!TypeHelper.IsPrimitiveExtendedIncludingNullable(parameterInfo.ParameterType))
{
ValidationErrors.Add(new ValidationResult(parameterInfo.Name + " is null!", new[] { parameterInfo.Name }));
}
return;
}
ValidateObjectRecursively(parameterValue);
}
protected virtual void ValidateObjectRecursively(object validatingObject)
{
if (validatingObject == null)
{
return;
}
SetDataAnnotationAttributeErrors(validatingObject);
//Validate items of enumerable
if (validatingObject is IEnumerable && !(validatingObject is IQueryable))
{
foreach (var item in (validatingObject as IEnumerable))
{
ValidateObjectRecursively(item);
}
}
//Custom validations
(validatingObject as ICustomValidate)?.AddValidationErrors(
new CustomValidationContext(
ValidationErrors,
_iocResolver
)
);
//Add list to be normalized later
if (validatingObject is IShouldNormalize)
{
ObjectsToBeNormalized.Add(validatingObject as IShouldNormalize);
}
//Do not recursively validate for enumerable objects
if (validatingObject is IEnumerable)
{
return;
}
var validatingObjectType = validatingObject.GetType();
//Do not recursively validate for primitive objects
if (TypeHelper.IsPrimitiveExtendedIncludingNullable(validatingObjectType))
{
return;
}
if (_configuration.IgnoredTypes.Any(t => t.IsInstanceOfType(validatingObject)))
{
return;
}
var properties = TypeDescriptor.GetProperties(validatingObject).Cast<PropertyDescriptor>();
foreach (var property in properties)
{
if (property.Attributes.OfType<DisableValidationAttribute>().Any())
{
continue;
}
ValidateObjectRecursively(property.GetValue(validatingObject));
}
}
/// <summary>
/// Checks all properties for DataAnnotations attributes.
/// </summary>
protected virtual void SetDataAnnotationAttributeErrors(object validatingObject)
{
var properties = TypeDescriptor.GetProperties(validatingObject).Cast<PropertyDescriptor>();
foreach (var property in properties)
{
var validationAttributes = property.Attributes.OfType<ValidationAttribute>().ToArray();
if (validationAttributes.IsNullOrEmpty())
{
continue;
}
var validationContext = new ValidationContext(validatingObject)
{
DisplayName = property.DisplayName,
MemberName = property.Name
};
foreach (var attribute in validationAttributes)
{
var result = attribute.GetValidationResult(property.GetValue(validatingObject), validationContext);
if (result != null)
{
ValidationErrors.Add(result);
}
}
}
if (validatingObject is IValidatableObject)
{
var results = (validatingObject as IValidatableObject).Validate(new ValidationContext(validatingObject));
ValidationErrors.AddRange(results);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using DevExpress.CodeRush.Core;
using DevExpress.CodeRush.Diagnostics.General;
using System.Windows.Forms;
namespace CR_XkeysEngine
{
public enum MatchQuality {NoMatch, FullMatch}
/// <summary>
/// Binds a command with a keystroke and a context.
/// </summary>
public class CommandKeyBinding : ICloneable
{
#region private fields...
private CommandKeyFolder _ParentFolder;
private bool _Enabled = true;
private bool _CtrlKeyDown;
private bool _AnyShiftModifier;
private bool _AltKeyDown;
private bool _ShiftKeyDown;
private string _Command = String.Empty;
private string _Parameters = String.Empty;
private string _CustomData = String.Empty;
private string _Comments = String.Empty;
private ContextPickerData _Context = new ContextPickerData();
private ContextNode _ContextRoot;
#endregion
// constructors...
#region CommandKeyBinding
public CommandKeyBinding()
{
}
#endregion
// public properties...
#region Command
public string Command
{
get
{
return _Command;
}
set
{
_Command = value;
}
}
#endregion
#region Parameters
public string Parameters
{
get
{
return _Parameters;
}
set
{
_Parameters = value;
}
}
#endregion
#region Comments
public string Comments
{
get
{
return _Comments;
}
set
{
_Comments = value;
}
}
#endregion
string GetShiftKeysAsStr()
{
if (_AnyShiftModifier)
return "";
return DevExpress.CodeRush.Core.CodeRush.Key.GetName(0, 0, _CtrlKeyDown, _ShiftKeyDown, _AltKeyDown);
}
public string CustomBindingName
{
get
{
return String.Format("{0}{1}", GetShiftKeysAsStr(), CustomData);
}
}
#region ShiftKeyDown
public bool ShiftKeyDown
{
get
{
return _ShiftKeyDown;
}
set
{
_ShiftKeyDown = value;
}
}
#endregion
#region AltKeyDown
public bool AltKeyDown
{
get
{
return _AltKeyDown;
}
set
{
_AltKeyDown = value;
}
}
#endregion
#region CtrlKeyDown
public bool CtrlKeyDown
{
get
{
return _CtrlKeyDown;
}
set
{
_CtrlKeyDown = value;
}
}
#endregion
#region AnyShiftModifier
public bool AnyShiftModifier
{
get
{
return _AnyShiftModifier;
}
set
{
_AnyShiftModifier = value;
}
}
#endregion
public string GetDisplayShortcut(KeyLayout xkeyLayout = null)
{
if (xkeyLayout == null)
return CustomBindingName;
return xkeyLayout.GetBindingName(_AnyShiftModifier, _CtrlKeyDown, _ShiftKeyDown, _AltKeyDown, CustomData);
}
#region DisplayShortcut
public string DisplayShortcut
{
get
{
return GetDisplayShortcut();
}
}
#endregion
#region DisplayCommand
public string DisplayCommand
{
get
{
if (Parameters != "")
{
return String.Format("{0}({1})", Command, Parameters);
}
else
{
return Command;
}
}
}
#endregion
/// <summary>
/// Returns true if current binding is available for executing.
/// </summary>
public bool IsAvailable
{
get
{
try
{
string parameters = _Parameters;
DevExpress.CodeRush.Core.Action action = GetAction();
if (action != null)
return action.GetAvailability(parameters);
string fullName = GetFullCommandName();
// here we can not tell if command is available or not.
return CodeRush.Command.Exists(fullName);
}
catch (Exception ex)
{
Log.SendException(ex);
return false;
}
}
}
// private methods...
string GetFullCommandName()
{
string commandName = _Command;
if (commandName.IndexOf(".") < 0)
commandName = "CodeRush." + commandName; // This code must be changed if we ever change the add-in name to "DXCore".
return commandName;
}
public MatchQuality Matches(CustomInputShortcut customInputShortcut)
{
if (customInputShortcut.CustomData == CustomData)
return MatchQuality.FullMatch;
else
return MatchQuality.NoMatch;
}
// public properties
#region Context
public ContextPickerData Context
{
get
{
return _Context;
}
}
#endregion
#region ReadableContext
public string ReadableContext
{
get
{
return GetReadableContext(new ContextNameDecorator(DefaultNameDecorator));
}
}
#endregion
#region SetContext
public void SetContext(ContextPickerData aContext)
{
if (aContext == null)
{
_Context = aContext;
_ContextRoot = null;
}
else
{
_Context = aContext.Clone() as ContextPickerData;
_ContextRoot = new ContextNode(aContext.Selected);
}
}
#endregion
#region Enabled
public bool Enabled
{
get
{
return _Enabled;
}
set
{
_Enabled = value;
}
}
#endregion
// public methods
public DevExpress.CodeRush.Core.Action GetAction()
{
DevExpress.CodeRush.Core.Action action = CodeRush.Actions.Get(_Command);
if (action != null)
return action;
string parameters;
string isolatedAction = _Command;
CodeRush.StrUtil.SeparateParams(ref isolatedAction, out parameters);
if (isolatedAction != _Command)
return CodeRush.Actions.Get(isolatedAction);
return null;
}
#region Execute
public bool Execute()
{
string lParams = _Parameters;
DevExpress.CodeRush.Core.Action codeRushCommand = GetAction();
if (codeRushCommand != null)
{
bool handled = true;
codeRushCommand.DoExecute(lParams, ref handled);
return handled;
}
string commandName = GetFullCommandName();
if (CodeRush.Command.Exists(commandName))
return CodeRush.Command.Execute(commandName, _Parameters);
else
return false;
}
#endregion
#region KeyStateMatches
/// <summary>
/// Returns true if the key state matches the expected state.
/// </summary>
/// <param name="keyToMatch">The key to match: one of Keys.Control, Keys.Shift, or Keys.Alt.</param>
/// <param name="expectedState">true == down, false == up</param>
private static bool KeyStateMatches(Keys keyToMatch, bool expectedState)
{
if ((Control.ModifierKeys & keyToMatch) == keyToMatch) // Key is down.
return expectedState;
else // Key is up (not pressed)
return !expectedState; // Return true if we were expecting the key to be up.
}
#endregion
#region ShiftKeysMatch
private bool ShiftKeysMatch()
{
if (AnyShiftModifier)
return true;
return KeyStateMatches(Keys.Control, CtrlKeyDown) &&
KeyStateMatches(Keys.Shift, ShiftKeyDown) &&
KeyStateMatches(Keys.Alt, AltKeyDown);
}
#endregion
public string CustomData
{
get
{
return _CustomData;
}
set
{
_CustomData = value;
}
}
#region Matches(string customData)
public MatchQuality Matches(string customData)
{
if (!ShiftKeysMatch())
return MatchQuality.NoMatch;
if (CustomData == customData)
if (ContextMatches())
return MatchQuality.FullMatch;
return MatchQuality.NoMatch;
}
#endregion
internal bool ShouldLogDataForBinding()
{
return DevExpress.CodeRush.Core.KeyboardServices.LogShortcutChecks && !String.IsNullOrEmpty(DisplayCommand) && DisplayCommand.StartsWith("Embed");
}
#region AffirmativeContextMatches
private bool AffirmativeContextMatches()
{
bool rootIsNull = _ContextRoot == null;
if (rootIsNull)
{
if (ShouldLogDataForBinding())
DevExpress.CodeRush.Core.KeyboardServices.LogShortcutMessage("AffirmativeContextMatches - root is null");
return true;
}
bool contextSatisfied = _ContextRoot.IsSatisfied(ShouldLogDataForBinding());
if (ShouldLogDataForBinding())
DevExpress.CodeRush.Core.KeyboardServices.LogShortcutMessage("AffirmativeContextMatches {0} _ContextRoot {1} ", contextSatisfied, _ContextRoot.Description);
return contextSatisfied;
}
#endregion
#region NegativeContextMatches
private bool NegativeContextMatches()
{
bool result = CodeRush.Context.Satisfied(_Context.Excluded, false);
if (ShouldLogDataForBinding())
DevExpress.CodeRush.Core.KeyboardServices.LogShortcutMessage("NegativeContextMatches {0} _Context.Excluded {1} ", result, _Context.Excluded.ToString());
return result;
}
#endregion
// TODO: Move to CodeRush.State
public ContextProviderBase[] GetStateContextProviders()
{
StateProviderBase[] lProviders = CodeRush.States.Providers;
if (lProviders == null)
return new ContextProviderBase[0];
ContextProviderBase[] lContextProviders = new ContextProviderBase[lProviders.Length];
for (int i = 0; i < lProviders.Length; i++)
lContextProviders[i] = lProviders[i].StateContext;
return lContextProviders;
}
private ContextProviderBase[] FilterSatisfiedProviders(ContextProviderBase[] providers)
{
if (providers == null || providers.Length == 0)
return new ContextProviderBase[0];
ArrayList lSatisfied = new ArrayList();
for (int i = 0; i < providers.Length; i++)
{
ContextProviderBase lProvider = providers[i];
if (CodeRush.Context.Satisfied(lProvider.ProviderName) == ContextResult.Satisfied)
lSatisfied.Add(lProvider);
}
ContextProviderBase[] lResult = new ContextProviderBase[lSatisfied.Count];
lSatisfied.CopyTo(lResult);
return lResult;
}
#region StateContextMatches
private bool StateContextMatches()
{
ContextProviderBase[] lStateProviders = GetStateContextProviders();
ContextProviderBase[] lSatisfiedProviders = FilterSatisfiedProviders(lStateProviders);
bool lIsAnyStateActive = lSatisfiedProviders.Length > 0;
if (lIsAnyStateActive)
{
for (int i = 0; i < lSatisfiedProviders.Length; i++)
{
ContextProviderBase lProvider = lSatisfiedProviders[i];
if (_Context.Selected.Contains(lProvider.ProviderName))
{
DevExpress.CodeRush.Core.KeyboardServices.LogShortcutMessage("StateContextMatches inside loop");
return true;
}
}
DevExpress.CodeRush.Core.KeyboardServices.LogShortcutMessage("!StateContextMatches");
return false;
}
DevExpress.CodeRush.Core.KeyboardServices.LogShortcutMessage("StateContextMatches");
return true;
}
#endregion
#region ContextMatches
internal bool ContextMatches()
{
return NegativeContextMatches() && AffirmativeContextMatches() && StateContextMatches();
}
#endregion
#region ChangeParent
private void ChangeParent(CommandKeyFolder newParent)
{
if (_ParentFolder != null)
_ParentFolder.RemoveBinding(this);
if (newParent != null)
newParent.AddBinding(this);
}
#endregion
#region DeleteBinding
protected internal void DeleteBinding()
{
if (ParentFolder != null)
ParentFolder = null;
}
#endregion
#region Save
public void Save(DecoupledStorage decoupledStorage, string section, bool isSelected)
{
decoupledStorage.WriteString(section, "CustomData", _CustomData);
decoupledStorage.WriteString(section, "Command", _Command);
decoupledStorage.WriteString(section, "Comments", _Comments);
decoupledStorage.WriteString(section, "Parameters", _Parameters);
decoupledStorage.WriteBoolean(section, "ShiftKeyDown", _ShiftKeyDown);
decoupledStorage.WriteBoolean(section, "CtrlKeyDown", _CtrlKeyDown);
decoupledStorage.WriteBoolean(section, "AnyShiftModifier", _AnyShiftModifier);
decoupledStorage.WriteBoolean(section, "AltKeyDown", _AltKeyDown);
decoupledStorage.WriteBoolean(section, "Enabled", _Enabled);
_Context.Save(decoupledStorage,section,"Context");
decoupledStorage.WriteBoolean(section, "Selected", isSelected);
}
#endregion
#region Load
/// <summary>
/// Loads the command binding from the specified section.
/// </summary>
/// <param name="decoupledStorage"></param>
/// <param name="section"></param>
/// <returns>Returns true if this command was most recently selected.</returns>
public bool Load(DecoupledStorage decoupledStorage, string section)
{
_CustomData = decoupledStorage.ReadString(section, "CustomData", "");
_Command = decoupledStorage.ReadString(section, "Command", "");
_Comments = decoupledStorage.ReadString(section, "Comments", "");
_Parameters = decoupledStorage.ReadString(section, "Parameters", "");
_CtrlKeyDown = decoupledStorage.ReadBoolean(section, "CtrlKeyDown", false);
_AnyShiftModifier = decoupledStorage.ReadBoolean(section, "AnyShiftModifier", false);
_AltKeyDown = decoupledStorage.ReadBoolean(section, "AltKeyDown", false);
_ShiftKeyDown = decoupledStorage.ReadBoolean(section, "ShiftKeyDown", false);
_Enabled = decoupledStorage.ReadBoolean(section, "Enabled", true);
_Context.Load(decoupledStorage,section, "Context");
_ContextRoot = new ContextNode(_Context.Selected);
return decoupledStorage.ReadBoolean(section, "Selected", false);
}
#endregion
#region ICloneable Members
public CommandKeyBinding Clone()
{
CommandKeyBinding result = new CommandKeyBinding();
result.Command = Command;
result.Comments = Comments;
result.CustomData= CustomData;
result.Parameters = Parameters;
result.SetContext(Context);
result.AltKeyDown = AltKeyDown;
result.CtrlKeyDown = CtrlKeyDown;
result.AnyShiftModifier = AnyShiftModifier;
result.ShiftKeyDown = ShiftKeyDown;
return result;
}
object System.ICloneable.Clone()
{
return Clone();
}
#endregion
#region DefaultNameDecorator
private string DefaultNameDecorator(string name, string path)
{
return name;
}
#endregion
#region GetReadableContext
public string GetReadableContext(ContextNameDecorator decorator)
{
string lResult = "";
if (_ContextRoot == null)
{
if (_Context == null)
lResult = "";
_ContextRoot = new ContextNode(_Context.Selected);
}
lResult = _ContextRoot.GetReadableContext(_Context, decorator);
return lResult;
}
#endregion
#region SetParentFolder
protected internal void SetParentFolder(CommandKeyFolder parentFolder)
{
_ParentFolder = parentFolder;
}
#endregion
#region ParentFolder
public CommandKeyFolder ParentFolder
{
get
{
return _ParentFolder;
}
set
{
if (_ParentFolder == value)
return;
ChangeParent(value);
}
}
#endregion
#region IsCompletelyEnabled
public bool IsCompletelyEnabled
{
get
{
CommandKeyFolder lParentFolder = ParentFolder;
if (lParentFolder == null)
return Enabled;
return lParentFolder.IsCompletelyEnabled && Enabled;
}
}
#endregion
public override string ToString()
{
return string.Format("{0} '{1}'", DisplayCommand, DisplayShortcut);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Security;
using Microsoft.Win32;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// This class is responsible for loading resources using the PSSnapin dll and
/// associated registry entries.
/// </summary>
///
/// <remarks>
/// The class creates an app-domain to load the resource assemblies in. Upon dispose
/// the class unloads the app-domain to ensure the assemblies get unloaded. It uses
/// ReflectionOnlyLoad and ReflectionOnlyLoadFrom to ensure that no code can execute
/// and that dependencies are not loaded. This allows us to load assemblies that were
/// built with different version of the CLR.
/// </remarks>
///
internal sealed class RegistryStringResourceIndirect : IDisposable
{
/// <summary>
/// Creates an instance of the RegistryStringResourceIndirect class.
/// </summary>
///
/// <returns>
/// A new instance of the RegistryStringResourceIndirect class.
/// </returns>
///
internal static RegistryStringResourceIndirect GetResourceIndirectReader()
{
return new RegistryStringResourceIndirect();
}
#region IDisposable Members
/// <summary>
/// Set to true when object is disposed
/// </summary>
///
private bool _disposed;
/// <summary>
/// Dispose method unloads the app domain that was
/// created in the constructor.
/// </summary>
///
public void Dispose()
{
if (_disposed == false)
{
if (_domain != null)
{
AppDomain.Unload(_domain);
_domain = null;
_resourceRetriever = null;
}
}
_disposed = true;
}
#endregion IDisposable Members
/// <summary>
/// The app-domain in which the resources will be loaded.
/// </summary>
///
private AppDomain _domain;
/// <summary>
/// The class that is created in the app-domain which does the resource loading.
/// </summary>
///
private ResourceRetriever _resourceRetriever;
/// <summary>
/// Creates the app-domain and the instance of the ResourceRetriever and
/// sets the private fields with the references.
/// </summary>
///
private void CreateAppDomain()
{
if (_domain == null)
{
// Create an app-domain to load the resource assemblies in so that they can be
// unloaded.
_domain = AppDomain.CreateDomain("ResourceIndirectDomain");
_resourceRetriever =
(ResourceRetriever)_domain.CreateInstanceAndUnwrap(
Assembly.GetExecutingAssembly().FullName,
"System.Management.Automation.ResourceRetriever");
}
}
/// <summary>
/// Retrieves a resource string based on a resource reference stored in the specified
/// registry key.
/// </summary>
///
/// <param name="key">
/// The key in which there is a value that contains the reference to the resource
/// to retrieve.
/// </param>
///
/// <param name="valueName">
/// The name of the value in the registry key that contains the reference to the resource.
/// </param>
///
/// <param name="assemblyName">
/// The full name of the assembly from which to load the resource.
/// </param>
///
/// <param name="modulePath">
/// The full path of the assembly from which to load the resource.
/// </param>
///
/// <returns>
/// The resource string that was loaded or null if it could not be found.
/// </returns>
///
/// <remarks>
/// This method ensures that an appropriate registry entry exists and that it contains
/// a properly formatted resource reference ("BaseName,ResourceID"). It then creates an
/// app-domain (or uses and existing one if it already exists on the instance of the class)
/// and an instance of the ResourceRetriever in that app-domain. It then calls the ResourceRetriever
/// to load the specified assembly and retrieve the resource. The assembly is loaded using ReflectionOnlyLoad
/// or ReflectionOnlyLoadFrom using the assemblyName or moduleName (respectively) so that
/// no code can be executed.
///
/// The app-domain is unloaded when this class instance is disposed.
/// </remarks>
///
internal string GetResourceStringIndirect(
RegistryKey key,
string valueName,
string assemblyName,
string modulePath)
{
if (_disposed)
{
throw PSTraceSource.NewInvalidOperationException(MshSnapinInfo.ResourceReaderDisposed);
}
if (key == null)
{
throw PSTraceSource.NewArgumentNullException("key");
}
if (String.IsNullOrEmpty(valueName))
{
throw PSTraceSource.NewArgumentException("valueName");
}
if (String.IsNullOrEmpty(assemblyName))
{
throw PSTraceSource.NewArgumentException("assemblyName");
}
if (String.IsNullOrEmpty(modulePath))
{
throw PSTraceSource.NewArgumentException("modulePath");
}
string result = null;
do // false loop
{
// Read the resource reference from the registry
string regValue = GetRegKeyValueAsString(key, valueName);
if (regValue == null)
{
break;
}
result = GetResourceStringIndirect(assemblyName, modulePath, regValue);
} while (false);
return result;
}
/// <summary>
/// Retrieves a resource string based on a resource reference supplied in <paramref name="baseNameRIDPair"/>.
/// </summary>
///
/// <param name="assemblyName">
/// The full name of the assembly from which to load the resource.
/// </param>
///
/// <param name="modulePath">
/// The full path of the assembly from which to load the resource.
/// </param>
///
/// <param name="baseNameRIDPair">
/// A comma separated basename and resource id pair.
/// </param>
///
/// <returns>
/// The resource string that was loaded or null if it could not be found.
/// </returns>
///
/// <remarks>
/// This method ensures that <paramref name="baseNameRIDPair"/> is a properly formatted
/// resource reference ("BaseName,ResourceID"). It then creates an app-domain (or uses
/// an existing one if it already exists on the instance of the class) and an instance
/// of the ResourceRetriever in that app-domain. It then calls the ResourceRetriever
/// to load the specified assembly and retrieve the resource. The assembly is loaded using ReflectionOnlyLoad
/// or ReflectionOnlyLoadFrom using the assemblyName or moduleName (respectively) so that
/// no code can be executed.
///
/// The app-domain is unloaded when this class instance is disposed.
/// </remarks>
///
internal string GetResourceStringIndirect(
string assemblyName,
string modulePath,
string baseNameRIDPair)
{
if (_disposed)
{
throw PSTraceSource.NewInvalidOperationException(MshSnapinInfo.ResourceReaderDisposed);
}
if (String.IsNullOrEmpty(assemblyName))
{
throw PSTraceSource.NewArgumentException("assemblyName");
}
if (String.IsNullOrEmpty(modulePath))
{
throw PSTraceSource.NewArgumentException("modulePath");
}
if (String.IsNullOrEmpty(baseNameRIDPair))
{
throw PSTraceSource.NewArgumentException("baseNameRIDPair");
}
string result = null;
do // false loop
{
// Initialize the app-domain and resource reader if not already initialized
if (_resourceRetriever == null)
{
CreateAppDomain();
}
// If the app-domain failed to load or the ResourceRetriever instance wasn't
// created, then return null.
if (_resourceRetriever == null)
{
break;
}
// Parse the resource reference
string[] resourceSplit = baseNameRIDPair.Split(Utils.Separators.Comma);
if (resourceSplit.Length != 2)
{
break;
}
string baseName = resourceSplit[0];
string resourceID = resourceSplit[1];
// Get the resource in the app-domain
result = _resourceRetriever.GetStringResource(assemblyName, modulePath, baseName, resourceID);
} while (false);
return result;
}
/// <summary>
/// Retrieves a string value from the registry
/// </summary>
///
/// <param name="key">
/// The key to retrieve the value from.
/// </param>
///
/// <param name="valueName">
/// The name of the value to retrieve.
/// </param>
///
/// <returns>
/// The string value of the registry key value.
/// </returns>
///
private static string GetRegKeyValueAsString(RegistryKey key, string valueName)
{
string result = null;
try
{
// Check the type of the value
RegistryValueKind kind = key.GetValueKind(valueName);
if (kind == RegistryValueKind.String)
{
// Get the value since it is a string
result = key.GetValue(valueName) as string;
}
}
catch (ArgumentException)
{
}
catch (IOException)
{
}
catch (SecurityException)
{
}
return result;
}
}
/// <summary>
/// This class is the worker class used by RegistryStringResourceIndirect to load the resource
/// assemblies and retrieve the resources inside the alternate app-domain.
/// </summary>
///
internal class ResourceRetriever : MarshalByRefObject
{
/// <summary>
/// Loads the specified assembly in the app-domain and retrieves the specified resource string.
/// </summary>
///
/// <param name="assemblyName">
/// Full name of the assembly to retrieve the resource from.
/// </param>
///
/// <param name="modulePath">
/// Full path of the assembly to retrieve the resource from.
/// </param>
///
/// <param name="baseName">
/// The resource base name to retrieve.
/// </param>
///
/// <param name="resourceID">
/// The resource ID of the resource to retrieve.
/// </param>
///
/// <returns>
/// The value of the specified string resource or null if the resource could not be found or loaded.
/// </returns>
///
internal string GetStringResource(string assemblyName, string modulePath, string baseName, string resourceID)
{
string result = null;
do // false loop
{
// Load the resource assembly
Assembly assembly = LoadAssembly(assemblyName, modulePath);
if (assembly == null)
{
break;
}
CultureInfo currentCulture = System.Globalization.CultureInfo.CurrentUICulture;
Stream stream = null;
// Get the resource stream from the manifest
// Loop until we have reached the default culture (identified by an empty Name string in the
// CultureInfo).
do
{
string resourceStream = baseName;
if (!String.IsNullOrEmpty(currentCulture.Name))
resourceStream += "." + currentCulture.Name;
resourceStream += ".resources";
stream = assembly.GetManifestResourceStream(resourceStream);
if (stream != null)
{
break;
}
if (String.IsNullOrEmpty(currentCulture.Name))
{
break;
}
currentCulture = currentCulture.Parent;
} while (true);
if (stream == null)
{
break;
}
// Retrieve the string resource from the stream.
result = GetString(stream, resourceID);
} while (false);
return result;
}
/// <summary>
/// Loads the specified assembly using ReflectionOnlyLoad or ReflectionOnlyLoadFrom
/// </summary>
///
/// <param name="assemblyName">
/// The FullName of the assembly to load. This takes precedence over the modulePath and
/// will be passed to as a parameter to the ReflectionOnlyLoad.
/// </param>
///
/// <param name="modulePath">
/// The full path of the assembly to load. This is used if the ReflectionOnlyLoad using the
/// assemblyName doesn't load the assembly. It is passed as a parameter to the ReflectionOnlyLoadFrom API.
/// </param>
///
/// <returns>
/// An loaded instance of the specified resource assembly or null if the assembly couldn't be loaded.
/// </returns>
///
/// <remarks>
/// Since the intent of this method is to load resource assemblies, the standard culture fallback rules
/// apply. If the assembly couldn't be loaded for the current culture we fallback to the parent culture
/// until the neutral culture is reached or an assembly is loaded.
/// </remarks>
///
private static Assembly LoadAssembly(string assemblyName, string modulePath)
{
Assembly assembly = null;
AssemblyName assemblyNameObj = new AssemblyName(assemblyName);
// Split the path up so we can add the culture directory.
string moduleBase = Path.GetDirectoryName(modulePath);
string moduleFile = Path.GetFileName(modulePath);
CultureInfo currentCulture = System.Globalization.CultureInfo.CurrentUICulture;
// Loop until we have reached the default culture (identified by an empty Name string in the
// CultureInfo).
do
{
assembly = LoadAssemblyForCulture(currentCulture, assemblyNameObj, moduleBase, moduleFile);
if (assembly != null)
{
break;
}
if (String.IsNullOrEmpty(currentCulture.Name))
{
break;
}
currentCulture = currentCulture.Parent;
} while (true);
return assembly;
}
/// <summary>
/// Attempts to load the assembly for the specified culture
/// </summary>
///
/// <param name="culture">
/// The culture for which the assembly should be loaded.
/// </param>
///
/// <param name="assemblyName">
/// The name of the assembly without culture information (or at least undefined culture information).
/// </param>
///
/// <param name="moduleBase">
/// The directory containing the neutral culture assembly.
/// </param>
///
/// <param name="moduleFile">
/// The name of the assembly file.
/// </param>
///
/// <returns>
/// An instance of the loaded resource assembly or null if the assembly could not be loaded.
/// </returns>
///
private static Assembly LoadAssemblyForCulture(
CultureInfo culture,
AssemblyName assemblyName,
string moduleBase,
string moduleFile)
{
Assembly assembly = null;
// Set the assembly FullName to contain the culture we are trying to load.
assemblyName.CultureInfo = culture;
try
{
assembly = Assembly.ReflectionOnlyLoad(assemblyName.FullName);
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
}
catch (FileNotFoundException)
{
}
if (assembly != null)
return assembly;
// Try the resources DLL
string oldAssemblyName = assemblyName.Name;
try
{
assemblyName.Name = oldAssemblyName + ".resources";
assembly = Assembly.ReflectionOnlyLoad(assemblyName.FullName);
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
}
catch (FileNotFoundException)
{
}
if (assembly != null)
return assembly;
assemblyName.Name = oldAssemblyName;
// Add the culture directory into the file path
string modulePath = Path.Combine(moduleBase, culture.Name);
modulePath = Path.Combine(modulePath, moduleFile);
if (File.Exists(modulePath))
{
try
{
assembly = Assembly.ReflectionOnlyLoadFrom(modulePath);
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
}
catch (FileNotFoundException)
{
}
}
return assembly;
}
/// <summary>
/// Retrieves the specified resource string from the resource stream.
/// </summary>
///
/// <param name="stream">
/// The resource stream containing the desired resource.
/// </param>
///
/// <param name="resourceID">
/// The identifier of the string resource to retrieve from the stream.
/// </param>
///
/// <returns>
/// The resource string or null if the resourceID could not be found.
/// </returns>
///
private static string GetString(Stream stream, string resourceID)
{
string result = null;
ResourceReader rr = new ResourceReader(stream);
foreach (DictionaryEntry e in rr)
{
if (String.Equals(resourceID, (string)e.Key, StringComparison.OrdinalIgnoreCase))
{
result = (string)e.Value;
break;
}
}
/* NTRAID#Windows Out Of Band Releases-920971-2005/09/30-JeffJon
* Whidbey v2.0.50727 has a bug where GetResourceData throws an NullReferenceException if
* the assembly used to get the ResourceReader was loaded with ReflectionOnlyLoad. This code
* would be more efficient than the iteration in the foreach loop above and should be enabled
* when we move to the RTM version of Whidbey.
*
string resourceType = null;
byte[] resourceData = null;
rr.GetResourceData(resourceID, out resourceType, out resourceData);
*/
return result;
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using llemoi.AppTools;
using llemoi.ParseTools;
using llemoi.ConsoleTools;
namespace Yaga
{
public class TextPosition
{
public int sourceRow, sourceCol, sourceOffset, sourceLineStartOffset;
public TextPosition(int sr, int sc, int so, int slso)
{
sourceRow = sr;
sourceCol = sc;
sourceOffset = so;
sourceLineStartOffset = slso;
}
}
public class Token
{
public TextPosition textPos;
public string text;
public bool stringLiteral = false;
public string label = "";
public int tag = 0;
public Token(string s, TextPosition t)
{
text = s;
textPos = t;
}
public Token(string s, int sr, int sc, int so, int slso, bool sl): this(s, new TextPosition(sr, sc, so, slso))
{
stringLiteral = sl;
}
public Token(string s, int sr, int sc, int so, int slso): this(s, new TextPosition(sr, sc, so, slso))
{}
}
public class Assembler
{
public Glulx Machine;
private string _sourceFile;
private string _destFile;
private string _err = "";
public string Error { get { return _err; } }
private static bool IsLabel(string s)
{
return s[0] == ':';
}
private static bool IsValidName(string s)
{
return Char.IsLetter(s[0]) && s.Skip(1).All(c => Char.IsLetterOrDigit(c) || c == '_');
}
public Assembler(string sourceFile, string destFile)
{
string opsPath = Path.Combine(App.PerUserDir("yaga"), "glulx.ops");
//Console.WriteLine("Loading opcode specs from {0}", opsPath);
Machine = new Glulx(opsPath);
_sourceFile = sourceFile;
_destFile = destFile;
}
public bool Assemble()
{
//var sourceLines = Preprocess(_sourceFile, new List<string>());
//if (FirstPass(sourceLines)) return SecondPass(sourceLines);
//else return false;
var tokenlist = Tokenise(File.ReadAllText(_sourceFile));
tokenlist = DoInclusions(tokenlist);
// foreach (var t in tokenlist)
// {
// Print.Msg(t.text);
// }
var opcodeList = Pass0(tokenlist);
foreach (var opcode in opcodeList)
{
if (!String.IsNullOrEmpty(opcode[0].label)) Console.Write("[{0}] ", opcode[0].label);
foreach (var token in opcode)
{
Console.Write(token.text+" ");
}
Console.WriteLine();
}
return true;
}
private List<List<Token>> Pass0(List<Token> tokenList)
{
List<List<Token>> opcodes = new List<List<Token>>();
int value;
List<Token> currentOp;
string current;
for (int i = 0; i < tokenList.Count; i++)
{
current = tokenList[i].text;
if (Machine.Opcodes.ContainsKey(current))
{
currentOp = new List<Token>();
value = Machine.Opcodes[current].OperandCount;
Print.Msg("Opcode: "+current+" with "+value+" operands");
currentOp.Add(tokenList[i]);
for (int j=0; j < value; j++)
{
i++;
currentOp.Add(tokenList[i]);
}
opcodes.Add(currentOp);
}
else switch (current)
{
case "stack":
i++;
value = tokenList[i].text.ParseMaybeHex();
Machine.Settings["stack"] = Math.Max(value, Machine.Settings["stack"]);
Print.Msg("Set stack size: " + Machine.Settings["stack"]);
break;
case "ext":
i++;
value = tokenList[i].text.ParseMaybeHex();
Machine.Settings["ext"] = Math.Max(value, Machine.Settings["ext"]);
Print.Msg("Set EXT size: " + Machine.Settings["ext"]);
break;
case "var":
i++;
Print.Msg("Reserving RAM space for variable initalised to: "+tokenList[i].text);
break;
case "const":
i++;
Print.Msg("Reserving ROM space for constant set to: "+tokenList[i].text);
break;
case "reserve":
i++;
value = tokenList[i].text.ParseMaybeHex();
Print.Msg("Reserving uninitialised RAM space: "+tokenList[i].text);
break;
case "fn":
currentOp = new List<Token>();
string fname = tokenList[i+1].text;
tokenList[i].label = fname;
currentOp.Add(tokenList[i]);
opcodes.Add(currentOp);
i+=2;
value = tokenList[i].text.ParseMaybeHex();
Print.Msg("New function labelled: "+fname+" with "+value+" arguments");
break;
default:
if (IsLabel(current))
{
Print.Msg("New label: "+current.StripPrefix(1));
tokenList[i+1].label = current.StripPrefix(1);
}
else
{
Print.Error("Unknown: "+current);
}
break;
}
}
return opcodes;
}
private List<Token> DoInclusions(List<Token> tokenList)
{
List<string> guard = new List<string>();
guard.Add(Path.GetFullPath(_sourceFile));
int incIndex = tokenList.FindIndex(t => t.text == "include");
while (incIndex > -1)
{
string inclusion = Path.GetFullPath(tokenList[incIndex + 1].text);
tokenList.RemoveRange(incIndex, 2);
if (!File.Exists(inclusion))
{
Print.Error("Included file not found: "+inclusion);
}
else if (guard.Contains(inclusion))
{
Print.Warn("File already included: "+inclusion);
}
else
{
guard.Add(inclusion);
List<Token> incFile = Tokenise(File.ReadAllText(inclusion));
tokenList.InsertRange(incIndex, incFile);
Print.Msg("Included file: "+inclusion);
}
incIndex = tokenList.FindIndex(t => t.text == "include");
}
return tokenList;
}
private List<Token> Tokenise(string s)
{
var tokens = new List<Token>();
StringBuilder token = new StringBuilder();
StringBuilder escape = new StringBuilder();
bool inString = false;
bool inEscape = false;
bool inComment = false;
int linestart = 0;
int row = 0; // current row starts at s[linestart]
int col = -1;
int offset = -1; // currently considered character is at s[offset]
foreach (char c in s)
{
offset++;
if (c == '\n')
{
row++;
col = 0;
linestart = offset;
if (inComment) inComment = false;
}
else
{
col++;
}
if (inComment) continue;
if (inEscape)
{
if (c == ']')
{
inEscape = false;
switch (escape.ToString())
{
case "n": token.Append('\n'); break;
case "q": token.Append('"'); break;
case "lb": token.Append('['); break;
case "rb": token.Append(']'); break;
default: break;
}
escape.Clear();
}
else
{
escape.Append(c);
}
}
else if (inString)
{
switch (c)
{
case '"':
tokens.Add(new Token(token.ToString(), row, col, offset, linestart, true));
token.Clear();
inString = false;
break;
case '[':
inEscape = true;
break;
default:
token.Append(c);
break;
}
}
else if (Char.IsWhiteSpace(c))
{
if (token.Length > 0) tokens.Add(new Token(token.ToString(), row, col, offset, linestart));
token.Clear();
}
else
{
switch (c)
{
case ';':
if (token.Length > 0) tokens.Add(new Token(token.ToString(), row, col, offset, linestart));
token.Clear();
inComment = true;
break;
case '"':
inString = true;
break;
default:
token.Append(c);
break;
}
}
}
if (token.Length > 0) tokens.Add(new Token(token.ToString(), row, col, offset, linestart));
return tokens;
}
}
}
| |
// $Id: mxEdgeStyle.cs,v 1.28 2010-06-10 08:57:30 gaudenz Exp $
// Copyright (c) 2007-2008, Gaudenz Alder
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace com.mxgraph
{
/// <summary>
/// Defines the requirements for an edge style function. At the time
/// the function is called, the result array contains a placeholder (null)
/// for the first absolute point, that is, the point where the edge and
/// source terminal are connected. The implementation of the style then
/// adds all intermediate waypoints except for the last point, that is,
/// the connection point between the edge and the target terminal. The
/// first ant the last point in the result array are then replaced with
/// mxPoints that take into account the terminal's perimeter and next point
/// on the edge.
/// </summary>
/// <param name="state">Cell state that represents the edge to be updated.</param>
/// <param name="source">Cell state that represents the source terminal.</param>
/// <param name="target">Cell state that represents the target terminal.</param>
/// <param name="points">List of relative control points.</param>
/// <param name="result">Array of points that represent the actual points of the
/// edge.</param>
public delegate void mxEdgeStyleFunction(mxCellState state, mxCellState source,
mxCellState target, List<mxPoint> points, List<mxPoint> result);
/// <summary>
/// Provides various edge styles to be used as the values for
/// mxConstants.STYLE_EDGE in a cell style.
/// </summary>
public class mxEdgeStyle
{
/// <summary>
/// Implements an entity relation style for edges (as used in database
/// schema diagrams).
/// </summary>
public static mxEdgeStyleFunction EntityRelation = delegate(
mxCellState state, mxCellState source,
mxCellState target, List<mxPoint> points,
List<mxPoint> result)
{
mxGraphView view = state.View;
mxIGraphModel model = view.Graph.Model;
double segment = mxUtils.GetDouble(state.Style,
mxConstants.STYLE_SEGMENT, mxConstants.ENTITY_SEGMENT) *
state.View.Scale;
mxPoint p0 = state.AbsolutePoints[0];
mxPoint pe = state.AbsolutePoints[state.AbsolutePointCount() - 1];
bool isSourceLeft = false;
if (p0 != null)
{
source = new mxCellState();
source.X = p0.X;
source.Y = p0.Y;
}
else if (source != null)
{
mxGeometry sourceGeometry = model.GetGeometry(source.Cell);
if (sourceGeometry.Relative)
{
isSourceLeft = sourceGeometry.X <= 0.5;
}
else if (target != null)
{
isSourceLeft = target.X + target.Width < source
.X;
}
}
bool isTargetLeft = true;
if (pe != null)
{
target = new mxCellState();
target.X = pe.X;
target.Y = pe.Y;
}
else if (target != null)
{
mxGeometry targetGeometry = model.GetGeometry(target.Cell);
if (targetGeometry.Relative)
{
isTargetLeft = targetGeometry.X <= 0.5;
}
else if (source != null)
{
isTargetLeft = source.X + source.Width < target
.X;
}
}
if (source != null && target != null)
{
double x0 = (isSourceLeft) ? source.X : source.X
+ source.Width;
double y0 = view.GetRoutingCenterY(source);
double xe = (isTargetLeft) ? target.X : target.X
+ target.Width;
double ye = view.GetRoutingCenterY(target);
double seg = segment;
double dx = (isSourceLeft) ? -seg : seg;
mxPoint dep = new mxPoint(x0 + dx, y0);
result.Add(dep);
dx = (isTargetLeft) ? -seg : seg;
mxPoint arr = new mxPoint(xe + dx, ye);
// Adds intermediate points if both go out on same side
if (isSourceLeft == isTargetLeft)
{
double x = (isSourceLeft) ? Math.Min(x0, xe) - segment : Math
.Max(x0, xe)
+ segment;
result.Add(new mxPoint(x, y0));
result.Add(new mxPoint(x, ye));
}
else if ((dep.X < arr.X) == isSourceLeft)
{
double midY = y0 + (ye - y0) / 2;
result.Add(new mxPoint(dep.X, midY));
result.Add(new mxPoint(arr.X, midY));
}
result.Add(arr);
}
};
/// <summary>
/// Implements a self-reference, aka. loop.
/// </summary>
public static mxEdgeStyleFunction Loop = delegate(
mxCellState state, mxCellState source,
mxCellState target, List<mxPoint> points,
List<mxPoint> result)
{
if (source != null)
{
mxGraphView view = state.View;
mxGraph graph = view.Graph;
mxPoint pt = (points != null && points.Count > 0) ? points[0] : null;
if (pt != null)
{
pt = view.TransformControlPoint(state, pt);
if (source.Contains(pt.X, pt.Y))
{
pt = null;
}
}
double x = 0;
double dx = 0;
double y = 0;
double dy = 0;
double seg = mxUtils.GetDouble(state.Style,
mxConstants.STYLE_SEGMENT, graph.GridSize)
* view.Scale;
String dir = mxUtils.GetString(state.Style,
mxConstants.STYLE_DIRECTION,
mxConstants.DIRECTION_WEST);
if (dir.Equals(mxConstants.DIRECTION_NORTH)
|| dir.Equals(mxConstants.DIRECTION_SOUTH))
{
x = view.GetRoutingCenterX(source);
dx = seg;
}
else
{
y = view.GetRoutingCenterY(source);
dy = seg;
}
if (pt == null ||
pt.X < source.X ||
pt.X > source.X + source.Width)
{
if (pt != null)
{
x = pt.X;
dy = Math.Max(Math.Abs(y - pt.Y), dy);
}
else
{
if (dir.Equals(mxConstants.DIRECTION_NORTH))
{
y = source.Y - 2 * dx;
}
else if (dir.Equals(mxConstants.DIRECTION_SOUTH))
{
y = source.Y + source.Height + 2 * dx;
}
else if (dir.Equals(mxConstants.DIRECTION_EAST))
{
x = source.X - 2 * dy;
}
else
{
x = source.X + source.Width + 2 * dy;
}
}
}
else if (pt != null)
{
x = view.GetRoutingCenterX(source);
dx = Math.Max(Math.Abs(x - pt.X), dy);
y = pt.Y;
dy = 0;
}
result.Add(new mxPoint(x - dx, y - dy));
result.Add(new mxPoint(x + dx, y + dy));
}
};
/// <summary>
/// Uses either SideToSide or TopToBottom depending on the horizontal
/// flag in the cell style. SideToSide is used if horizontal is true or
/// unspecified.
/// </summary>
public static mxEdgeStyleFunction ElbowConnector = delegate(
mxCellState state, mxCellState source,
mxCellState target, List<mxPoint> points,
List<mxPoint> result)
{
mxPoint pt = (points != null && points.Count > 0) ? points[0] : null;
bool vertical = false;
bool horizontal = false;
if (source != null && target != null)
{
if (pt != null)
{
double left = Math.Min(source.X, target.X);
double right = Math.Max(source.X + source.Width,
target.X + target.Width);
double top = Math.Min(source.Y, target.Y);
double bottom = Math.Max(source.Y + source.Height,
target.Y + target.Height);
pt = state.View.TransformControlPoint(state, pt);
vertical = pt.Y < top || pt.Y > bottom;
horizontal = pt.X < left || pt.X > right;
}
else
{
double left = Math.Max(source.X, target.X);
double right = Math.Min(source.X + source.Width,
target.X + target.Width);
vertical = left == right;
if (!vertical)
{
double top = Math.Max(source.Y, target.Y);
double bottom = Math.Min(source.Y
+ source.Height, target.Y
+ target.Height);
horizontal = top == bottom;
}
}
}
if (!horizontal && (vertical ||
mxUtils.GetString(state.Style, mxConstants.STYLE_ELBOW, "").Equals(mxConstants.ELBOW_VERTICAL)))
{
mxEdgeStyle.TopToBottom(state, source, target, points, result);
}
else
{
mxEdgeStyle.SideToSide(state, source, target, points, result);
}
};
/// <summary>
/// Implements a vertical elbow edge.
/// </summary>
public static mxEdgeStyleFunction SideToSide = delegate(
mxCellState state, mxCellState source,
mxCellState target, List<mxPoint> points,
List<mxPoint> result)
{
mxGraphView view = state.View;
mxPoint pt = (points != null && points.Count > 0) ? points[0] : null;
mxPoint p0 = state.AbsolutePoints[0];
mxPoint pe = state.AbsolutePoints[state.AbsolutePointCount() - 1];
if (pt != null)
{
pt = view.TransformControlPoint(state, pt);
}
if (p0 != null)
{
source = new mxCellState();
source.X = p0.X;
source.Y = p0.Y;
}
if (pe != null)
{
target = new mxCellState();
target.X = pe.X;
target.Y = pe.Y;
}
if (source != null && target != null)
{
double l = Math.Max(source.X, target.X);
double r = Math.Min(source.X + source.Width,
target.X + target.Width);
double x = (pt != null) ? pt.X : r + (l - r) / 2;
double y1 = view.GetRoutingCenterY(source);
double y2 = view.GetRoutingCenterY(target);
if (pt != null)
{
if (pt.Y >= source.Y &&
pt.Y <= source.Y + source.Height)
{
y1 = pt.Y;
}
if (pt.Y >= target.Y &&
pt.Y <= target.Y + target.Height)
{
y2 = pt.Y;
}
}
if (!target.Contains(x, y1) &&
!source.Contains(x, y1))
{
result.Add(new mxPoint(x, y1));
}
if (!target.Contains(x, y2) &&
!source.Contains(x, y2))
{
result.Add(new mxPoint(x, y2));
}
if (result.Count == 1)
{
if (pt != null)
{
result.Add(new mxPoint(x, pt.Y));
}
else
{
double t = Math.Max(source.Y, target.Y);
double b = Math.Min(source.Y + source.Height,
target.Y + target.Height);
result.Add(new mxPoint(x, t + (b - t) / 2));
}
}
}
};
/// <summary>
/// Implements a horizontal elbow edge.
/// </summary>
public static mxEdgeStyleFunction TopToBottom = delegate(
mxCellState state, mxCellState source,
mxCellState target, List<mxPoint> points,
List<mxPoint> result)
{
mxGraphView view = state.View;
mxPoint pt = (points != null && points.Count > 0) ? points[0] : null;
mxPoint p0 = state.AbsolutePoints[0];
mxPoint pe = state.AbsolutePoints[state.AbsolutePointCount() - 1];
if (pt != null)
{
pt = view.TransformControlPoint(state, pt);
}
if (p0 != null)
{
source = new mxCellState();
source.X = p0.X;
source.Y = p0.Y;
}
if (pe != null)
{
target = new mxCellState();
target.X = pe.X;
target.Y = pe.Y;
}
if (source != null && target != null)
{
double t = Math.Max(source.Y, target.Y);
double b = Math.Min(source.Y + source.Height,
target.Y + target.Height);
double x = view.GetRoutingCenterX(source);
if (pt != null &&
pt.X >= source.X &&
pt.X <= source.X + source.Width)
{
x = pt.X;
}
double y = (pt != null) ? pt.Y : b + (t - b) / 2;
if (!target.Contains(x, y) &&
!source.Contains(x, y))
{
result.Add(new mxPoint(x, y));
}
if (pt != null &&
pt.X >= target.X &&
pt.X <= target.X + target.Width)
{
x = pt.X;
}
else
{
x = view.GetRoutingCenterX(target);
}
if (!target.Contains(x, y) &&
!source.Contains(x, y))
{
result.Add(new mxPoint(x, y));
}
if (result.Count == 1)
{
if (pt != null)
{
result.Add(new mxPoint(pt.X, y));
}
else
{
double l = Math.Max(source.X, target.X);
double r = Math.Min(source.X + source.Width,
target.X + target.Width);
result.Add(new mxPoint(l + (r - l) / 2, y));
}
}
}
};
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprPercentilesLongitudEstaturaEdad class.
/// </summary>
[Serializable]
public partial class AprPercentilesLongitudEstaturaEdadCollection : ActiveList<AprPercentilesLongitudEstaturaEdad, AprPercentilesLongitudEstaturaEdadCollection>
{
public AprPercentilesLongitudEstaturaEdadCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprPercentilesLongitudEstaturaEdadCollection</returns>
public AprPercentilesLongitudEstaturaEdadCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprPercentilesLongitudEstaturaEdad o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_PercentilesLongitudEstaturaEdad table.
/// </summary>
[Serializable]
public partial class AprPercentilesLongitudEstaturaEdad : ActiveRecord<AprPercentilesLongitudEstaturaEdad>, IActiveRecord
{
#region .ctors and Default Settings
public AprPercentilesLongitudEstaturaEdad()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprPercentilesLongitudEstaturaEdad(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprPercentilesLongitudEstaturaEdad(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprPercentilesLongitudEstaturaEdad(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_PercentilesLongitudEstaturaEdad", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "Sexo";
colvarSexo.DataType = DbType.Int32;
colvarSexo.MaxLength = 0;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = false;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
colvarSexo.DefaultSetting = @"";
colvarSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "Edad";
colvarEdad.DataType = DbType.Int32;
colvarEdad.MaxLength = 0;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = false;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
colvarEdad.DefaultSetting = @"";
colvarEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarL = new TableSchema.TableColumn(schema);
colvarL.ColumnName = "L";
colvarL.DataType = DbType.Decimal;
colvarL.MaxLength = 0;
colvarL.AutoIncrement = false;
colvarL.IsNullable = false;
colvarL.IsPrimaryKey = false;
colvarL.IsForeignKey = false;
colvarL.IsReadOnly = false;
colvarL.DefaultSetting = @"";
colvarL.ForeignKeyTableName = "";
schema.Columns.Add(colvarL);
TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema);
colvarM.ColumnName = "M";
colvarM.DataType = DbType.Decimal;
colvarM.MaxLength = 0;
colvarM.AutoIncrement = false;
colvarM.IsNullable = false;
colvarM.IsPrimaryKey = false;
colvarM.IsForeignKey = false;
colvarM.IsReadOnly = false;
colvarM.DefaultSetting = @"";
colvarM.ForeignKeyTableName = "";
schema.Columns.Add(colvarM);
TableSchema.TableColumn colvarS = new TableSchema.TableColumn(schema);
colvarS.ColumnName = "S";
colvarS.DataType = DbType.Decimal;
colvarS.MaxLength = 0;
colvarS.AutoIncrement = false;
colvarS.IsNullable = false;
colvarS.IsPrimaryKey = false;
colvarS.IsForeignKey = false;
colvarS.IsReadOnly = false;
colvarS.DefaultSetting = @"";
colvarS.ForeignKeyTableName = "";
schema.Columns.Add(colvarS);
TableSchema.TableColumn colvarP01 = new TableSchema.TableColumn(schema);
colvarP01.ColumnName = "P01";
colvarP01.DataType = DbType.Decimal;
colvarP01.MaxLength = 0;
colvarP01.AutoIncrement = false;
colvarP01.IsNullable = false;
colvarP01.IsPrimaryKey = false;
colvarP01.IsForeignKey = false;
colvarP01.IsReadOnly = false;
colvarP01.DefaultSetting = @"";
colvarP01.ForeignKeyTableName = "";
schema.Columns.Add(colvarP01);
TableSchema.TableColumn colvarP1 = new TableSchema.TableColumn(schema);
colvarP1.ColumnName = "P1";
colvarP1.DataType = DbType.Decimal;
colvarP1.MaxLength = 0;
colvarP1.AutoIncrement = false;
colvarP1.IsNullable = false;
colvarP1.IsPrimaryKey = false;
colvarP1.IsForeignKey = false;
colvarP1.IsReadOnly = false;
colvarP1.DefaultSetting = @"";
colvarP1.ForeignKeyTableName = "";
schema.Columns.Add(colvarP1);
TableSchema.TableColumn colvarP3 = new TableSchema.TableColumn(schema);
colvarP3.ColumnName = "P3";
colvarP3.DataType = DbType.Decimal;
colvarP3.MaxLength = 0;
colvarP3.AutoIncrement = false;
colvarP3.IsNullable = false;
colvarP3.IsPrimaryKey = false;
colvarP3.IsForeignKey = false;
colvarP3.IsReadOnly = false;
colvarP3.DefaultSetting = @"";
colvarP3.ForeignKeyTableName = "";
schema.Columns.Add(colvarP3);
TableSchema.TableColumn colvarP5 = new TableSchema.TableColumn(schema);
colvarP5.ColumnName = "P5";
colvarP5.DataType = DbType.Decimal;
colvarP5.MaxLength = 0;
colvarP5.AutoIncrement = false;
colvarP5.IsNullable = false;
colvarP5.IsPrimaryKey = false;
colvarP5.IsForeignKey = false;
colvarP5.IsReadOnly = false;
colvarP5.DefaultSetting = @"";
colvarP5.ForeignKeyTableName = "";
schema.Columns.Add(colvarP5);
TableSchema.TableColumn colvarP10 = new TableSchema.TableColumn(schema);
colvarP10.ColumnName = "P10";
colvarP10.DataType = DbType.Decimal;
colvarP10.MaxLength = 0;
colvarP10.AutoIncrement = false;
colvarP10.IsNullable = false;
colvarP10.IsPrimaryKey = false;
colvarP10.IsForeignKey = false;
colvarP10.IsReadOnly = false;
colvarP10.DefaultSetting = @"";
colvarP10.ForeignKeyTableName = "";
schema.Columns.Add(colvarP10);
TableSchema.TableColumn colvarP15 = new TableSchema.TableColumn(schema);
colvarP15.ColumnName = "P15";
colvarP15.DataType = DbType.Decimal;
colvarP15.MaxLength = 0;
colvarP15.AutoIncrement = false;
colvarP15.IsNullable = false;
colvarP15.IsPrimaryKey = false;
colvarP15.IsForeignKey = false;
colvarP15.IsReadOnly = false;
colvarP15.DefaultSetting = @"";
colvarP15.ForeignKeyTableName = "";
schema.Columns.Add(colvarP15);
TableSchema.TableColumn colvarP25 = new TableSchema.TableColumn(schema);
colvarP25.ColumnName = "P25";
colvarP25.DataType = DbType.Decimal;
colvarP25.MaxLength = 0;
colvarP25.AutoIncrement = false;
colvarP25.IsNullable = false;
colvarP25.IsPrimaryKey = false;
colvarP25.IsForeignKey = false;
colvarP25.IsReadOnly = false;
colvarP25.DefaultSetting = @"";
colvarP25.ForeignKeyTableName = "";
schema.Columns.Add(colvarP25);
TableSchema.TableColumn colvarP50 = new TableSchema.TableColumn(schema);
colvarP50.ColumnName = "P50";
colvarP50.DataType = DbType.Decimal;
colvarP50.MaxLength = 0;
colvarP50.AutoIncrement = false;
colvarP50.IsNullable = false;
colvarP50.IsPrimaryKey = false;
colvarP50.IsForeignKey = false;
colvarP50.IsReadOnly = false;
colvarP50.DefaultSetting = @"";
colvarP50.ForeignKeyTableName = "";
schema.Columns.Add(colvarP50);
TableSchema.TableColumn colvarP75 = new TableSchema.TableColumn(schema);
colvarP75.ColumnName = "P75";
colvarP75.DataType = DbType.Decimal;
colvarP75.MaxLength = 0;
colvarP75.AutoIncrement = false;
colvarP75.IsNullable = false;
colvarP75.IsPrimaryKey = false;
colvarP75.IsForeignKey = false;
colvarP75.IsReadOnly = false;
colvarP75.DefaultSetting = @"";
colvarP75.ForeignKeyTableName = "";
schema.Columns.Add(colvarP75);
TableSchema.TableColumn colvarP85 = new TableSchema.TableColumn(schema);
colvarP85.ColumnName = "P85";
colvarP85.DataType = DbType.Decimal;
colvarP85.MaxLength = 0;
colvarP85.AutoIncrement = false;
colvarP85.IsNullable = false;
colvarP85.IsPrimaryKey = false;
colvarP85.IsForeignKey = false;
colvarP85.IsReadOnly = false;
colvarP85.DefaultSetting = @"";
colvarP85.ForeignKeyTableName = "";
schema.Columns.Add(colvarP85);
TableSchema.TableColumn colvarP90 = new TableSchema.TableColumn(schema);
colvarP90.ColumnName = "P90";
colvarP90.DataType = DbType.Decimal;
colvarP90.MaxLength = 0;
colvarP90.AutoIncrement = false;
colvarP90.IsNullable = false;
colvarP90.IsPrimaryKey = false;
colvarP90.IsForeignKey = false;
colvarP90.IsReadOnly = false;
colvarP90.DefaultSetting = @"";
colvarP90.ForeignKeyTableName = "";
schema.Columns.Add(colvarP90);
TableSchema.TableColumn colvarP95 = new TableSchema.TableColumn(schema);
colvarP95.ColumnName = "P95";
colvarP95.DataType = DbType.Decimal;
colvarP95.MaxLength = 0;
colvarP95.AutoIncrement = false;
colvarP95.IsNullable = false;
colvarP95.IsPrimaryKey = false;
colvarP95.IsForeignKey = false;
colvarP95.IsReadOnly = false;
colvarP95.DefaultSetting = @"";
colvarP95.ForeignKeyTableName = "";
schema.Columns.Add(colvarP95);
TableSchema.TableColumn colvarP97 = new TableSchema.TableColumn(schema);
colvarP97.ColumnName = "P97";
colvarP97.DataType = DbType.Decimal;
colvarP97.MaxLength = 0;
colvarP97.AutoIncrement = false;
colvarP97.IsNullable = false;
colvarP97.IsPrimaryKey = false;
colvarP97.IsForeignKey = false;
colvarP97.IsReadOnly = false;
colvarP97.DefaultSetting = @"";
colvarP97.ForeignKeyTableName = "";
schema.Columns.Add(colvarP97);
TableSchema.TableColumn colvarP99 = new TableSchema.TableColumn(schema);
colvarP99.ColumnName = "P99";
colvarP99.DataType = DbType.Decimal;
colvarP99.MaxLength = 0;
colvarP99.AutoIncrement = false;
colvarP99.IsNullable = false;
colvarP99.IsPrimaryKey = false;
colvarP99.IsForeignKey = false;
colvarP99.IsReadOnly = false;
colvarP99.DefaultSetting = @"";
colvarP99.ForeignKeyTableName = "";
schema.Columns.Add(colvarP99);
TableSchema.TableColumn colvarP999 = new TableSchema.TableColumn(schema);
colvarP999.ColumnName = "P999";
colvarP999.DataType = DbType.Decimal;
colvarP999.MaxLength = 0;
colvarP999.AutoIncrement = false;
colvarP999.IsNullable = false;
colvarP999.IsPrimaryKey = false;
colvarP999.IsForeignKey = false;
colvarP999.IsReadOnly = false;
colvarP999.DefaultSetting = @"";
colvarP999.ForeignKeyTableName = "";
schema.Columns.Add(colvarP999);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_PercentilesLongitudEstaturaEdad",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public int Sexo
{
get { return GetColumnValue<int>(Columns.Sexo); }
set { SetColumnValue(Columns.Sexo, value); }
}
[XmlAttribute("Edad")]
[Bindable(true)]
public int Edad
{
get { return GetColumnValue<int>(Columns.Edad); }
set { SetColumnValue(Columns.Edad, value); }
}
[XmlAttribute("L")]
[Bindable(true)]
public decimal L
{
get { return GetColumnValue<decimal>(Columns.L); }
set { SetColumnValue(Columns.L, value); }
}
[XmlAttribute("M")]
[Bindable(true)]
public decimal M
{
get { return GetColumnValue<decimal>(Columns.M); }
set { SetColumnValue(Columns.M, value); }
}
[XmlAttribute("S")]
[Bindable(true)]
public decimal S
{
get { return GetColumnValue<decimal>(Columns.S); }
set { SetColumnValue(Columns.S, value); }
}
[XmlAttribute("P01")]
[Bindable(true)]
public decimal P01
{
get { return GetColumnValue<decimal>(Columns.P01); }
set { SetColumnValue(Columns.P01, value); }
}
[XmlAttribute("P1")]
[Bindable(true)]
public decimal P1
{
get { return GetColumnValue<decimal>(Columns.P1); }
set { SetColumnValue(Columns.P1, value); }
}
[XmlAttribute("P3")]
[Bindable(true)]
public decimal P3
{
get { return GetColumnValue<decimal>(Columns.P3); }
set { SetColumnValue(Columns.P3, value); }
}
[XmlAttribute("P5")]
[Bindable(true)]
public decimal P5
{
get { return GetColumnValue<decimal>(Columns.P5); }
set { SetColumnValue(Columns.P5, value); }
}
[XmlAttribute("P10")]
[Bindable(true)]
public decimal P10
{
get { return GetColumnValue<decimal>(Columns.P10); }
set { SetColumnValue(Columns.P10, value); }
}
[XmlAttribute("P15")]
[Bindable(true)]
public decimal P15
{
get { return GetColumnValue<decimal>(Columns.P15); }
set { SetColumnValue(Columns.P15, value); }
}
[XmlAttribute("P25")]
[Bindable(true)]
public decimal P25
{
get { return GetColumnValue<decimal>(Columns.P25); }
set { SetColumnValue(Columns.P25, value); }
}
[XmlAttribute("P50")]
[Bindable(true)]
public decimal P50
{
get { return GetColumnValue<decimal>(Columns.P50); }
set { SetColumnValue(Columns.P50, value); }
}
[XmlAttribute("P75")]
[Bindable(true)]
public decimal P75
{
get { return GetColumnValue<decimal>(Columns.P75); }
set { SetColumnValue(Columns.P75, value); }
}
[XmlAttribute("P85")]
[Bindable(true)]
public decimal P85
{
get { return GetColumnValue<decimal>(Columns.P85); }
set { SetColumnValue(Columns.P85, value); }
}
[XmlAttribute("P90")]
[Bindable(true)]
public decimal P90
{
get { return GetColumnValue<decimal>(Columns.P90); }
set { SetColumnValue(Columns.P90, value); }
}
[XmlAttribute("P95")]
[Bindable(true)]
public decimal P95
{
get { return GetColumnValue<decimal>(Columns.P95); }
set { SetColumnValue(Columns.P95, value); }
}
[XmlAttribute("P97")]
[Bindable(true)]
public decimal P97
{
get { return GetColumnValue<decimal>(Columns.P97); }
set { SetColumnValue(Columns.P97, value); }
}
[XmlAttribute("P99")]
[Bindable(true)]
public decimal P99
{
get { return GetColumnValue<decimal>(Columns.P99); }
set { SetColumnValue(Columns.P99, value); }
}
[XmlAttribute("P999")]
[Bindable(true)]
public decimal P999
{
get { return GetColumnValue<decimal>(Columns.P999); }
set { SetColumnValue(Columns.P999, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varSexo,int varEdad,decimal varL,decimal varM,decimal varS,decimal varP01,decimal varP1,decimal varP3,decimal varP5,decimal varP10,decimal varP15,decimal varP25,decimal varP50,decimal varP75,decimal varP85,decimal varP90,decimal varP95,decimal varP97,decimal varP99,decimal varP999)
{
AprPercentilesLongitudEstaturaEdad item = new AprPercentilesLongitudEstaturaEdad();
item.Sexo = varSexo;
item.Edad = varEdad;
item.L = varL;
item.M = varM;
item.S = varS;
item.P01 = varP01;
item.P1 = varP1;
item.P3 = varP3;
item.P5 = varP5;
item.P10 = varP10;
item.P15 = varP15;
item.P25 = varP25;
item.P50 = varP50;
item.P75 = varP75;
item.P85 = varP85;
item.P90 = varP90;
item.P95 = varP95;
item.P97 = varP97;
item.P99 = varP99;
item.P999 = varP999;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,int varSexo,int varEdad,decimal varL,decimal varM,decimal varS,decimal varP01,decimal varP1,decimal varP3,decimal varP5,decimal varP10,decimal varP15,decimal varP25,decimal varP50,decimal varP75,decimal varP85,decimal varP90,decimal varP95,decimal varP97,decimal varP99,decimal varP999)
{
AprPercentilesLongitudEstaturaEdad item = new AprPercentilesLongitudEstaturaEdad();
item.Id = varId;
item.Sexo = varSexo;
item.Edad = varEdad;
item.L = varL;
item.M = varM;
item.S = varS;
item.P01 = varP01;
item.P1 = varP1;
item.P3 = varP3;
item.P5 = varP5;
item.P10 = varP10;
item.P15 = varP15;
item.P25 = varP25;
item.P50 = varP50;
item.P75 = varP75;
item.P85 = varP85;
item.P90 = varP90;
item.P95 = varP95;
item.P97 = varP97;
item.P99 = varP99;
item.P999 = varP999;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn SexoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn EdadColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn LColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn MColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn SColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn P01Column
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn P1Column
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn P3Column
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn P5Column
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn P10Column
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn P15Column
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn P25Column
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn P50Column
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn P75Column
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn P85Column
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn P90Column
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn P95Column
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn P97Column
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn P99Column
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn P999Column
{
get { return Schema.Columns[20]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string Sexo = @"Sexo";
public static string Edad = @"Edad";
public static string L = @"L";
public static string M = @"M";
public static string S = @"S";
public static string P01 = @"P01";
public static string P1 = @"P1";
public static string P3 = @"P3";
public static string P5 = @"P5";
public static string P10 = @"P10";
public static string P15 = @"P15";
public static string P25 = @"P25";
public static string P50 = @"P50";
public static string P75 = @"P75";
public static string P85 = @"P85";
public static string P90 = @"P90";
public static string P95 = @"P95";
public static string P97 = @"P97";
public static string P99 = @"P99";
public static string P999 = @"P999";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
/*
* 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 QuantConnect.Brokerages;
using QuantConnect.Data;
using QuantConnect.Data.Shortable;
using QuantConnect.Interfaces;
using QuantConnect.Orders;
namespace QuantConnect.Algorithm.CSharp
{
/// <summary>
/// Tests that orders are denied if they exceed the max shortable quantity.
/// </summary>
public class ShortableProviderOrdersRejectedRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition
{
private Symbol _spy;
private Symbol _aig;
private readonly List<OrderTicket> _ordersAllowed = new List<OrderTicket>();
private readonly List<OrderTicket> _ordersDenied = new List<OrderTicket>();
private bool _initialize;
private OrderEvent _lastOrderEvent;
private bool _invalidatedAllowedOrder;
private bool _invalidatedNewOrderWithPortfolioHoldings;
public override void Initialize()
{
SetStartDate(2013, 10, 4);
SetEndDate(2013, 10, 11);
SetCash(10000000);
_spy = AddEquity("SPY", Resolution.Minute).Symbol;
_aig = AddEquity("AIG", Resolution.Minute).Symbol;
SetBrokerageModel(new RegressionTestShortableBrokerageModel());
}
public override void OnData(Slice data)
{
if (!_initialize)
{
HandleOrder(LimitOrder(_spy, -1001, 10000m)); // Should be canceled, exceeds the max shortable quantity
HandleOrder(LimitOrder(_spy, -1000, 10000m)); // Allowed, orders at or below 1000 should be accepted
HandleOrder(LimitOrder(_spy, -10, 0.01m)); // Should be canceled, the total quantity we would be short would exceed the max shortable quantity.
_initialize = true;
return;
}
if (!_invalidatedAllowedOrder)
{
if (_ordersAllowed.Count != 1)
{
throw new Exception($"Expected 1 successful order, found: {_ordersAllowed.Count}");
}
if (_ordersDenied.Count != 2)
{
throw new Exception($"Expected 2 failed orders, found: {_ordersDenied.Count}");
}
var allowedOrder = _ordersAllowed[0];
var orderUpdate = new UpdateOrderFields()
{
LimitPrice = 0.01m,
Quantity = -1001,
Tag = "Testing updating and exceeding maximum quantity"
};
var response = allowedOrder.Update(orderUpdate);
if (response.ErrorCode != OrderResponseErrorCode.ExceedsShortableQuantity)
{
throw new Exception($"Expected order to fail due to exceeded shortable quantity, found: {response.ErrorCode.ToString()}");
}
var cancelResponse = allowedOrder.Cancel();
if (cancelResponse.IsError)
{
throw new Exception("Expected to be able to cancel open order after bad qty update");
}
_invalidatedAllowedOrder = true;
_ordersDenied.Clear();
_ordersAllowed.Clear();
return;
}
if (!_invalidatedNewOrderWithPortfolioHoldings)
{
HandleOrder(MarketOrder(_spy, -1000)); // Should succeed, no holdings and no open orders to stop this
var spyShares = Portfolio[_spy].Quantity;
if (spyShares != -1000m)
{
throw new Exception($"Expected -1000 shares in portfolio, found: {spyShares}");
}
HandleOrder(LimitOrder(_spy, -1, 0.01m)); // Should fail, portfolio holdings are at the max shortable quantity.
if (_ordersDenied.Count != 1)
{
throw new Exception($"Expected limit order to fail due to existing holdings, but found {_ordersDenied.Count} failures");
}
_ordersAllowed.Clear();
_ordersDenied.Clear();
HandleOrder(MarketOrder(_aig, -1001));
if (_ordersAllowed.Count != 1)
{
throw new Exception($"Expected market order of -1001 BAC to not fail");
}
_invalidatedNewOrderWithPortfolioHoldings = true;
}
}
public override void OnOrderEvent(OrderEvent orderEvent)
{
_lastOrderEvent = orderEvent;
}
private void HandleOrder(OrderTicket orderTicket)
{
if (orderTicket.SubmitRequest.Status == OrderRequestStatus.Error)
{
if (_lastOrderEvent == null || _lastOrderEvent.Status != OrderStatus.Invalid)
{
throw new Exception($"Expected order event with invalid status for ticket {orderTicket}");
}
_lastOrderEvent = null;
_ordersDenied.Add(orderTicket);
return;
}
_ordersAllowed.Add(orderTicket);
}
private class RegressionTestShortableProvider : LocalDiskShortableProvider
{
public RegressionTestShortableProvider() : base(SecurityType.Equity, "testbrokerage", Market.USA)
{
}
}
public class RegressionTestShortableBrokerageModel : DefaultBrokerageModel
{
public RegressionTestShortableBrokerageModel() : base()
{
ShortableProvider = new RegressionTestShortableProvider();
}
}
/// <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", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-1.623%"},
{"Drawdown", "0.100%"},
{"Expectancy", "0"},
{"Net Profit", "-0.034%"},
{"Sharpe Ratio", "-1.535"},
{"Probabilistic Sharpe Ratio", "33.979%"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.002"},
{"Beta", "-0.022"},
{"Annual Standard Deviation", "0.004"},
{"Annual Variance", "0"},
{"Information Ratio", "-2.082"},
{"Tracking Error", "0.179"},
{"Treynor Ratio", "0.269"},
{"Total Fees", "$10.01"},
{"Estimated Strategy Capacity", "$99000000.00"},
{"Lowest Capacity Asset", "AIG R735QTJ8XC9X"},
{"Fitness Score", "0"},
{"Kelly Criterion Estimate", "0"},
{"Kelly Criterion Probability Value", "0"},
{"Sortino Ratio", "-4.826"},
{"Return Over Maximum Drawdown", "-21.709"},
{"Portfolio Turnover", "0.003"},
{"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", "3ac2d7a61f71c1345eb569e30cc2834c"}
};
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#region Using directives
using System;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Collections.Generic;
#endregion
namespace Microsoft.Management.Infrastructure.CimCmdlets
{
/// <summary>
/// <para>
/// The Cmdlet retrieves instances connected to the given instance, which
/// is called the source instance, via a given association. In an
/// association each instance has a named role, and the same instance can
/// participate in an association in different roles. Hence, the Cmdlet
/// takes SourceRole and AssociatorRole parameters in addition to the
/// Association parameter.
/// </para>
/// </summary>
[Cmdlet(VerbsCommon.Get,
GetCimAssociatedInstanceCommand.Noun,
DefaultParameterSetName = CimBaseCommand.ComputerSetName,
HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227958")]
[OutputType(typeof(CimInstance))]
public class GetCimAssociatedInstanceCommand : CimBaseCommand
{
#region constructor
/// <summary>
/// Constructor.
/// </summary>
public GetCimAssociatedInstanceCommand()
: base(parameters, parameterSets)
{
DebugHelper.WriteLogEx();
}
#endregion
#region parameters
/// <summary>
/// The following is the definition of the input parameter "Association".
/// Specifies the class name of the association to be traversed from the
/// SourceRole to AssociatorRole.
/// </summary>
[Parameter(
Position = 1,
ValueFromPipelineByPropertyName = true)]
public string Association
{
get { return association; }
set { association = value; }
}
private string association;
/// <summary>
/// The following is the definition of the input parameter "ResultClassName".
/// Specifies the class name of the result class name, which associated with
/// the given instance.
/// </summary>
[Parameter]
public string ResultClassName
{
get { return resultClassName; }
set { resultClassName = value; }
}
private string resultClassName;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "InputObject".
/// Provides the instance from which the association traversal is to begin.
/// </para>
/// </summary>
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true)]
[Alias(CimBaseCommand.AliasCimInstance)]
public CimInstance InputObject
{
get { return cimInstance; }
set
{
cimInstance = value;
base.SetParameter(value, nameCimInstance);
}
}
/// <summary>
/// Property for internal usage purpose.
/// </summary>
internal CimInstance CimInstance
{
get { return cimInstance; }
}
private CimInstance cimInstance;
/// <summary>
/// The following is the definition of the input parameter "Namespace".
/// Identifies the Namespace in which the source class, indicated by ClassName,
/// is registered.
/// </summary>
[Parameter(ValueFromPipelineByPropertyName = true)]
public string Namespace
{
get { return nameSpace; }
set { nameSpace = value; }
}
private string nameSpace;
/// <summary>
/// The following is the definition of the input parameter "OperationTimeoutSec".
/// Specifies the operation timeout after which the client operation should be
/// canceled. The default is the CimSession operation timeout. If this parameter
/// is specified, then this value takes precedence over the CimSession
/// OperationTimeout.
/// </summary>
[Alias(AliasOT)]
[Parameter(ValueFromPipelineByPropertyName = true)]
public UInt32 OperationTimeoutSec
{
get { return operationTimeout; }
set { operationTimeout = value; }
}
private UInt32 operationTimeout;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ResourceUri".
/// Define the Resource Uri for which the instances are retrieved.
/// </para>
/// </summary>
[Parameter]
public Uri ResourceUri
{
get { return resourceUri; }
set
{
this.resourceUri = value;
base.SetParameter(value, nameResourceUri);
}
}
private Uri resourceUri;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies the name of the computer where the source instance is stored and
/// where the association traversal should begin.
/// </para>
/// <para>
/// This is an optional parameter and if it is not provided, the default value
/// will be "localhost".
/// </para>
/// </summary>
[Alias(AliasCN, AliasServerName)]
[Parameter(
ParameterSetName = ComputerSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName
{
get { return computerName; }
set
{
computerName = value;
base.SetParameter(value, nameComputerName);
}
}
private string[] computerName;
/// <summary>
/// The following is the definition of the input parameter "CimSession".
/// Identifies the CimSession which is to be used to retrieve the instances.
/// </summary>
[Parameter(
Mandatory = true,
ValueFromPipeline = true,
ParameterSetName = SessionSetName)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public Microsoft.Management.Infrastructure.CimSession[] CimSession
{
get { return cimSession; }
set
{
cimSession = value;
base.SetParameter(value, nameCimSession);
}
}
private Microsoft.Management.Infrastructure.CimSession[] cimSession;
/// <summary>
/// <para>
/// The following is the definition of the input parameter "KeyOnly".
/// Indicates that only key properties of the retrieved instances should be
/// returned to the client.
/// </para>
/// </summary>
[Parameter]
public SwitchParameter KeyOnly
{
get { return keyOnly; }
set { keyOnly = value; }
}
private SwitchParameter keyOnly;
#endregion
#region cmdlet methods
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
this.CmdletOperation = new CmdletOperationBase(this);
this.AtBeginProcess = false;
}
/// <summary>
/// ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
base.CheckParameterSet();
CimGetAssociatedInstance operation = this.GetOperationAgent();
if (operation == null)
{
operation = this.CreateOperationAgent();
}
operation.GetCimAssociatedInstance(this);
operation.ProcessActions(this.CmdletOperation);
}
/// <summary>
/// EndProcessing method.
/// </summary>
protected override void EndProcessing()
{
CimGetAssociatedInstance operation = this.GetOperationAgent();
if (operation != null)
operation.ProcessRemainActions(this.CmdletOperation);
}
#endregion
#region helper methods
/// <summary>
/// <para>
/// Get <see cref="CimGetAssociatedInstance"/> object, which is
/// used to delegate all Get-CimAssociatedInstance operations.
/// </para>
/// </summary>
CimGetAssociatedInstance GetOperationAgent()
{
return this.AsyncOperation as CimGetAssociatedInstance;
}
/// <summary>
/// <para>
/// Create <see cref="CimGetAssociatedInstance"/> object, which is
/// used to delegate all Get-CimAssociatedInstance operations.
/// </para>
/// </summary>
/// <returns></returns>
CimGetAssociatedInstance CreateOperationAgent()
{
this.AsyncOperation = new CimGetAssociatedInstance();
return GetOperationAgent();
}
#endregion
#region internal const strings
/// <summary>
/// Noun of current cmdlet.
/// </summary>
internal const string Noun = @"CimAssociatedInstance";
#endregion
#region private members
#region const string of parameter names
internal const string nameCimInstance = "InputObject";
internal const string nameComputerName = "ComputerName";
internal const string nameCimSession = "CimSession";
internal const string nameResourceUri = "ResourceUri";
#endregion
/// <summary>
/// Static parameter definition entries.
/// </summary>
static Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new Dictionary<string, HashSet<ParameterDefinitionEntry>>
{
{
nameComputerName, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false),
}
},
{
nameCimSession, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true),
}
},
{
nameCimInstance, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, true),
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true),
}
},
{
nameResourceUri, new HashSet<ParameterDefinitionEntry> {
new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false),
new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, false),
}
},
};
/// <summary>
/// Static parameter set entries.
/// </summary>
static Dictionary<string, ParameterSetEntry> parameterSets = new Dictionary<string, ParameterSetEntry>
{
{ CimBaseCommand.SessionSetName, new ParameterSetEntry(2, false) },
{ CimBaseCommand.ComputerSetName, new ParameterSetEntry(1, true) },
};
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Provides access to configuration variables for a repository.
/// </summary>
public class Configuration : IDisposable,
IEnumerable<ConfigurationEntry<string>>
{
private readonly FilePath repoConfigPath;
private readonly FilePath globalConfigPath;
private readonly FilePath xdgConfigPath;
private readonly FilePath systemConfigPath;
private ConfigurationSafeHandle configHandle;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Configuration()
{ }
internal Configuration(
Repository repository,
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation,
string systemConfigurationFileLocation)
{
if (repositoryConfigurationFileLocation != null)
{
repoConfigPath = NormalizeConfigPath(repositoryConfigurationFileLocation);
}
globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global();
xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg();
systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system();
Init(repository);
}
private void Init(Repository repository)
{
configHandle = Proxy.git_config_new();
if (repository != null)
{
//TODO: push back this logic into libgit2.
// As stated by @carlosmn "having a helper function to load the defaults and then allowing you
// to modify it before giving it to git_repository_open_ext() would be a good addition, I think."
// -- Agreed :)
string repoConfigLocation = Path.Combine(repository.Info.Path, "config");
Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local);
Proxy.git_repository_set_config(repository.Handle, configHandle);
}
else if (repoConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, repoConfigPath, ConfigurationLevel.Local);
}
if (globalConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global);
}
if (xdgConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg);
}
if (systemConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System);
}
}
private FilePath NormalizeConfigPath(FilePath path)
{
if (File.Exists(path.Native))
{
return path;
}
if (!Directory.Exists(path.Native))
{
throw new FileNotFoundException("Cannot find repository configuration file", path.Native);
}
var configPath = Path.Combine(path.Native, "config");
if (File.Exists(configPath))
{
return configPath;
}
var gitConfigPath = Path.Combine(path.Native, ".git", "config");
if (File.Exists(gitConfigPath))
{
return gitConfigPath;
}
throw new FileNotFoundException("Cannot find repository configuration file", path.Native);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(string repositoryConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, null, null, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, null, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a System configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation,
string systemConfigurationFileLocation)
{
return new Configuration(null, repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation);
}
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
[Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string) instead.")]
public Configuration(string globalConfigurationFileLocation)
: this(null, null, globalConfigurationFileLocation, null, null)
{ }
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
[Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string, string) instead.")]
public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation)
: this(null, null, globalConfigurationFileLocation, xdgConfigurationFileLocation, null)
{ }
/// <summary>
/// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </summary>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a system configuration file will be probed.</param>
[Obsolete("This method will be removed in the next release. Please use Configuration.BuildFrom(string, string, string, string) instead.")]
public Configuration(string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation)
: this(null, null, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation)
{ }
/// <summary>
/// Determines which configuration file has been found.
/// </summary>
public virtual bool HasConfig(ConfigurationLevel level)
{
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
return handle != null;
}
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// Saves any open configuration files.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Unset a configuration variable (key and value) in the local configuration.
/// </summary>
/// <param name="key">The key to unset.</param>
public virtual void Unset(string key)
{
Unset(key, ConfigurationLevel.Local);
}
/// <summary>
/// Unset a configuration variable (key and value).
/// </summary>
/// <param name="key">The key to unset.</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Unset(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_delete(h, key);
}
}
internal void UnsetMultivar(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_delete_multivar(h, key);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
configHandle.SafeDispose();
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>(new []{ "core", "bare" }).Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="keyParts">The key parts</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string[] keyParts)
{
Ensure.ArgumentNotNull(keyParts, "keyParts");
return Get<T>(string.Join(".", keyParts));
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [difftool "kdiff3"]
/// path = c:/Program Files/KDiff3/kdiff3.exe
/// </code>
///
/// You would call:
///
/// <code>
/// string where = repo.Config.Get<string>("difftool", "kdiff3", "path").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="firstKeyPart">The first key part</param>
/// <param name="secondKeyPart">The second key part</param>
/// <param name="thirdKeyPart">The third key part</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "thirdKeyPart");
return Get<T>(new[] { firstKeyPart, secondKeyPart, thirdKeyPart });
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
///
/// The first occurence of the key will be returned.
/// </para>
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle snapshot = Snapshot())
{
return Proxy.git_config_get_entry<T>(snapshot, key);
}
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <param name="level">The configuration file into which the key should be searched for</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
if (handle == null)
{
return null;
}
return Proxy.git_config_get_entry<T>(handle, key);
}
}
/// <summary>
/// Get a configuration value for the given key.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/>if not found</returns>
public virtual T GetValueOrDefault<T>(string key)
{
return ValueOrDefault(Get<T>(key), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value</returns>
public virtual T GetValueOrDefault<T>(string key, T defaultValue)
{
return ValueOrDefault(Get<T>(key), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>The configuration value, or the default value for <see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level)
{
return ValueOrDefault(Get<T>(key, level), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValue">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, T defaultValue)
{
return ValueOrDefault(Get<T>(key, level), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <returns>The configuration value, or the default value for<see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts)
{
return ValueOrDefault(Get<T>(keyParts), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts, T defaultValue)
{
return ValueOrDefault(Get<T>(keyParts), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default.</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string key, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(key), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(key, level), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(keyParts), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValueSelector);
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, T defaultValue)
{
return value == null ? defaultValue : value.Value;
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, Func<T> defaultValueSelector)
{
Ensure.ArgumentNotNull(defaultValueSelector, "defaultValueSelector");
return value == null
? defaultValueSelector()
: value.Value;
}
/// <summary>
/// Set a configuration value for a key in the local configuration. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
public virtual void Set<T>(string key, T value)
{
Set(key, value, ConfigurationLevel.Local);
}
/// <summary>
/// Set a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Set<T>(string key, T value, ConfigurationLevel level)
{
Ensure.ArgumentNotNull(value, "value");
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
if (!configurationTypedUpdater.ContainsKey(typeof(T)))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName));
}
configurationTypedUpdater[typeof(T)](key, value, h);
}
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp)
{
return Find(regexp, ConfigurationLevel.Local);
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp");
using (ConfigurationSafeHandle snapshot = Snapshot())
using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot))
{
return Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList();
}
}
private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationSafeHandle fromHandle)
{
ConfigurationSafeHandle handle = null;
if (fromHandle != null)
{
handle = Proxy.git_config_open_level(fromHandle, level);
}
if (handle == null && throwIfStoreHasNotBeenFound)
{
throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture,
"No {0} configuration file has been found.",
Enum.GetName(typeof(ConfigurationLevel), level)));
}
return handle;
}
private static Action<string, object, ConfigurationSafeHandle> GetUpdater<T>(Action<ConfigurationSafeHandle, string, T> setter)
{
return (key, val, handle) => setter(handle, key, (T)val);
}
private readonly static IDictionary<Type, Action<string, object, ConfigurationSafeHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationSafeHandle>>
{
{ typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) },
{ typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) },
{ typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) },
{ typeof(string), GetUpdater<string>(Proxy.git_config_set_string) },
};
/// <summary>
/// Returns an enumerator that iterates through the configuration entries.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns>
public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator()
{
return BuildConfigEntries().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator();
}
private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries()
{
return Proxy.git_config_foreach(configHandle, BuildConfigEntry);
}
private static ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr)
{
var entry = entryPtr.MarshalAs<GitConfigEntry>();
return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry.namePtr),
LaxUtf8Marshaler.FromNative(entry.valuePtr),
(ConfigurationLevel)entry.level);
}
/// <summary>
/// Builds a <see cref="Signature"/> based on current configuration.
/// <para>
/// Name is populated from the user.name setting, and is "unknown" if unspecified.
/// Email is populated from the user.email setting, and is built from
/// <see cref="Environment.UserName"/> and <see cref="Environment.UserDomainName"/> if unspecified.
/// </para>
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
/// </para>
/// </summary>
/// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param>
/// <returns>The signature.</returns>
public virtual Signature BuildSignature(DateTimeOffset now)
{
return BuildSignature(now, false);
}
internal Signature BuildSignature(DateTimeOffset now, bool shouldThrowIfNotFound)
{
const string userNameKey = "user.name";
var name = this.GetValueOrDefault<string>(userNameKey);
var normalizedName = NormalizeUserSetting(shouldThrowIfNotFound,
userNameKey,
name,
() => "unknown");
const string userEmailKey = "user.email";
var email = this.GetValueOrDefault<string>(userEmailKey);
var normalizedEmail = NormalizeUserSetting(shouldThrowIfNotFound,
userEmailKey,
email,
() => string.Format(CultureInfo.InvariantCulture,
"{0}@{1}",
Environment.UserName,
Environment.UserDomainName));
return new Signature(normalizedName, normalizedEmail, now);
}
private string NormalizeUserSetting(bool shouldThrowIfNotFound, string entryName, string currentValue, Func<string> defaultValue)
{
if (!string.IsNullOrEmpty(currentValue))
{
return currentValue;
}
string message = string.Format("Configuration value '{0}' is missing or invalid.", entryName);
if (shouldThrowIfNotFound)
{
throw new LibGit2SharpException(message);
}
Log.Write(LogLevel.Warning, message);
return defaultValue();
}
private ConfigurationSafeHandle Snapshot()
{
return Proxy.git_config_snapshot(configHandle);
}
}
}
| |
// Copyright (c) Microsoft. 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Dynamic.Utils
{
internal static class ExpressionUtils
{
public static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection)
{
IList<T> value = collection;
// if it's already read-only just return it.
ReadOnlyCollection<T> res = value as ReadOnlyCollection<T>;
if (res != null)
{
return res;
}
// otherwise make sure only readonly collection every gets exposed
Interlocked.CompareExchange<IList<T>>(
ref collection,
value.ToReadOnly(),
value
);
// and return it
return (ReadOnlyCollection<T>)collection;
}
/// <summary>
/// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
///
/// This is similar to the ReturnReadOnly of T. This version supports nodes which hold
/// onto multiple Expressions where one is typed to object. That object field holds either
/// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection
/// the IList which backs it is a ListArgumentProvider which uses the Expression which
/// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider
/// continues to hold onto the 1st expression.
///
/// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if
/// it was just an array. Meanwhile The DLR internally avoids accessing which would force
/// the readonly collection to be created resulting in a typical memory savings.
/// </summary>
public static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection)
{
Expression tObj = collection as Expression;
if (tObj != null)
{
// otherwise make sure only one readonly collection ever gets exposed
Interlocked.CompareExchange(
ref collection,
new ReadOnlyCollection<Expression>(new ListArgumentProvider(provider, tObj)),
tObj
);
}
// and return what is not guaranteed to be a readonly collection
return (ReadOnlyCollection<Expression>)collection;
}
/// <summary>
/// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...).
/// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider.
///
/// This is used to return the 1st argument. The 1st argument is typed as object and either
/// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's
/// present we return that, otherwise we return the 1st element of the ReadOnlyCollection.
/// </summary>
public static T ReturnObject<T>(object collectionOrT) where T : class
{
T t = collectionOrT as T;
if (t != null)
{
return t;
}
return ((ReadOnlyCollection<T>)collectionOrT)[0];
}
public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection<Expression> arguments)
{
Debug.Assert(nodeKind == ExpressionType.Invoke || nodeKind == ExpressionType.Call || nodeKind == ExpressionType.Dynamic || nodeKind == ExpressionType.New);
ParameterInfo[] pis = GetParametersForValidation(method, nodeKind);
ValidateArgumentCount(method, nodeKind, arguments.Count, pis);
Expression[] newArgs = null;
for (int i = 0, n = pis.Length; i < n; i++)
{
Expression arg = arguments[i];
ParameterInfo pi = pis[i];
arg = ValidateOneArgument(method, nodeKind, arg, pi);
if (newArgs == null && arg != arguments[i])
{
newArgs = new Expression[arguments.Count];
for (int j = 0; j < i; j++)
{
newArgs[j] = arguments[j];
}
}
if (newArgs != null)
{
newArgs[i] = arg;
}
}
if (newArgs != null)
{
arguments = new TrueReadOnlyCollection<Expression>(newArgs);
}
}
public static void ValidateArgumentCount(MethodBase method, ExpressionType nodeKind, int count, ParameterInfo[] pis)
{
if (pis.Length != count)
{
// Throw the right error for the node we were given
switch (nodeKind)
{
case ExpressionType.New:
throw Error.IncorrectNumberOfConstructorArguments();
case ExpressionType.Invoke:
throw Error.IncorrectNumberOfLambdaArguments();
case ExpressionType.Dynamic:
case ExpressionType.Call:
throw Error.IncorrectNumberOfMethodCallArguments(method);
default:
throw ContractUtils.Unreachable;
}
}
}
public static Expression ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
{
RequiresCanRead(arg, "arguments");
Type pType = pi.ParameterType;
if (pType.IsByRef)
{
pType = pType.GetElementType();
}
TypeUtils.ValidateType(pType);
if (!TypeUtils.AreReferenceAssignable(pType, arg.Type))
{
if (!TryQuote(pType, ref arg))
{
// Throw the right error for the node we were given
switch (nodeKind)
{
case ExpressionType.New:
throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arg.Type, pType);
case ExpressionType.Invoke:
throw Error.ExpressionTypeDoesNotMatchParameter(arg.Type, pType);
case ExpressionType.Dynamic:
case ExpressionType.Call:
throw Error.ExpressionTypeDoesNotMatchMethodParameter(arg.Type, pType, method);
default:
throw ContractUtils.Unreachable;
}
}
}
return arg;
}
public static void RequiresCanRead(Expression expression, string paramName)
{
if (expression == null)
{
throw new ArgumentNullException(paramName);
}
// validate that we can read the node
switch (expression.NodeType)
{
case ExpressionType.Index:
IndexExpression index = (IndexExpression)expression;
if (index.Indexer != null && !index.Indexer.CanRead)
{
throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName);
}
break;
case ExpressionType.MemberAccess:
MemberExpression member = (MemberExpression)expression;
PropertyInfo prop = member.Member as PropertyInfo;
if (prop != null)
{
if (!prop.CanRead)
{
throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName);
}
}
break;
}
}
// Attempts to auto-quote the expression tree. Returns true if it succeeded, false otherwise.
public static bool TryQuote(Type parameterType, ref Expression argument)
{
// We used to allow quoting of any expression, but the behavior of
// quote (produce a new tree closed over parameter values), only
// works consistently for lambdas
Type quoteable = typeof(LambdaExpression);
if (TypeUtils.IsSameOrSubclass(quoteable, parameterType) &&
parameterType.IsAssignableFrom(argument.GetType()))
{
argument = Expression.Quote(argument);
return true;
}
return false;
}
internal static ParameterInfo[] GetParametersForValidation(MethodBase method, ExpressionType nodeKind)
{
ParameterInfo[] pis = method.GetParametersCached();
if (nodeKind == ExpressionType.Dynamic)
{
pis = pis.RemoveFirst(); // ignore CallSite argument
}
return pis;
}
}
}
| |
using System;
#if NET_45
using System.Collections.Generic;
#endif
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Repositories API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/">Repositories API documentation</a> for more details.
/// </remarks>
public interface IRepositoriesClient
{
/// <summary>
/// Client for managing pull requests.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/pulls/">Pull Requests API documentation</a> for more details
/// </remarks>
IPullRequestsClient PullRequest { get; }
/// <summary>
/// Client for managing commit comments in a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/comments/">Repository Comments API documentation</a> for more information.
/// </remarks>
IRepositoryCommentsClient RepositoryComments { get; }
/// <summary>
/// Client for managing deploy keys in a repository.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/keys/">Repository Deploy Keys API documentation</a> for more information.
/// </remarks>
IRepositoryDeployKeysClient DeployKeys { get; }
/// <summary>
/// Client for managing the contents of a repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/contents/">Repository Contents API documentation</a> for more information.
/// </remarks>
IRepositoryContentsClient Content { get; }
/// <summary>
/// Creates a new repository for the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
/// </remarks>
/// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/> instance for the created repository.</returns>
Task<Repository> Create(NewRepository newRepository);
/// <summary>
/// Creates a new repository in the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#create">API documentation</a> for more information.
/// </remarks>
/// <param name="organizationLogin">Login of the organization in which to create the repostiory</param>
/// <param name="newRepository">A <see cref="NewRepository"/> instance describing the new repository to create</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/> instance for the created repository</returns>
Task<Repository> Create(string organizationLogin, NewRepository newRepository);
/// <summary>
/// Deletes the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#delete-a-repository">API documentation</a> for more information.
/// Deleting a repository requires admin access. If OAuth is used, the `delete_repo` scope is required.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
Task Delete(string owner, string name);
/// <summary>
/// Gets the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#get">API documentation</a> for more information.
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="Repository"/></returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get")]
Task<Repository> Get(string owner, string name);
/// <summary>
/// Gets all public repositories.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllPublic();
/// <summary>
/// Gets all public repositories since the integer ID of the last Repository that you've seen.
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/#list-all-public-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <param name="request">Search parameters of the last repository seen</param>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
Task<IReadOnlyList<Repository>> GetAllPublic(PublicRepositoryRequest request);
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForCurrent();
/// <summary>
/// Gets all repositories owned by the current user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-your-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <param name="request">Search parameters to filter results on</param>
/// <exception cref="AuthorizationException">Thrown if the client is not authenticated.</exception>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForCurrent(RepositoryRequest request);
/// <summary>
/// Gets all repositories owned by the specified user.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-user-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForUser(string login);
/// <summary>
/// Gets all repositories owned by the specified organization.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-organization-repositories">API documentation</a> for more information.
/// The default page size on GitHub.com is 30.
/// </remarks>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A <see cref="IReadOnlyPagedCollection{Repository}"/> of <see cref="Repository"/>.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Makes a network request")]
Task<IReadOnlyList<Repository>> GetAllForOrg(string organization);
/// <summary>
/// A client for GitHub's Commit Status API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/statuses/">Commit Status API documentation</a> for more
/// details. Also check out the <a href="https://github.com/blog/1227-commit-status-api">blog post</a>
/// that announced this feature.
/// </remarks>
ICommitStatusClient CommitStatus { get; }
/// <summary>
/// A client for GitHub's Repository Hooks API.
/// </summary>
/// <remarks>See <a href="http://developer.github.com/v3/repos/hooks/">Hooks API documentation</a> for more information.</remarks>
IRepositoryHooksClient Hooks { get; }
/// <summary>
/// A client for GitHub's Repository Forks API.
/// </summary>
/// <remarks>See <a href="http://developer.github.com/v3/repos/forks/">Forks API documentation</a> for more information.</remarks>
IRepositoryForksClient Forks { get; }
/// <summary>
/// A client for GitHub's Repo Collaborators.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/collaborators/">Collaborators API documentation</a> for more details
/// </remarks>
IRepoCollaboratorsClient RepoCollaborators { get; }
/// <summary>
/// Client for GitHub's Repository Deployments API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/deployment/">Collaborators API documentation</a> for more details
/// </remarks>
IDeploymentsClient Deployment { get; }
/// <summary>
/// Client for GitHub's Repository Statistics API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/statistics/">Statistics API documentation</a> for more details
///</remarks>
IStatisticsClient Statistics { get; }
/// <summary>
/// Client for GitHub's Repository Commits API
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/commits/">Commits API documentation</a> for more details
///</remarks>
IRepositoryCommitsClient Commits { get; }
/// <summary>
/// Client for GitHub's Repository Merging API
/// </summary>
/// <remarks>
/// See the <a href="https://developer.github.com/v3/repos/merging/">Merging API documentation</a> for more details
///</remarks>
IMergingClient Merging { get; }
/// <summary>
/// Gets all the branches for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-branches">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>All <see cref="T:Octokit.Branch"/>es of the repository</returns>
Task<IReadOnlyList<Branch>> GetAllBranches(string owner, string name);
/// <summary>
/// Gets all contributors for the specified repository. Does not include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name);
/// <summary>
/// Gets all contributors for the specified repository. With the option to include anonymous contributors.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-contributors">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="includeAnonymous">True if anonymous contributors should be included in result; Otherwise false</param>
/// <returns>All contributors of the repository.</returns>
Task<IReadOnlyList<RepositoryContributor>> GetAllContributors(string owner, string name, bool includeAnonymous);
/// <summary>
/// Gets all languages for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-languages">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All languages used in the repository and the number of bytes of each language.</returns>
Task<IReadOnlyList<RepositoryLanguage>> GetAllLanguages(string owner, string name);
/// <summary>
/// Gets all teams for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-teams">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All <see cref="T:Octokit.Team"/>s associated with the repository</returns>
Task<IReadOnlyList<Team>> GetAllTeams(string owner, string name);
/// <summary>
/// Gets all tags for the specified repository.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#list-tags">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <returns>All of the repositorys tags.</returns>
Task<IReadOnlyList<RepositoryTag>> GetAllTags(string owner, string name);
/// <summary>
/// Gets the specified branch.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/repos/#get-branch">API documentation</a> for more details
/// </remarks>
/// <param name="owner">The owner of the repository</param>
/// <param name="repositoryName">The name of the repository</param>
/// <param name="branchName">The name of the branch</param>
/// <returns>The specified <see cref="T:Octokit.Branch"/></returns>
Task<Branch> GetBranch(string owner, string repositoryName, string branchName);
/// <summary>
/// Updates the specified repository with the values given in <paramref name="update"/>
/// </summary>
/// <param name="owner">The owner of the repository</param>
/// <param name="name">The name of the repository</param>
/// <param name="update">New values to update the repository with</param>
/// <returns>The updated <see cref="T:Octokit.Repository"/></returns>
Task<Repository> Edit(string owner, string name, RepositoryUpdate update);
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.PlatformsCommon.Factories;
using Microsoft.Identity.Client.Utils;
namespace Microsoft.Identity.Client
{
/// <summary>
/// Parameters returned by the WWW-Authenticate header. This allows for dynamic
/// scenarios such as claim challenge, CAE, CA auth context.
/// See https://aka.ms/msal-net/wwwAuthenticate.
/// </summary>
public class WwwAuthenticateParameters
{
/// <summary>
/// Resource for which to request scopes.
/// This is the App ID URI of the API that returned the WWW-Authenticate header.
/// </summary>
[Obsolete("The client apps should know which App ID URI it requests scopes for.", true)]
public string Resource { get; set; }
/// <summary>
/// Scopes to request.
/// If it's not provided by the web API, it's computed from the Resource.
/// </summary>
[Obsolete("The client apps should know which scopes to request for.", true)]
public IEnumerable<string> Scopes { get; set; }
/// <summary>
/// Authority from which to request an access token.
/// </summary>
public string Authority { get; set; }
/// <summary>
/// Claims demanded by the web API.
/// </summary>
public string Claims { get; set; }
/// <summary>
/// Error.
/// </summary>
public string Error { get; set; }
/// <summary>
/// Return the <see cref="RawParameters"/> of key <paramref name="key"/>.
/// </summary>
/// <param name="key">Name of the raw parameter to retrieve.</param>
/// <returns>The raw parameter if it exists,
/// or throws a <see cref="System.Collections.Generic.KeyNotFoundException"/> otherwise.
/// </returns>
public string this[string key]
{
get
{
return RawParameters[key];
}
}
/// <summary>
/// Dictionary of raw parameters in the WWW-Authenticate header (extracted from the WWW-Authenticate header
/// string value, without any processing). This allows support for APIs which are not mappable easily to the standard
/// or framework specific (Microsoft.Identity.Model, Microsoft.Identity.Web).
/// </summary>
internal IDictionary<string, string> RawParameters { get; private set; }
/// <summary>
/// Gets Azure AD tenant ID.
/// </summary>
public string GetTenantId() => Instance.Authority
.CreateAuthority(Authority, validateAuthority: true)
.TenantId;
/// <summary>
/// Create WWW-Authenticate parameters from the HttpResponseHeaders.
/// </summary>
/// <param name="httpResponseHeaders">HttpResponseHeaders.</param>
/// <param name="scheme">Authentication scheme. Default is "Bearer".</param>
/// <returns>The parameters requested by the web API.</returns>
/// <remarks>Currently it only supports the Bearer scheme</remarks>
public static WwwAuthenticateParameters CreateFromResponseHeaders(
HttpResponseHeaders httpResponseHeaders,
string scheme = "Bearer")
{
if (httpResponseHeaders.WwwAuthenticate.Any())
{
// TODO: add POP support
AuthenticationHeaderValue bearer = httpResponseHeaders.WwwAuthenticate.First(v => string.Equals(v.Scheme, scheme, StringComparison.OrdinalIgnoreCase));
string wwwAuthenticateValue = bearer.Parameter;
return CreateFromWwwAuthenticateHeaderValue(wwwAuthenticateValue);
}
return CreateWwwAuthenticateParameters(new Dictionary<string, string>());
}
/// <summary>
/// Creates parameters from the WWW-Authenticate string.
/// </summary>
/// <param name="wwwAuthenticateValue">String contained in a WWW-Authenticate header.</param>
/// <returns>The parameters requested by the web API.</returns>
public static WwwAuthenticateParameters CreateFromWwwAuthenticateHeaderValue(string wwwAuthenticateValue)
{
if (string.IsNullOrWhiteSpace(wwwAuthenticateValue))
{
throw new ArgumentNullException(nameof(wwwAuthenticateValue));
}
IDictionary<string, string> parameters = CoreHelpers.SplitWithQuotes(wwwAuthenticateValue, ',')
.Select(v => ExtractKeyValuePair(v.Trim()))
.ToDictionary(pair => pair.Key, pair => pair.Value, StringComparer.OrdinalIgnoreCase);
return CreateWwwAuthenticateParameters(parameters);
}
/// <summary>
/// Create the authenticate parameters by attempting to call the resource unauthenticated, and analyzing the response.
/// </summary>
/// <param name="resourceUri">URI of the resource.</param>
/// <returns>WWW-Authenticate Parameters extracted from response to the unauthenticated call.</returns>
public static Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(string resourceUri)
{
return CreateFromResourceResponseAsync(resourceUri, default);
}
/// <summary>
/// Create the authenticate parameters by attempting to call the resource unauthenticated, and analyzing the response.
/// </summary>
/// <param name="resourceUri">URI of the resource.</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <returns>WWW-Authenticate Parameters extracted from response to the unauthenticated call.</returns>
public static Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(string resourceUri, CancellationToken cancellationToken = default)
{
var httpClientFactory = PlatformProxyFactory.CreatePlatformProxy(null).CreateDefaultHttpClientFactory();
var httpClient = httpClientFactory.GetHttpClient();
return CreateFromResourceResponseAsync(httpClient, resourceUri, cancellationToken);
}
/// <summary>
/// Create the authenticate parameters by attempting to call the resource unauthenticated, and analyzing the response.
/// </summary>
/// <param name="httpClient">Instance of <see cref="HttpClient"/> to make the request with.</param>
/// <param name="resourceUri">URI of the resource.</param>
/// <param name="cancellationToken">The cancellation token to cancel operation.</param>
/// <returns>WWW-Authenticate Parameters extracted from response to the unauthenticated call.</returns>
public static async Task<WwwAuthenticateParameters> CreateFromResourceResponseAsync(HttpClient httpClient, string resourceUri, CancellationToken cancellationToken = default)
{
if (httpClient is null)
{
throw new ArgumentNullException(nameof(httpClient));
}
if (string.IsNullOrWhiteSpace(resourceUri))
{
throw new ArgumentNullException(nameof(resourceUri));
}
// call this endpoint and see what the header says and return that
HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(resourceUri, cancellationToken).ConfigureAwait(false);
var wwwAuthParam = CreateFromResponseHeaders(httpResponseMessage.Headers);
return wwwAuthParam;
}
/// <summary>
/// Gets the claim challenge from HTTP header.
/// Used, for example, for CA auth context.
/// </summary>
/// <param name="httpResponseHeaders">The HTTP response headers.</param>
/// <param name="scheme">Authentication scheme. Default is Bearer.</param>
/// <returns></returns>
public static string GetClaimChallengeFromResponseHeaders(
HttpResponseHeaders httpResponseHeaders,
string scheme = "Bearer")
{
WwwAuthenticateParameters parameters = CreateFromResponseHeaders(
httpResponseHeaders,
scheme);
// read the header and checks if it contains an error with insufficient_claims value.
if (parameters.Claims != null &&
string.Equals(parameters.Error, "insufficient_claims", StringComparison.OrdinalIgnoreCase))
{
return parameters.Claims;
}
return null;
}
internal static WwwAuthenticateParameters CreateWwwAuthenticateParameters(IDictionary<string, string> values)
{
WwwAuthenticateParameters wwwAuthenticateParameters = new WwwAuthenticateParameters
{
RawParameters = values
};
string value;
if (values.TryGetValue("authorization_uri", out value))
{
wwwAuthenticateParameters.Authority = value.Replace("/oauth2/authorize", string.Empty);
}
if (string.IsNullOrEmpty(wwwAuthenticateParameters.Authority))
{
if (values.TryGetValue("authorization", out value))
{
wwwAuthenticateParameters.Authority = value.Replace("/oauth2/authorize", string.Empty);
}
}
if (string.IsNullOrEmpty(wwwAuthenticateParameters.Authority))
{
if (values.TryGetValue("authority", out value))
{
wwwAuthenticateParameters.Authority = value.TrimEnd('/');
}
}
if (values.TryGetValue("claims", out value))
{
wwwAuthenticateParameters.Claims = GetJsonFragment(value);
}
if (values.TryGetValue("error", out value))
{
wwwAuthenticateParameters.Error = value;
}
return wwwAuthenticateParameters;
}
/// <summary>
/// Extracts a key value pair from an expression of the form a=b
/// </summary>
/// <param name="assignment">assignment</param>
/// <returns>Key Value pair</returns>
private static KeyValuePair<string, string> ExtractKeyValuePair(string assignment)
{
string[] segments = CoreHelpers.SplitWithQuotes(assignment, '=')
.Select(s => s.Trim().Trim('"'))
.ToArray();
if (segments.Length != 2)
{
throw new ArgumentException(nameof(assignment), $"{assignment} isn't of the form a=b");
}
return new KeyValuePair<string, string>(segments[0], segments[1]);
}
/// <summary>
/// Checks if input is a base-64 encoded string.
/// If it is one, decodes it to get a json fragment.
/// </summary>
/// <param name="inputString">Input string</param>
/// <returns>a json fragment (original input string or decoded from base64 encoded).</returns>
private static string GetJsonFragment(string inputString)
{
if (string.IsNullOrEmpty(inputString) || inputString.Length % 4 != 0 || inputString.Any(c => char.IsWhiteSpace(c)))
{
return inputString;
}
try
{
var decodedBase64Bytes = Convert.FromBase64String(inputString);
var decoded = Encoding.UTF8.GetString(decodedBase64Bytes);
return decoded;
}
catch
{
return inputString;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using OctoTorrent.Client.Messages;
using OctoTorrent.Client.Messages.UdpTracker;
using OctoTorrent.Common;
namespace OctoTorrent.Client.Tracker
{
public class UdpTracker : Tracker
{
private long connectionId;
private UdpClient tracker;
private IPEndPoint endpoint;
bool hasConnected;
bool amConnecting;
internal TimeSpan RetryDelay;
int timeout;
public UdpTracker(Uri announceUrl)
: base(announceUrl)
{
CanScrape = true;
CanAnnounce = true;
RetryDelay = TimeSpan.FromSeconds(15);
tracker = new UdpClient(announceUrl.Host, announceUrl.Port);
endpoint = (IPEndPoint)tracker.Client.RemoteEndPoint;
}
#region announce
public override void Announce(AnnounceParameters parameters, object state)
{
//LastUpdated = DateTime.Now;
if (!hasConnected && amConnecting)
return;
if (!hasConnected)
{
amConnecting = true;
try
{
Connect(new ConnectAnnounceState(parameters, ConnectAnnounceCallback, state));
}
catch (SocketException)
{
DoAnnounceComplete(false, state, new List<Peer>());
return;
}
}
else
DoAnnounce(parameters, state);
}
private void DoAnnounce(AnnounceParameters parameters, object state)
{
ConnectAnnounceState announceState = new ConnectAnnounceState(parameters, AnnounceCallback, state);
announceState.Message = new AnnounceMessage(DateTime.Now.GetHashCode(), connectionId, parameters);
try
{
SendAndReceive(announceState);
}
catch (SocketException)
{
DoAnnounceComplete(false, state, new List<Peer>());
}
}
private void ConnectAnnounceCallback(IAsyncResult ar)
{
ConnectAnnounceState announceState = (ConnectAnnounceState)ar;
try
{
if (announceState.SavedException != null)
{
FailureMessage = announceState.SavedException.Message;
amConnecting = false;
DoAnnounceComplete(false, announceState.AsyncState, new List<Peer>());
return;
}
if (!ConnectCallback(ar))//bad transaction id
{
DoAnnounceComplete(false, announceState.AsyncState, new List<Peer>());
return;
}
DoAnnounce(announceState.Parameters, announceState.AsyncState);
}
catch
{
DoAnnounceComplete(false, announceState.AsyncState, null);
}
}
private void AnnounceCallback(IAsyncResult ar)
{
ConnectAnnounceState announceState = (ConnectAnnounceState)ar;
try
{
if (announceState.SavedException != null)
{
FailureMessage = announceState.SavedException.Message;
DoAnnounceComplete(false, announceState.AsyncState, new List<Peer>());
return;
}
UdpTrackerMessage rsp = Receive(announceState, announceState.Data);
if (!(rsp is AnnounceResponseMessage))
{
DoAnnounceComplete(false, announceState.AsyncState, new List<Peer>());
return;
}
MinUpdateInterval = ((AnnounceResponseMessage)rsp).Interval;
CompleteAnnounce(rsp, announceState.AsyncState);
}
catch
{
DoAnnounceComplete(false, announceState.AsyncState, null);
}
}
private void CompleteAnnounce(UdpTrackerMessage message, object state)
{
ErrorMessage error = message as ErrorMessage;
if (error != null)
{
FailureMessage = error.Error;
DoAnnounceComplete(false, state, new List<Peer>());
}
else
{
AnnounceResponseMessage response = (AnnounceResponseMessage)message;
DoAnnounceComplete(true, state, response.Peers);
//TODO seeders and leechers is not used in event.
}
}
private void DoAnnounceComplete(bool successful, object state, List<Peer> peers)
{
RaiseAnnounceComplete(new AnnounceResponseEventArgs(this, state, successful, peers));
}
#endregion
#region connect
private void Connect(UdpTrackerAsyncState connectState)
{
connectState.Message = new ConnectMessage();
tracker.Connect(Uri.Host, Uri.Port);
SendAndReceive(connectState);
}
private bool ConnectCallback(IAsyncResult ar)
{
UdpTrackerAsyncState trackerState = (UdpTrackerAsyncState)ar;
try
{
UdpTrackerMessage msg = Receive(trackerState, trackerState.Data);
if (msg == null)
return false;//bad transaction id
ConnectResponseMessage rsp = msg as ConnectResponseMessage;
if (rsp == null)
{
//is there a possibility to have a message which is not error message or connect rsp but udp msg
FailureMessage = ((ErrorMessage)msg).Error;
return false;//error message
}
connectionId = rsp.ConnectionId;
hasConnected = true;
amConnecting = false;
return true;
}
catch
{
return false;
}
}
#endregion
#region scrape
public override void Scrape(ScrapeParameters parameters, object state)
{
//LastUpdated = DateTime.Now;
if (!hasConnected && amConnecting)
return;
if (!hasConnected)
{
amConnecting = true;
try
{
Connect(new ConnectScrapeState(parameters, ConnectScrapeCallback, state));
}
catch (SocketException)
{
DoScrapeComplete(false, state);
return;
}
}
else
DoScrape(parameters, state);
}
private void ConnectScrapeCallback(IAsyncResult ar)
{
ConnectScrapeState scrapeState = (ConnectScrapeState)ar;
try
{
if (scrapeState.SavedException != null)
{
FailureMessage = scrapeState.SavedException.Message;
amConnecting = false;
DoScrapeComplete(false, scrapeState.AsyncState);
return;
}
if (!ConnectCallback(ar))//bad transaction id
{
DoScrapeComplete(false, scrapeState.AsyncState);
return;
}
DoScrape(scrapeState.Parameters, scrapeState.AsyncState);
}
catch
{
DoScrapeComplete(false, scrapeState.AsyncState);
}
}
private void DoScrape(ScrapeParameters parameters, object state)
{
//strange because here only one infohash???
//or get all torrent infohash so loop on torrents of client engine
List<byte[]> infohashs= new List<byte[]>(1);
infohashs.Add(parameters.InfoHash.Hash);
ConnectScrapeState scrapeState = new ConnectScrapeState(parameters, ScrapeCallback, state);
scrapeState.Message = new ScrapeMessage(DateTime.Now.GetHashCode(), connectionId, infohashs);
try
{
SendAndReceive(scrapeState);
}
catch (SocketException)
{
DoScrapeComplete(false, state);
}
}
private void ScrapeCallback(IAsyncResult ar)
{
try
{
ConnectScrapeState scrapeState = (ConnectScrapeState)ar;
if (scrapeState.SavedException != null)
{
FailureMessage = scrapeState.SavedException.Message;
DoScrapeComplete(false, scrapeState.AsyncState);
return;
}
UdpTrackerMessage rsp = Receive(scrapeState, scrapeState.Data);
if (!(rsp is ScrapeResponseMessage))
{
DoScrapeComplete(false, scrapeState.AsyncState);
return;
}
CompleteScrape(rsp, scrapeState.AsyncState);
}
catch
{
// Nothing to do i think
}
}
private void CompleteScrape(UdpTrackerMessage message, object state)
{
ErrorMessage error = message as ErrorMessage;
if (error != null)
{
FailureMessage = error.Error;
DoScrapeComplete(false, state);
}
else
{
//response.Scrapes not used for moment
//ScrapeResponseMessage response = (ScrapeResponseMessage)message;
DoScrapeComplete(true, state);
}
}
private void DoScrapeComplete(bool successful, object state)
{
ScrapeResponseEventArgs e = new ScrapeResponseEventArgs(this, state, successful);
RaiseScrapeComplete(e);
}
#endregion
#region TimeOut System
private void SendAndReceive(UdpTrackerAsyncState messageState)
{
timeout = 1;
SendRequest(messageState);
tracker.BeginReceive(EndReceiveMessage, messageState);
}
private void EndReceiveMessage(IAsyncResult result)
{
UdpTrackerAsyncState trackerState = (UdpTrackerAsyncState)result.AsyncState;
try
{
IPEndPoint endpoint = null;
trackerState.Data = tracker.EndReceive(result, ref endpoint);
trackerState.Callback(trackerState);
}
catch (Exception ex)
{
trackerState.Complete(ex);
}
}
private void SendRequest(UdpTrackerAsyncState requestState)
{
//TODO BeginSend
byte[] buffer = requestState.Message.Encode();
tracker.Send(buffer, buffer.Length);
//response timeout: we try 4 times every 15 sec
ClientEngine.MainLoop.QueueTimeout(RetryDelay, delegate
{
if (timeout == 0)//we receive data
return false;
if (timeout <= 4)
{
timeout++;
try
{
tracker.Send(buffer, buffer.Length);
}
catch (Exception ex)
{
timeout = 0;
requestState.Complete(ex);
return false;
}
}
else
{
timeout = 0;
requestState.Complete(new Exception("Tracker did not respond to the connect requests"));
return false;
}
return true;
});
}
private UdpTrackerMessage Receive(UdpTrackerAsyncState trackerState, byte[] receivedMessage)
{
timeout = 0;//we have receive so unactive the timeout
byte[] data = receivedMessage;
UdpTrackerMessage rsp = UdpTrackerMessage.DecodeMessage(data, 0, data.Length, MessageType.Response);
if (trackerState.Message.TransactionId != rsp.TransactionId)
{
FailureMessage = "Invalid transaction Id in response from udp tracker!";
return null;//to raise event fail outside
}
return rsp;
}
#endregion
public override string ToString()
{
return "udptracker:"+connectionId;
}
#region async state
abstract class UdpTrackerAsyncState : AsyncResult
{
public byte[] Data;
public UdpTrackerMessage Message;
protected UdpTrackerAsyncState(AsyncCallback callback, object state)
: base(callback, state)
{
}
}
class ConnectAnnounceState : UdpTrackerAsyncState
{
public AnnounceParameters Parameters;
public ConnectAnnounceState(AnnounceParameters parameters, AsyncCallback callback, object state)
: base (callback, state)
{
Parameters = parameters;
}
}
class ConnectScrapeState : UdpTrackerAsyncState
{
public ScrapeParameters Parameters;
public ConnectScrapeState(ScrapeParameters parameters, AsyncCallback callback, object state)
: base (callback, state)
{
Parameters = parameters;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Permissions;
using Fasterflect;
namespace Python.Runtime
{
using MaybeMethodInfo = MaybeMethodBase<MethodInfo>;
/// <summary>
/// Implements a Python descriptor type that manages CLR properties.
/// </summary>
[Serializable]
internal class PropertyObject : ExtensionType
{
private MaybeMemberInfo<PropertyInfo> info;
private MaybeMethodInfo getter;
private MaybeMethodInfo setter;
private MemberGetter _memberGetter;
private Type _memberGetterType;
private MemberSetter _memberSetter;
private Type _memberSetterType;
private bool _isValueType;
private Type _isValueTypeType;
[StrongNameIdentityPermission(SecurityAction.Assert)]
public PropertyObject(PropertyInfo md)
{
getter = md.GetGetMethod(true);
setter = md.GetSetMethod(true);
info = md;
}
/// <summary>
/// Descriptor __get__ implementation. This method returns the
/// value of the property on the given object. The returned value
/// is converted to an appropriately typed Python object.
/// </summary>
public static IntPtr tp_descr_get(IntPtr ds, IntPtr ob, IntPtr tp)
{
var self = (PropertyObject)GetManagedObject(ds);
if (!self.info.Valid)
{
return Exceptions.RaiseTypeError(self.info.DeletedMessage);
}
var info = self.info.Value;
MethodInfo getter = self.getter.UnsafeValue;
object result;
if (getter == null)
{
return Exceptions.RaiseTypeError("property cannot be read");
}
if (ob == IntPtr.Zero || ob == Runtime.PyNone)
{
if (!getter.IsStatic)
{
Exceptions.SetError(Exceptions.TypeError,
"instance property must be accessed through a class instance");
return IntPtr.Zero;
}
try
{
result = self.GetMemberGetter(info.DeclaringType)(info.DeclaringType);
return Converter.ToPython(result, info.PropertyType);
}
catch (Exception e)
{
return Exceptions.RaiseTypeError(e.Message);
}
}
var co = GetManagedObject(ob) as CLRObject;
if (co == null)
{
return Exceptions.RaiseTypeError("invalid target");
}
try
{
var type = co.inst.GetType();
result = self.GetMemberGetter(type)(self.IsValueType(type) ? co.inst.WrapIfValueType() : co.inst);
return Converter.ToPython(result, info.PropertyType);
}
catch (Exception e)
{
if (e.InnerException != null)
{
e = e.InnerException;
}
Exceptions.SetError(e);
return IntPtr.Zero;
}
}
/// <summary>
/// Descriptor __set__ implementation. This method sets the value of
/// a property based on the given Python value. The Python value must
/// be convertible to the type of the property.
/// </summary>
public new static int tp_descr_set(IntPtr ds, IntPtr ob, IntPtr val)
{
var self = (PropertyObject)GetManagedObject(ds);
if (!self.info.Valid)
{
Exceptions.RaiseTypeError(self.info.DeletedMessage);
return -1;
}
var info = self.info.Value;
MethodInfo setter = self.setter.UnsafeValue;
object newval;
if (val == IntPtr.Zero)
{
Exceptions.RaiseTypeError("cannot delete property");
return -1;
}
if (setter == null)
{
Exceptions.RaiseTypeError("property is read-only");
return -1;
}
if (!Converter.ToManaged(val, info.PropertyType, out newval, true))
{
return -1;
}
bool is_static = setter.IsStatic;
if (ob == IntPtr.Zero || ob == Runtime.PyNone)
{
if (!is_static)
{
Exceptions.RaiseTypeError("instance property must be set on an instance");
return -1;
}
}
try
{
if (!is_static)
{
var co = GetManagedObject(ob) as CLRObject;
if (co == null)
{
Exceptions.RaiseTypeError("invalid target");
return -1;
}
var type = co.inst.GetType();
self.GetMemberSetter(type)(self.IsValueType(type) ? co.inst.WrapIfValueType() : co.inst, newval);
}
else
{
self.GetMemberSetter(info.DeclaringType)(info.DeclaringType, newval);
}
return 0;
}
catch (Exception e)
{
if (e.InnerException != null)
{
e = e.InnerException;
}
Exceptions.SetError(e);
return -1;
}
}
/// <summary>
/// Descriptor __repr__ implementation.
/// </summary>
public static IntPtr tp_repr(IntPtr ob)
{
var self = (PropertyObject)GetManagedObject(ob);
return Runtime.PyString_FromString($"<property '{self.info}'>");
}
private MemberGetter GetMemberGetter(Type type)
{
if (type != _memberGetterType)
{
_memberGetter = FasterflectManager.GetPropertyGetter(type, info.Value.Name);
_memberGetterType = type;
}
return _memberGetter;
}
private MemberSetter GetMemberSetter(Type type)
{
if (type != _memberSetterType)
{
_memberSetter = FasterflectManager.GetPropertySetter(type, info.Value.Name);
_memberSetterType = type;
}
return _memberSetter;
}
private bool IsValueType(Type type)
{
if (type != _isValueTypeType)
{
_isValueType = FasterflectManager.IsValueType(type);
_isValueTypeType = type;
}
return _isValueType;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.FileProperties;
namespace System.IO
{
partial class WinRTFileSystem
{
internal sealed class WinRTFileSystemObject : IFileSystemObject
{
private readonly bool _asDirectory;
// Cache the file/directory information
private readonly string _fullPath;
// Cache the file information
private IStorageItem _item;
// Cache any error retrieving the file/directory information
// We use this field in conjunction with the Refresh method which should never throw.
// If we succeed this is null, on failure we capture the Exception so that we can
// throw it when attempting to access the cached info later.
private ExceptionDispatchInfo _initializationException;
public WinRTFileSystemObject(string fullPath, bool asDirectory)
{
_asDirectory = asDirectory;
_fullPath = fullPath;
_item = null;
_initializationException = null;
}
public FileAttributes Attributes
{
get
{
EnsureItemInitialized();
if (_item == null)
return (FileAttributes)(-1);
return ConvertFileAttributes(_item.Attributes);
}
set
{
EnsureItemExists();
EnsureBackgroundThread();
try
{
SynchronousResultOf(SetAttributesAsync(_item, value));
}
catch (UnauthorizedAccessException)
{
// For consistency with Win32 we remap ACCESS_DENIED to ArgumentException
// Intentionally omit argument name since this is mimicking the Win32 sourced ArgumentException
throw new ArgumentException(SR.UnauthorizedAccess_IODenied_NoPathName /*, intentionally omitted*/);
}
// reset our attributes
_item = null;
}
}
public DateTimeOffset CreationTime
{
get
{
EnsureItemInitialized();
if (_item == null)
return DateTimeOffset.FromFileTime(0);
return _item.DateCreated;
}
set
{
EnsureItemExists();
// intentionally noop : not supported
}
}
public bool Exists
{
get
{
// Do not throw
if (_item == null)
Refresh();
if (_item == null)
return false;
return _item.IsOfType(_asDirectory ? StorageItemTypes.Folder : StorageItemTypes.File);
}
}
public DateTimeOffset LastAccessTime
{
get
{
EnsureItemInitialized();
if (_item == null)
return DateTimeOffset.FromFileTime(0);
EnsureBackgroundThread();
return SynchronousResultOf(GetLastAccessTimeAsync(_item));
}
set
{
EnsureItemExists();
// intentionally noop : not supported
}
}
public DateTimeOffset LastWriteTime
{
get
{
EnsureItemInitialized();
if (_item == null)
return DateTimeOffset.FromFileTime(0);
EnsureBackgroundThread();
return SynchronousResultOf(GetLastWriteTimeAsync(_item));
}
set
{
EnsureItemExists();
// intentionally noop : not supported
}
}
public long Length
{
get
{
EnsureItemExists();
EnsureBackgroundThread();
return (long)SynchronousResultOf(GetLengthAsync());
}
}
private async Task<ulong> GetLengthAsync()
{
BasicProperties properties = await _item.GetBasicPropertiesAsync().TranslateWinRTTask(_fullPath, _asDirectory);
return properties.Size;
}
// Consumes cached file/directory information and throw if any error occurred retrieving
// it, including file not found.
private void EnsureItemExists()
{
// If we've already tried and failed to get the item, throw
if (_initializationException != null)
_initializationException.Throw();
// We don't have the item, try and get it allowing any exception to be thrown
if (_item == null)
{
EnsureBackgroundThread();
_item = SynchronousResultOf(GetStorageItemAsync(_fullPath));
}
}
private void EnsureItemInitialized()
{
// Refresh only if we haven't already done so once.
if (_item == null && _initializationException == null)
{
// Refresh will ignore file-not-found errors.
Refresh();
}
// Refresh was unable to initialize the data
if (_initializationException != null)
_initializationException.Throw();
}
public void Refresh()
{
EnsureBackgroundThread();
SynchronousResultOf(RefreshAsync());
}
// Similar to WinRTFileSystem.TryGetStorageItemAsync but we only
// want to capture exceptions that are not related to file not
// found. This matches the behavior of the Win32 implementation.
private async Task RefreshAsync()
{
string directoryPath, itemName;
_item = null;
_initializationException = null;
try
{
PathHelpers.SplitDirectoryFile(_fullPath, out directoryPath, out itemName);
StorageFolder parent = null;
try
{
parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);
}
catch (DirectoryNotFoundException)
{
// Ignore DirectoryNotFound, in this case we just return null;
}
if (String.IsNullOrEmpty(itemName) || null == parent)
_item = parent;
else
_item = await parent.TryGetItemAsync(itemName).TranslateWinRTTask(_fullPath);
}
catch (Exception e)
{
_initializationException = ExceptionDispatchInfo.Capture(e);
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using osu.Framework.Lists;
namespace osu.Framework.Graphics.Transforms
{
/// <summary>
/// Tracks the lifetime of transforms for one specified target member.
/// </summary>
internal class TargetGroupingTransformTracker
{
/// <summary>
/// A list of <see cref="Transform"/>s associated with the <see cref="TargetGrouping"/>.
/// </summary>
public IReadOnlyList<Transform> Transforms => transforms;
/// <summary>
/// The member this instance is tracking.
/// </summary>
public readonly string TargetGrouping;
private readonly SortedList<Transform> transforms = new SortedList<Transform>(Transform.COMPARER);
private readonly Transformable transformable;
private readonly Queue<(ITransformSequence sequence, Action<ITransformSequence> action)> removalActions = new Queue<(ITransformSequence, Action<ITransformSequence>)>();
/// <summary>
/// Used to assign a monotonically increasing ID to <see cref="Transform"/>s as they are added. This member is
/// incremented whenever a <see cref="Transform"/> is added.
/// </summary>
private ulong currentTransformID;
/// <summary>
/// The index of the last transform in <see cref="transforms"/> to be applied to completion.
/// </summary>
private readonly Dictionary<string, int> lastAppliedTransformIndices = new Dictionary<string, int>();
/// <summary>
/// All <see cref="Transform.TargetMember"/>s which are handled by this tracker.
/// </summary>
public IEnumerable<string> TargetMembers => targetMembers;
private readonly HashSet<string> targetMembers = new HashSet<string>();
public TargetGroupingTransformTracker(Transformable transformable, string targetGrouping)
{
TargetGrouping = targetGrouping;
this.transformable = transformable;
}
public void UpdateTransforms(in double time, bool rewinding)
{
if (rewinding && !transformable.RemoveCompletedTransforms)
{
resetLastAppliedCache();
var appliedToEndReverts = new List<string>();
// Under the case that completed transforms are not removed, reversing the clock is permitted.
// We need to first look back through all the transforms and apply the start values of the ones that were previously
// applied, but now exist in the future relative to the current time.
for (int i = transforms.Count - 1; i >= 0; i--)
{
var t = transforms[i];
// rewind logic needs to only run on transforms which have been applied at least once.
if (!t.Applied)
continue;
// some specific transforms can be marked as non-rewindable.
if (!t.Rewindable)
continue;
if (time >= t.StartTime)
{
// we are in the middle of this transform, so we want to mark as not-completely-applied.
// note that we should only do this for the last transform of each TargetMember to avoid incorrect application order.
// the actual application will be in the main loop below now that AppliedToEnd is false.
if (!appliedToEndReverts.Contains(t.TargetMember))
{
t.AppliedToEnd = false;
appliedToEndReverts.Add(t.TargetMember);
}
}
else
{
// we are before the start time of this transform, so we want to eagerly apply the value at current time and mark as not-yet-applied.
// this transform will not be applied again unless we play forward in the future.
t.Apply(time);
t.Applied = false;
t.AppliedToEnd = false;
}
}
}
for (int i = getLastAppliedIndex(); i < transforms.Count; ++i)
{
var t = transforms[i];
var tCanRewind = !transformable.RemoveCompletedTransforms && t.Rewindable;
bool flushAppliedCache = false;
if (time < t.StartTime)
break;
if (!t.Applied)
{
// This is the first time we are updating this transform.
// We will find other still active transforms which act on the same target member and remove them.
// Since following transforms acting on the same target member are immediately removed when a
// new one is added, we can be sure that previous transforms were added before this one and can
// be safely removed.
for (int j = getLastAppliedIndex(t.TargetMember); j < i; ++j)
{
var u = transforms[j];
if (u.TargetMember != t.TargetMember) continue;
if (!u.AppliedToEnd)
// we may have applied the existing transforms too far into the future.
// we want to prepare to potentially read into the newly activated transform's StartTime,
// so we should re-apply using its StartTime as a basis.
u.Apply(t.StartTime);
if (!tCanRewind)
{
transforms.RemoveAt(j--);
flushAppliedCache = true;
i--;
if (u.AbortTargetSequence != null)
removalActions.Enqueue((u.AbortTargetSequence, s => s.TransformAborted()));
}
else
u.AppliedToEnd = true;
}
}
if (!t.HasStartValue)
{
t.ReadIntoStartValue();
t.HasStartValue = true;
}
if (!t.AppliedToEnd)
{
t.Apply(time);
t.AppliedToEnd = time >= t.EndTime;
if (t.AppliedToEnd)
{
if (!tCanRewind)
{
transforms.RemoveAt(i--);
flushAppliedCache = true;
}
if (t.IsLooping)
{
if (tCanRewind)
{
t.IsLooping = false;
t = t.Clone();
}
t.AppliedToEnd = false;
t.Applied = false;
t.HasStartValue = false;
t.IsLooping = true;
t.StartTime += t.LoopDelay;
t.EndTime += t.LoopDelay;
// this could be added back at a lower index than where we are currently iterating, but
// running the same transform twice isn't a huge deal.
transforms.Add(t);
flushAppliedCache = true;
}
else if (t.CompletionTargetSequence != null)
removalActions.Enqueue((t.CompletionTargetSequence, s => s.TransformCompleted()));
}
}
if (flushAppliedCache)
resetLastAppliedCache();
// if this transform is applied to end, we can be sure that all previous transforms have been completed.
else if (t.AppliedToEnd)
setLastAppliedIndex(t.TargetMember, i + 1);
}
invokePendingRemovalActions();
}
/// <summary>
/// Adds to this object a <see cref="Transform"/> which was previously populated using this object via
/// <see cref="TransformableExtensions.PopulateTransform{TValue, TEasing, TThis}"/>.
/// Added <see cref="Transform"/>s are immediately applied, and therefore have an immediate effect on this object if the current time of this
/// object falls within <see cref="Transform.StartTime"/> and <see cref="Transform.EndTime"/>.
/// If <see cref="Transformable.Clock"/> is null, e.g. because this object has just been constructed, then the given transform will be finished instantaneously.
/// </summary>
/// <param name="transform">The <see cref="Transform"/> to be added.</param>
/// <param name="customTransformID">When not null, the <see cref="Transform.TransformID"/> to assign for ordering.</param>
public void AddTransform(Transform transform, ulong? customTransformID = null)
{
Debug.Assert(!(transform.TransformID == 0 && transforms.Contains(transform)), $"Zero-id {nameof(Transform)}s should never be contained already.");
if (transform.TargetGrouping != TargetGrouping)
throw new ArgumentException($"Target grouping \"{transform.TargetGrouping}\" does not match this tracker's grouping \"{TargetGrouping}\".", nameof(transform));
targetMembers.Add(transform.TargetMember);
// This contains check may be optimized away in the future, should it become a bottleneck
if (transform.TransformID != 0 && transforms.Contains(transform))
throw new InvalidOperationException($"{nameof(Transformable)} may not contain the same {nameof(Transform)} more than once.");
transform.TransformID = customTransformID ?? ++currentTransformID;
int insertionIndex = transforms.Add(transform);
resetLastAppliedCache();
// Remove all existing following transforms touching the same property as this one.
for (int i = insertionIndex + 1; i < transforms.Count; ++i)
{
var t = transforms[i];
if (t.TargetMember == transform.TargetMember)
{
transforms.RemoveAt(i--);
if (t.AbortTargetSequence != null)
removalActions.Enqueue((t.AbortTargetSequence, s => s.TransformAborted()));
}
}
invokePendingRemovalActions();
}
/// <summary>
/// Removes a <see cref="Transform"/>.
/// </summary>
/// <param name="toRemove">The <see cref="Transform"/> to remove.</param>
public void RemoveTransform(Transform toRemove)
{
transforms.Remove(toRemove);
resetLastAppliedCache();
}
/// <summary>
/// Removes <see cref="Transform"/>s that start after <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to clear <see cref="Transform"/>s after.</param>
/// <param name="targetMember">
/// An optional <see cref="Transform.TargetMember"/> name of <see cref="Transform"/>s to clear.
/// Null for clearing all <see cref="Transform"/>s.
/// </param>
public virtual void ClearTransformsAfter(double time, string targetMember = null)
{
resetLastAppliedCache();
if (targetMember == null)
{
for (int i = 0; i < transforms.Count; i++)
{
var t = transforms[i];
if (t.StartTime >= time)
{
transforms.RemoveAt(i--);
if (t.AbortTargetSequence != null)
removalActions.Enqueue((t.AbortTargetSequence, s => s.TransformAborted()));
}
}
}
else
{
for (int i = 0; i < transforms.Count; i++)
{
var t = transforms[i];
if (t.TargetMember == targetMember && t.StartTime >= time)
{
transforms.RemoveAt(i--);
if (t.AbortTargetSequence != null)
removalActions.Enqueue((t.AbortTargetSequence, s => s.TransformAborted()));
}
}
}
invokePendingRemovalActions();
}
/// <summary>
/// Finishes specified <see cref="Transform"/>s, using their <see cref="Transform{TValue}.EndValue"/>.
/// </summary>
/// <param name="targetMember">
/// An optional <see cref="Transform.TargetMember"/> name of <see cref="Transform"/>s to finish.
/// Null for finishing all <see cref="Transform"/>s.
/// </param>
public virtual void FinishTransforms(string targetMember = null)
{
Func<Transform, bool> toFlushPredicate;
if (targetMember == null)
toFlushPredicate = t => !t.IsLooping;
else
toFlushPredicate = t => !t.IsLooping && t.TargetMember == targetMember;
// Flush is undefined for endlessly looping transforms
var toFlush = transforms.Where(toFlushPredicate).ToArray();
transforms.RemoveAll(t => toFlushPredicate(t));
resetLastAppliedCache();
foreach (Transform t in toFlush)
{
if (!t.HasStartValue)
{
t.ReadIntoStartValue();
t.HasStartValue = true;
}
t.Apply(t.EndTime);
t.TriggerComplete();
}
}
private void invokePendingRemovalActions()
{
while (removalActions.TryDequeue(out var item))
item.action(item.sequence);
}
/// <summary>
/// Retrieve the last transform index that was <see cref="Transform.AppliedToEnd"/>.
/// </summary>
/// <param name="targetMember">An optional target member. If null, the lowest common last application is returned.</param>
private int getLastAppliedIndex(string targetMember = null)
{
if (targetMember == null)
{
int min = int.MaxValue;
foreach (int i in lastAppliedTransformIndices.Values)
{
if (i < min)
min = i;
}
return min;
}
if (lastAppliedTransformIndices.TryGetValue(targetMember, out int val))
return val;
return 0;
}
/// <summary>
/// Set the last transform index that was <see cref="Transform.AppliedToEnd"/> for a specific target member.
/// </summary>
/// <param name="targetMember">The target member to set the index of.</param>
/// <param name="index">The index of the transform in <see cref="transforms"/>.</param>
private void setLastAppliedIndex(string targetMember, int index)
{
lastAppliedTransformIndices[targetMember] = index;
}
/// <summary>
/// Reset the last applied index cache completely.
/// </summary>
private void resetLastAppliedCache()
{
foreach (var tracked in targetMembers)
lastAppliedTransformIndices[tracked] = 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Drawing;
using System.IO;
namespace Vestris.ResourceLib
{
/// <summary>
/// A device-independent image consists of a BITMAPINFOHEADER where
/// bmWidth is the width of the image andbmHeight is double the height
/// of the image, followed by the bitmap color table, followed by the image
/// pixels, followed by the mask pixels.
/// </summary>
public class DeviceIndependentBitmap
{
private Gdi32.BITMAPINFOHEADER _header = new Gdi32.BITMAPINFOHEADER();
private byte[] _data = null;
private Bitmap _mask = null;
private Bitmap _color = null;
private Bitmap _image = null;
/// <summary>
/// Raw image data.
/// </summary>
public byte[] Data
{
get
{
return _data;
}
set
{
_data = value;
IntPtr pData = Marshal.AllocHGlobal(Marshal.SizeOf(_header));
try
{
Marshal.Copy(_data, 0, pData, Marshal.SizeOf(_header));
_header = (Gdi32.BITMAPINFOHEADER)Marshal.PtrToStructure(
pData, typeof(Gdi32.BITMAPINFOHEADER));
}
finally
{
Marshal.FreeHGlobal(pData);
}
}
}
/// <summary>
/// Bitmap info header.
/// </summary>
public Gdi32.BITMAPINFOHEADER Header
{
get
{
return _header;
}
}
/// <summary>
/// Bitmap size in bytes.
/// </summary>
public int Size
{
get
{
return _data.Length;
}
}
/// <summary>
/// A new icon image.
/// </summary>
public DeviceIndependentBitmap()
{
}
/// <summary>
/// A device-independent bitmap.
/// </summary>
/// <param name="data">Bitmap data.</param>
public DeviceIndependentBitmap(byte[] data)
{
Data = data;
}
/// <summary>
/// Create a copy of an image.
/// </summary>
/// <param name="image">Source image.</param>
public DeviceIndependentBitmap(DeviceIndependentBitmap image)
{
_data = new byte[image._data.Length];
Buffer.BlockCopy(image._data, 0, _data, 0, image._data.Length);
_header = image._header;
}
/// <summary>
/// Read icon data.
/// </summary>
/// <param name="lpData">Pointer to the beginning of icon data.</param>
/// <param name="size">Icon data size.</param>
internal void Read(IntPtr lpData, uint size)
{
_header = (Gdi32.BITMAPINFOHEADER)Marshal.PtrToStructure(
lpData, typeof(Gdi32.BITMAPINFOHEADER));
_data = new byte[size];
Marshal.Copy(lpData, _data, 0, _data.Length);
}
/// <summary>
/// Size of the image mask.
/// </summary>
private Int32 MaskImageSize
{
get
{
return (Int32)(_header.biHeight / 2 * GetDIBRowWidth(_header.biWidth));
}
}
private Int32 XorImageSize
{
get
{
return (Int32)(_header.biHeight / 2 *
GetDIBRowWidth(_header.biWidth * _header.biBitCount * _header.biPlanes));
}
}
/// <summary>
/// Position of the DIB bitmap bits within a DIB bitmap array.
/// </summary>
private Int32 XorImageIndex
{
get
{
return (Int32)(Marshal.SizeOf(_header) +
ColorCount * Marshal.SizeOf(new Gdi32.RGBQUAD()));
}
}
/// <summary>
/// Number of colors in the palette.
/// </summary>
private UInt32 ColorCount
{
get
{
if (_header.biClrUsed != 0)
return _header.biClrUsed;
if (_header.biBitCount <= 8)
return (UInt32)(1 << _header.biBitCount);
return 0;
}
}
private Int32 MaskImageIndex
{
get
{
return XorImageIndex + XorImageSize;
}
}
/// <summary>
/// Returns the width of a row in a DIB Bitmap given the number of bits. DIB Bitmap rows always align on a DWORD boundary.
/// </summary>
/// <param name="width">Number of bits.</param>
/// <returns>Width of a row in bytes.</returns>
private Int32 GetDIBRowWidth(int width)
{
return (Int32)((width + 31) / 32) * 4;
}
/// <summary>
/// Bitmap monochrome mask.
/// </summary>
public Bitmap Mask
{
get
{
if (_mask == null)
{
IntPtr hdc = IntPtr.Zero;
IntPtr hBmp = IntPtr.Zero;
IntPtr hBmpOld = IntPtr.Zero;
IntPtr bitsInfo = IntPtr.Zero;
IntPtr bits = IntPtr.Zero;
try
{
// extract monochrome mask
hdc = Gdi32.CreateCompatibleDC(IntPtr.Zero);
if (hdc == null)
throw new Win32Exception(Marshal.GetLastWin32Error());
hBmp = Gdi32.CreateCompatibleBitmap(hdc, _header.biWidth, _header.biHeight / 2);
if (hBmp == null)
throw new Win32Exception(Marshal.GetLastWin32Error());
hBmpOld = Gdi32.SelectObject(hdc, hBmp);
// prepare BitmapInfoHeader for mono bitmap:
int monoBmHdrSize = (int)_header.biSize + Marshal.SizeOf(new Gdi32.RGBQUAD()) * 2;
bitsInfo = Marshal.AllocCoTaskMem(monoBmHdrSize);
Marshal.WriteInt32(bitsInfo, Marshal.SizeOf(_header));
Marshal.WriteInt32(bitsInfo, 4, _header.biWidth);
Marshal.WriteInt32(bitsInfo, 8, _header.biHeight / 2);
Marshal.WriteInt16(bitsInfo, 12, 1);
Marshal.WriteInt16(bitsInfo, 14, 1);
Marshal.WriteInt32(bitsInfo, 16, (Int32)Gdi32.BitmapCompression.BI_RGB);
Marshal.WriteInt32(bitsInfo, 20, 0);
Marshal.WriteInt32(bitsInfo, 24, 0);
Marshal.WriteInt32(bitsInfo, 28, 0);
Marshal.WriteInt32(bitsInfo, 32, 0);
Marshal.WriteInt32(bitsInfo, 36, 0);
// black and white color indices
Marshal.WriteInt32(bitsInfo, 40, 0);
Marshal.WriteByte(bitsInfo, 44, 255);
Marshal.WriteByte(bitsInfo, 45, 255);
Marshal.WriteByte(bitsInfo, 46, 255);
Marshal.WriteByte(bitsInfo, 47, 0);
// prepare mask bits
bits = Marshal.AllocCoTaskMem(MaskImageSize);
Marshal.Copy(_data, MaskImageIndex, bits, MaskImageSize);
if (0 == Gdi32.SetDIBitsToDevice(hdc, 0, 0, (UInt32)_header.biWidth, (UInt32)_header.biHeight / 2,
0, 0, 0, (UInt32)_header.biHeight / 2, bits, bitsInfo, (UInt32)Gdi32.DIBColors.DIB_RGB_COLORS))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
_mask = Bitmap.FromHbitmap(hBmp);
}
finally
{
if (bits != IntPtr.Zero) Marshal.FreeCoTaskMem(bits);
if (bitsInfo != IntPtr.Zero) Marshal.FreeCoTaskMem(bitsInfo);
if (hdc != IntPtr.Zero) Gdi32.SelectObject(hdc, hBmpOld);
if (hdc != IntPtr.Zero) Gdi32.DeleteObject(hdc);
}
}
return _mask;
}
}
/// <summary>
/// Bitmap color (XOR) part of the image.
/// </summary>
public Bitmap Color
{
get
{
if (_color == null)
{
IntPtr hdcDesktop = IntPtr.Zero;
IntPtr hdc = IntPtr.Zero;
IntPtr hBmp = IntPtr.Zero;
IntPtr hBmpOld = IntPtr.Zero;
IntPtr bitsInfo = IntPtr.Zero;
IntPtr bits = IntPtr.Zero;
try
{
hdcDesktop = User32.GetDC(IntPtr.Zero); // Gdi32.CreateDC("DISPLAY", null, null, IntPtr.Zero);
if (hdcDesktop == null)
throw new Win32Exception(Marshal.GetLastWin32Error());
hdc = Gdi32.CreateCompatibleDC(hdcDesktop);
if (hdc == null)
throw new Win32Exception(Marshal.GetLastWin32Error());
hBmp = Gdi32.CreateCompatibleBitmap(hdcDesktop, _header.biWidth, _header.biHeight / 2);
if (hBmp == null)
throw new Win32Exception(Marshal.GetLastWin32Error());
hBmpOld = Gdi32.SelectObject(hdc, hBmp);
// bitmap header
bitsInfo = Marshal.AllocCoTaskMem(XorImageIndex);
if (bitsInfo == null)
throw new Win32Exception(Marshal.GetLastWin32Error());
Marshal.Copy(_data, 0, bitsInfo, XorImageIndex);
// fix the height
Marshal.WriteInt32(bitsInfo, 8, _header.biHeight / 2);
// XOR bits
bits = Marshal.AllocCoTaskMem(XorImageSize);
Marshal.Copy(_data, XorImageIndex, bits, XorImageSize);
if (0 == Gdi32.SetDIBitsToDevice(hdc, 0, 0, (UInt32)_header.biWidth, (UInt32)_header.biHeight / 2,
0, 0, 0, (UInt32)(_header.biHeight / 2), bits, bitsInfo, (Int32)Gdi32.DIBColors.DIB_RGB_COLORS))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
_color = Bitmap.FromHbitmap(hBmp);
}
finally
{
if (hdcDesktop != IntPtr.Zero) Gdi32.DeleteDC(hdcDesktop);
if (bits != IntPtr.Zero) Marshal.FreeCoTaskMem(bits);
if (bitsInfo != IntPtr.Zero) Marshal.FreeCoTaskMem(bitsInfo);
if (hdc != IntPtr.Zero) Gdi32.SelectObject(hdc, hBmpOld);
if (hdc != IntPtr.Zero) Gdi32.DeleteObject(hdc);
}
}
return _color;
}
}
/// <summary>
/// Complete image.
/// </summary>
public Bitmap Image
{
get
{
if (_image == null)
{
IntPtr hDCScreen = IntPtr.Zero;
IntPtr bits = IntPtr.Zero;
IntPtr hDCScreenOUTBmp = IntPtr.Zero;
IntPtr hBitmapOUTBmp = IntPtr.Zero;
try
{
hDCScreen = User32.GetDC(IntPtr.Zero);
if (hDCScreen == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
// Image
Gdi32.BITMAPINFO bitmapInfo = new Gdi32.BITMAPINFO();
bitmapInfo.bmiHeader = _header;
// bitmapInfo.bmiColors = Tools.StandarizePalette(mEncoder.Colors);
hDCScreenOUTBmp = Gdi32.CreateCompatibleDC(hDCScreen);
hBitmapOUTBmp = Gdi32.CreateDIBSection(hDCScreenOUTBmp, ref bitmapInfo, 0, out bits, IntPtr.Zero, 0);
Marshal.Copy(_data, XorImageIndex, bits, XorImageSize);
_image = Bitmap.FromHbitmap(hBitmapOUTBmp);
}
finally
{
if (hDCScreen != IntPtr.Zero) User32.ReleaseDC(IntPtr.Zero, hDCScreen);
if (hBitmapOUTBmp != IntPtr.Zero) Gdi32.DeleteObject(hBitmapOUTBmp);
if (hDCScreenOUTBmp != IntPtr.Zero) Gdi32.DeleteDC(hDCScreenOUTBmp);
}
}
return _image;
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.PythonTools.Commands;
using Microsoft.PythonTools.Environments;
using Microsoft.PythonTools.EnvironmentsList;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Infrastructure.Commands;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.InterpreterList {
[Guid(PythonConstants.InterpreterListToolWindowGuid)]
sealed class InterpreterListToolWindow : ToolWindowPane {
private IServiceProvider _site;
private UIThreadBase _uiThread;
private PythonToolsService _pyService;
private Redirector _outputWindow;
private IVsStatusbar _statusBar;
private readonly object _commandsLock = new object();
private readonly Dictionary<Command, MenuCommand> _commands = new Dictionary<Command, MenuCommand>();
private readonly Dictionary<EnvironmentView, string> _cachedScriptPaths;
public InterpreterListToolWindow(IServiceProvider services) : base(services) {
ToolBar = new CommandID(GuidList.guidPythonToolsCmdSet, PkgCmdIDList.EnvWindowToolbar);
_site = services;
_cachedScriptPaths = new Dictionary<EnvironmentView, string>();
}
protected override void OnCreate() {
base.OnCreate();
_pyService = _site.GetPythonToolsService();
_uiThread = _site.GetUIThread();
_pyService.InteractiveOptions.Changed += InteractiveOptions_Changed;
// TODO: Get PYEnvironment added to image list
BitmapImageMoniker = KnownMonikers.DockPanel;
Caption = Strings.Environments;
_outputWindow = OutputWindowRedirector.GetGeneral(_site);
Debug.Assert(_outputWindow != null);
_statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar;
var list = new ToolWindow();
list.ViewCreated += List_ViewCreated;
list.ViewSelected += List_ViewSelected;
list.Site = _site;
try {
list.TelemetryLogger = _pyService.Logger;
} catch (Exception ex) {
Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
}
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.OpenInteractiveWindow,
OpenInteractiveWindow_Executed,
OpenInteractiveWindow_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.OpenInteractiveScripts,
OpenInteractiveScripts_Executed,
OpenInteractiveScripts_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentPathsExtension.StartInterpreter,
StartInterpreter_Executed,
StartInterpreter_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentPathsExtension.StartWindowsInterpreter,
StartInterpreter_Executed,
StartInterpreter_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
ApplicationCommands.Help,
OnlineHelp_Executed,
OnlineHelp_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
ToolWindow.UnhandledException,
UnhandledException_Executed,
UnhandledException_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.OpenInPowerShell,
OpenInPowerShell_Executed,
OpenInPowerShell_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.OpenInCommandPrompt,
OpenInCommandPrompt_Executed,
OpenInCommandPrompt_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentPathsExtension.OpenInBrowser,
OpenInBrowser_Executed,
OpenInBrowser_CanExecute
));
list.CommandBindings.Add(new CommandBinding(
EnvironmentView.Delete,
DeleteEnvironment_Executed,
DeleteEnvironment_CanExecute
));
RegisterCommands(
CommandAsyncToOleMenuCommandShimFactory.CreateCommand(GuidList.guidPythonToolsCmdSet, (int)PkgCmdIDList.cmdidAddEnvironment, new AddEnvironmentCommand(this))
);
Content = list;
}
internal void RegisterCommands(params MenuCommand[] commands) {
_uiThread.MustBeCalledFromUIThreadOrThrow();
if (GetService(typeof(IMenuCommandService)) is OleMenuCommandService mcs) {
foreach (var command in commands) {
mcs.AddCommand(command);
}
}
}
private void InteractiveOptions_Changed(object sender, EventArgs e) {
lock (_cachedScriptPaths) {
_cachedScriptPaths.Clear();
}
CommandManager.InvalidateRequerySuggested();
}
private string GetScriptPath(EnvironmentView view) {
if (view == null) {
return null;
}
string path;
lock (_cachedScriptPaths) {
if (_cachedScriptPaths.TryGetValue(view, out path)) {
return path;
}
}
try {
path = _uiThread.Invoke(() => PythonInteractiveEvaluator.GetScriptsPath(
_site,
view.Description,
view.Factory.Configuration,
false
));
} catch (DirectoryNotFoundException) {
path = null;
} catch (Exception ex) when (!ex.IsCriticalException()) {
view.Dispatcher.BeginInvoke((Action)(() => ex.ReportUnhandledException(_site, GetType())), DispatcherPriority.ApplicationIdle);
path = null;
}
lock (_cachedScriptPaths) {
_cachedScriptPaths[view] = path;
}
return path;
}
private void OpenInteractiveScripts_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var path = GetScriptPath(e.Parameter as EnvironmentView);
e.CanExecute = path != null;
e.Handled = true;
}
private bool EnsureScriptDirectory(string path) {
if (string.IsNullOrEmpty(path)) {
return false;
}
if (!Directory.Exists(path)) {
try {
Directory.CreateDirectory(path);
File.WriteAllText(PathUtils.GetAbsoluteFilePath(path, "readme.txt"), Strings.ReplScriptPathReadmeContents);
} catch (Exception ex) when (!ex.IsCriticalException()) {
TaskDialog.ForException(_site, ex, issueTrackerUrl: Strings.IssueTrackerUrl).ShowModal();
return false;
}
}
return true;
}
private void OpenInteractiveScripts_Executed(object sender, ExecutedRoutedEventArgs e) {
var path = GetScriptPath(e.Parameter as EnvironmentView);
if (!EnsureScriptDirectory(path)) {
return;
}
var psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe");
psi.Arguments = "\"" + path + "\"";
Process.Start(psi).Dispose();
e.Handled = true;
}
private bool QueryIPythonEnabled(EnvironmentView view) {
var path = GetScriptPath(view);
return path != null && File.Exists(PathUtils.GetAbsoluteFilePath(path, "mode.txt"));
}
private void SetIPythonEnabled(EnvironmentView view, bool enable) {
var path = GetScriptPath(view);
if (!EnsureScriptDirectory(path)) {
return;
}
try {
path = PathUtils.GetAbsoluteFilePath(path, "mode.txt");
if (enable) {
File.WriteAllText(path, Strings.ReplScriptPathIPythonModeTxtContents);
} else {
if (File.Exists(path)) {
File.Delete(path);
}
}
} catch (Exception ex) when (!ex.IsCriticalException()) {
TaskDialog.ForException(_site, ex, issueTrackerUrl: Strings.IssueTrackerUrl).ShowModal();
}
}
private void List_ViewCreated(object sender, EnvironmentViewEventArgs e) {
var view = e.View;
if (view.Factory == null) {
return;
}
view.IPythonModeEnabledSetter = SetIPythonEnabled;
view.IPythonModeEnabledGetter = QueryIPythonEnabled;
}
private void List_ViewSelected(object sender, EnvironmentViewEventArgs e) {
var view = e.View;
if (view.Factory == null || view.ExtensionsCreated) {
return;
}
// We used to create all the extensions up front in List_ViewCreated
// but that slowed down initialization of the tool window considerably
// due to the package manager extension in particular.
// We now create the extensions only if they are likely to be used,
// the first time an environment is selected in the list view.
view.ExtensionsCreated = true;
foreach (var pm in (_site.GetComponentModel().GetService<IInterpreterOptionsService>()?.GetPackageManagers(view.Factory)).MaybeEnumerate()) {
try {
var pep = new PipExtensionProvider(view.Factory, pm);
pep.QueryShouldElevate += PipExtensionProvider_QueryShouldElevate;
pep.OperationStarted += PipExtensionProvider_OperationStarted;
pep.OutputTextReceived += PipExtensionProvider_OutputTextReceived;
pep.ErrorTextReceived += PipExtensionProvider_ErrorTextReceived;
pep.OperationFinished += PipExtensionProvider_OperationFinished;
view.Extensions.Add(pep);
} catch (NotSupportedException) {
}
}
var model = _site.GetComponentModel();
if (model != null) {
try {
foreach (var provider in model.GetExtensions<IEnvironmentViewExtensionProvider>()) {
try {
var ext = provider.CreateExtension(view);
if (ext != null) {
view.Extensions.Add(ext);
}
} catch (Exception ex) {
LogLoadException(provider, ex);
}
}
} catch (Exception ex2) {
LogLoadException(null, ex2);
}
}
}
private void LogLoadException(IEnvironmentViewExtensionProvider provider, Exception ex) {
string message;
if (provider == null) {
message = Strings.ErrorLoadingEnvironmentViewExtensions.FormatUI(ex);
} else {
message = Strings.ErrorLoadingEnvironmentViewExtension.FormatUI(provider.GetType().FullName, ex);
}
Debug.Fail(message);
var log = _site.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
if (log != null) {
log.LogEntry(
(uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR,
Strings.ProductTitle,
message
);
}
}
private void PipExtensionProvider_QueryShouldElevate(object sender, QueryShouldElevateEventArgs e) {
try {
e.Elevate = VsPackageManagerUI.ShouldElevate(_site, e.Factory.Configuration, "pip");
} catch (OperationCanceledException) {
e.Cancel = true;
}
}
private void PipExtensionProvider_OperationStarted(object sender, OutputEventArgs e) {
if (_statusBar != null) {
_statusBar.SetText(e.Data);
}
if (_pyService.GeneralOptions.ShowOutputWindowForPackageInstallation) {
_outputWindow.ShowAndActivate();
}
}
private void PipExtensionProvider_OutputTextReceived(object sender, OutputEventArgs e) {
_outputWindow.WriteLine(e.Data.TrimEndNewline());
}
private void PipExtensionProvider_ErrorTextReceived(object sender, OutputEventArgs e) {
_outputWindow.WriteErrorLine(e.Data.TrimEndNewline());
}
private void PipExtensionProvider_OperationFinished(object sender, OperationFinishedEventArgs e) {
if (_pyService.GeneralOptions.ShowOutputWindowForPackageInstallation) {
_outputWindow.ShowAndActivate();
}
}
private void UnhandledException_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Parameter is ExceptionDispatchInfo;
}
private void UnhandledException_Executed(object sender, ExecutedRoutedEventArgs e) {
var ex = (ExceptionDispatchInfo)e.Parameter;
Debug.Assert(ex != null, "Unhandled exception with no exception object");
var td = TaskDialog.ForException(_site, ex.SourceException, string.Empty, Strings.IssueTrackerUrl);
td.Title = Strings.ProductTitle;
td.ShowModal();
}
private void OpenInteractiveWindow_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view != null &&
view.Factory != null &&
view.Factory.Configuration != null &&
File.Exists(view.Factory.Configuration.InterpreterPath);
}
private void OpenInteractiveWindow_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (EnvironmentView)e.Parameter;
var config = view.Factory.Configuration;
var replId = PythonReplEvaluatorProvider.GetEvaluatorId(config);
var compModel = _site.GetComponentModel();
var service = compModel.GetService<InteractiveWindowProvider>();
IVsInteractiveWindow window;
// TODO: Figure out another way to get the project
//var provider = _service.KnownProviders.OfType<LoadedProjectInterpreterFactoryProvider>().FirstOrDefault();
//var vsProject = provider == null ?
// null :
// provider.GetProject(factory);
//PythonProjectNode project = vsProject == null ? null : vsProject.GetPythonProject();
try {
window = service.OpenOrCreate(replId);
} catch (Exception ex) when (!ex.IsCriticalException()) {
TaskDialog.ForException(_site, ex, Strings.ErrorOpeningInteractiveWindow, Strings.IssueTrackerUrl).ShowModal();
return;
}
window?.Show(true);
}
private void StartInterpreter_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view != null && File.Exists(e.Command == EnvironmentPathsExtension.StartInterpreter ?
view.Factory.Configuration.InterpreterPath :
view.Factory.Configuration.GetWindowsInterpreterPath());
e.Handled = true;
}
private void StartInterpreter_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (EnvironmentView)e.Parameter;
var config = new LaunchConfiguration(view.Factory.Configuration) {
PreferWindowedInterpreter = (e.Command == EnvironmentPathsExtension.StartWindowsInterpreter),
WorkingDirectory = view.Factory.Configuration.GetPrefixPath(),
SearchPaths = new List<string>()
};
var sln = (IVsSolution)_site.GetService(typeof(SVsSolution));
foreach (var pyProj in sln.EnumerateLoadedPythonProjects()) {
if (pyProj.InterpreterConfigurations.Contains(config.Interpreter)) {
config.SearchPaths.AddRange(pyProj.GetSearchPaths());
}
}
config.LaunchOptions[PythonConstants.NeverPauseOnExit] = "true";
Process.Start(Debugger.DebugLaunchHelper.CreateProcessStartInfo(_site, config)).Dispose();
}
private void OnlineHelp_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = _site != null;
e.Handled = true;
}
private void OnlineHelp_Executed(object sender, ExecutedRoutedEventArgs e) {
VisualStudioTools.CommonPackage.OpenWebBrowser(_site, PythonToolsPackage.InterpreterHelpUrl);
e.Handled = true;
}
private static readonly string[] PathSuffixes = new[] { "", "Scripts" };
private static string GetPathEntries(EnvironmentView view) {
if (!Directory.Exists(view?.PrefixPath)) {
return null;
}
return string.Join(";", PathSuffixes
.Select(s => PathUtils.GetAbsoluteDirectoryPath(view.PrefixPath, s))
.Where(Directory.Exists));
}
private void DeleteEnvironment_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view?.CanBeDeleted == true;
e.Handled = true;
}
private void DeleteEnvironment_Executed(object sender, ExecutedRoutedEventArgs e) {
// TODO: this is assuming that all environments that CanBeDeleted are conda environments, which may not be true in the future
var view = e.Parameter as EnvironmentView;
var result = MessageBox.Show(
Resources.EnvironmentPathsExtensionDeleteConfirmation.FormatUI(view.Configuration.GetPrefixPath()),
Resources.ProductTitle,
MessageBoxButton.YesNo,
MessageBoxImage.Question
);
if (result != MessageBoxResult.Yes) {
return;
}
var compModel = _site.GetService(typeof(SComponentModel)) as IComponentModel;
var registry = compModel.GetService<IInterpreterRegistryService>();
var mgr = CondaEnvironmentManager.Create(_site);
mgr.DeleteAsync(
view.Configuration.GetPrefixPath(),
new CondaEnvironmentManagerUI(_outputWindow),
CancellationToken.None
).HandleAllExceptions(_site, GetType()).DoNotWait();
}
class CondaEnvironmentManagerUI : ICondaEnvironmentManagerUI {
private readonly Redirector _window;
public CondaEnvironmentManagerUI(Redirector window) {
_window = window;
}
public void OnErrorTextReceived(ICondaEnvironmentManager sender, string text) {
_window.WriteErrorLine(text.TrimEndNewline());
}
public void OnOperationFinished(ICondaEnvironmentManager sender, string operation, bool success) {
}
public void OnOperationStarted(ICondaEnvironmentManager sender, string operation) {
_window.ShowAndActivate();
}
public void OnOutputTextReceived(ICondaEnvironmentManager sender, string text) {
_window.WriteLine(text.TrimEndNewline());
}
}
private void OpenInCommandPrompt_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = Directory.Exists(view?.PrefixPath);
e.Handled = true;
}
private void OpenInCommandPrompt_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (EnvironmentView)e.Parameter;
var paths = GetPathEntries(view);
var pathCmd = string.IsNullOrEmpty(paths) ? "" : string.Format("set PATH={0};%PATH% & ", paths);
var psi = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "cmd.exe")) {
Arguments = string.Join(" ", new[] {
"/S",
"/K",
pathCmd + string.Format("title {0} environment", view.Description)
}.Select(ProcessOutput.QuoteSingleArgument)),
WorkingDirectory = view.PrefixPath
};
Process.Start(psi).Dispose();
}
private void OpenInPowerShell_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = Directory.Exists(view?.PrefixPath);
e.Handled = true;
}
private void OpenInPowerShell_Executed(object sender, ExecutedRoutedEventArgs e) {
var view = (EnvironmentView)e.Parameter;
var paths = GetPathEntries(view);
var pathCmd = string.IsNullOrEmpty(paths) ? "" : string.Format("$env:PATH='{0};' + $env:PATH; ", paths);
var psi = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe")) {
Arguments = string.Join(" ", new[] {
"-NoLogo",
"-NoExit",
"-Command",
pathCmd + string.Format("(Get-Host).UI.RawUI.WindowTitle = '{0} environment'", view.Description)
}.Select(ProcessOutput.QuoteSingleArgument)),
WorkingDirectory = view.PrefixPath
};
Process.Start(psi).Dispose();
}
private void OpenInBrowser_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Parameter is string;
e.Handled = true;
}
private void OpenInBrowser_Executed(object sender, ExecutedRoutedEventArgs e) {
PythonToolsPackage.OpenWebBrowser(_site, (string)e.Parameter);
}
internal static async System.Threading.Tasks.Task OpenAtAsync(IServiceProvider site, string viewId, Type extension) {
var service = (IPythonToolsToolWindowService)site?.GetService(typeof(IPythonToolsToolWindowService));
if (service == null) {
Debug.Fail("Failed to get environment list window");
return;
}
var wnd = await service.GetWindowPaneAsync(typeof(InterpreterListToolWindow), true) as InterpreterListToolWindow;
if (!(wnd?.Content is ToolWindow envs)) {
Debug.Fail("Failed to get environment list window");
return;
}
ErrorHandler.ThrowOnFailure((wnd.Frame as IVsWindowFrame)?.Show() ?? 0);
SelectEnvAndExt(envs, viewId, extension, 3);
}
internal static async System.Threading.Tasks.Task OpenAtAsync(IServiceProvider site, IPythonInterpreterFactory interpreter, Type extension = null) {
var service = (IPythonToolsToolWindowService)site?.GetService(typeof(IPythonToolsToolWindowService));
if (service == null) {
Debug.Fail("Failed to get environment list window");
return;
}
var wnd = await service.GetWindowPaneAsync(typeof(InterpreterListToolWindow), true) as InterpreterListToolWindow;
if (!(wnd?.Content is ToolWindow envs)) {
Debug.Fail("Failed to get environment list window");
return;
}
ErrorHandler.ThrowOnFailure((wnd.Frame as IVsWindowFrame)?.Show() ?? 0);
if (extension == null) {
SelectEnv(envs, interpreter, 3);
} else {
SelectEnvAndExt(envs, interpreter, extension, 3);
}
}
private static void SelectEnv(ToolWindow envs, IPythonInterpreterFactory interpreter, int retries) {
if (retries <= 0) {
Debug.Fail("Failed to select environment after multiple retries");
return;
}
var select = envs.IsLoaded ? envs.Environments.OfType<EnvironmentView>().FirstOrDefault(e => e.Factory == interpreter) : null;
if (select == null) {
envs.Dispatcher.InvokeAsync(() => SelectEnv(envs, interpreter, retries - 1), DispatcherPriority.Background);
return;
}
envs.Environments.MoveCurrentTo(select);
}
private static void SelectEnvAndExt(ToolWindow envs, IPythonInterpreterFactory interpreter, Type extension, int retries) {
if (retries <= 0) {
Debug.Fail("Failed to select environment/extension after multiple retries");
return;
}
var select = envs.IsLoaded ? envs.Environments.OfType<EnvironmentView>().FirstOrDefault(e => e.Factory == interpreter) : null;
if (select == null) {
envs.Dispatcher.InvokeAsync(() => SelectEnvAndExt(envs, interpreter, extension, retries - 1), DispatcherPriority.Background);
return;
}
envs.OnViewSelected(select);
var ext = select?.Extensions.FirstOrDefault(e => e != null && extension.IsEquivalentTo(e.GetType()));
envs.Environments.MoveCurrentTo(select);
if (ext != null) {
var exts = envs.Extensions;
if (exts != null && exts.Contains(ext)) {
exts.MoveCurrentTo(ext);
((ext as IEnvironmentViewExtension)?.WpfObject as ICanFocus)?.Focus();
}
}
}
private static void SelectEnvAndExt(ToolWindow envs, string viewId, Type extension, int retries) {
if (retries <= 0) {
Debug.Fail("Failed to select environment/extension after multiple retries");
return;
}
var select = envs.IsLoaded ? envs.Environments.OfType<EnvironmentView>().FirstOrDefault(e => e.Configuration.Id == viewId) : null;
if (select == null) {
envs.Dispatcher.InvokeAsync(() => SelectEnvAndExt(envs, viewId, extension, retries - 1), DispatcherPriority.Background);
return;
}
envs.OnViewSelected(select);
var ext = select?.Extensions.FirstOrDefault(e => e != null && extension.IsEquivalentTo(e.GetType()));
envs.Environments.MoveCurrentTo(select);
if (ext != null) {
var exts = envs.Extensions;
if (exts != null && exts.Contains(ext)) {
exts.MoveCurrentTo(ext);
((ext as IEnvironmentViewExtension)?.WpfObject as ICanFocus)?.Focus();
}
}
}
}
}
| |
using System;
using SharpDX;
using SharpDX.Toolkit.Graphics;
namespace factor10.VisionThing.Effects
{
/// <summary>
/// Track which effect parameters need to be recomputed during the next OnApply.
/// </summary>
[Flags]
internal enum EffectDirtyFlags
{
WorldViewProj = 1,
World = 2,
EyePosition = 4,
MaterialColor = 8,
Fog = 16,
FogEnable = 32,
AlphaTest = 64,
ShaderIndex = 128,
All = -1
}
/// <summary>
/// Helper code shared between the various built-in effects.
/// </summary>
internal static class EffectHelpers
{
/// <summary>
/// Sets up the standard key/fill/back lighting rig.
/// </summary>
internal static Vector3 EnableDefaultLighting(DirectionalLight light0, DirectionalLight light1, DirectionalLight light2)
{
// Key light.
light0.Direction = new Vector3(-0.5265408f, -0.5735765f, -0.6275069f);
light0.DiffuseColor = new Vector3(1, 0.9607844f, 0.8078432f);
light0.SpecularColor = new Vector3(1, 0.9607844f, 0.8078432f);
light0.Enabled = true;
// Fill light.
light1.Direction = new Vector3(0.7198464f, 0.3420201f, 0.6040227f);
light1.DiffuseColor = new Vector3(0.9647059f, 0.7607844f, 0.4078432f);
light1.SpecularColor = Vector3.Zero;
light1.Enabled = true;
// Back light.
light2.Direction = new Vector3(0.4545195f, -0.7660444f, 0.4545195f);
light2.DiffuseColor = new Vector3(0.3231373f, 0.3607844f, 0.3937255f);
light2.SpecularColor = new Vector3(0.3231373f, 0.3607844f, 0.3937255f);
light2.Enabled = true;
// Ambient light.
return new Vector3(0.05333332f, 0.09882354f, 0.1819608f);
}
/// <summary>
/// Lazily recomputes the world+view+projection matrix and
/// fog vector based on the current effect parameter settings.
/// </summary>
internal static EffectDirtyFlags SetWorldViewProjAndFog(EffectDirtyFlags dirtyFlags,
ref Matrix world, ref Matrix view, ref Matrix projection, ref Matrix worldView,
bool fogEnabled, float fogStart, float fogEnd,
EffectParameter worldViewProjParam, EffectParameter fogVectorParam)
{
// Recompute the world+view+projection matrix?
if ((dirtyFlags & EffectDirtyFlags.WorldViewProj) != 0)
{
Matrix worldViewProj;
Matrix.Multiply(ref world, ref view, out worldView);
Matrix.Multiply(ref worldView, ref projection, out worldViewProj);
worldViewProjParam.SetValue(worldViewProj);
dirtyFlags &= ~EffectDirtyFlags.WorldViewProj;
}
if (fogEnabled)
{
// Recompute the fog vector?
if ((dirtyFlags & (EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable)) != 0)
{
SetFogVector(ref worldView, fogStart, fogEnd, fogVectorParam);
dirtyFlags &= ~(EffectDirtyFlags.Fog | EffectDirtyFlags.FogEnable);
}
}
else
{
// When fog is disabled, make sure the fog vector is reset to zero.
if ((dirtyFlags & EffectDirtyFlags.FogEnable) != 0)
{
fogVectorParam.SetValue(Vector4.Zero);
dirtyFlags &= ~EffectDirtyFlags.FogEnable;
}
}
return dirtyFlags;
}
/// <summary>
/// Sets a vector which can be dotted with the object space vertex position to compute fog amount.
/// </summary>
static void SetFogVector(ref Matrix worldView, float fogStart, float fogEnd, EffectParameter fogVectorParam)
{
if (fogStart == fogEnd)
{
// Degenerate case: force everything to 100% fogged if start and end are the same.
fogVectorParam.SetValue(new Vector4(0, 0, 0, 1));
}
else
{
// We want to transform vertex positions into view space, take the resulting
// Z value, then scale and offset according to the fog start/end distances.
// Because we only care about the Z component, the shader can do all this
// with a single dot product, using only the Z row of the world+view matrix.
float scale = 1f / (fogStart - fogEnd);
Vector4 fogVector = new Vector4();
fogVector.X = worldView.M13 * scale;
fogVector.Y = worldView.M23 * scale;
fogVector.Z = worldView.M33 * scale;
fogVector.W = (worldView.M43 + fogStart) * scale;
fogVectorParam.SetValue(fogVector);
}
}
/// <summary>
/// Lazily recomputes the world inverse transpose matrix and
/// eye position based on the current effect parameter settings.
/// </summary>
internal static EffectDirtyFlags SetLightingMatrices(EffectDirtyFlags dirtyFlags, ref Matrix world, ref Matrix view,
EffectParameter worldParam, EffectParameter worldInverseTransposeParam, EffectParameter eyePositionParam)
{
// Set the world and world inverse transpose matrices.
if ((dirtyFlags & EffectDirtyFlags.World) != 0)
{
Matrix worldTranspose;
Matrix worldInverseTranspose;
Matrix.Invert(ref world, out worldTranspose);
Matrix.Transpose(ref worldTranspose, out worldInverseTranspose);
worldParam.SetValue(world);
worldInverseTransposeParam.SetValue(worldInverseTranspose);
dirtyFlags &= ~EffectDirtyFlags.World;
}
// Set the eye position.
if ((dirtyFlags & EffectDirtyFlags.EyePosition) != 0)
{
Matrix viewInverse;
Matrix.Invert(ref view, out viewInverse);
eyePositionParam.SetValue(viewInverse.TranslationVector);
dirtyFlags &= ~EffectDirtyFlags.EyePosition;
}
return dirtyFlags;
}
/// <summary>
/// Sets the diffuse/emissive/alpha material color parameters.
/// </summary>
internal static void SetMaterialColor(bool lightingEnabled, float alpha,
ref Vector4 diffuseColor, ref Vector3 emissiveColor, ref Vector3 ambientLightColor,
EffectParameter diffuseColorParam, EffectParameter emissiveColorParam)
{
// Desired lighting model:
//
// ((AmbientLightColor + sum(diffuse directional light)) * DiffuseColor) + EmissiveColor
//
// When lighting is disabled, ambient and directional lights are ignored, leaving:
//
// DiffuseColor + EmissiveColor
//
// For the lighting disabled case, we can save one shader instruction by precomputing
// diffuse+emissive on the CPU, after which the shader can use DiffuseColor directly,
// ignoring its emissive parameter.
//
// When lighting is enabled, we can merge the ambient and emissive settings. If we
// set our emissive parameter to emissive+(ambient*diffuse), the shader no longer
// needs to bother adding the ambient contribution, simplifying its computation to:
//
// (sum(diffuse directional light) * DiffuseColor) + EmissiveColor
//
// For futher optimization goodness, we merge material alpha with the diffuse
// color parameter, and premultiply all color values by this alpha.
if (lightingEnabled)
{
Vector4 diffuse = new Vector4();
Vector3 emissive = new Vector3();
diffuse.X = diffuseColor.X * alpha;
diffuse.Y = diffuseColor.Y * alpha;
diffuse.Z = diffuseColor.Z * alpha;
diffuse.W = alpha;
emissive.X = (emissiveColor.X + ambientLightColor.X * diffuseColor.X) * alpha;
emissive.Y = (emissiveColor.Y + ambientLightColor.Y * diffuseColor.Y) * alpha;
emissive.Z = (emissiveColor.Z + ambientLightColor.Z * diffuseColor.Z) * alpha;
diffuseColorParam.SetValue(diffuse);
emissiveColorParam.SetValue(emissive);
}
else
{
Vector4 diffuse = new Vector4();
diffuse.X = (diffuseColor.X + emissiveColor.X) * alpha;
diffuse.Y = (diffuseColor.Y + emissiveColor.Y) * alpha;
diffuse.Z = (diffuseColor.Z + emissiveColor.Z) * alpha;
diffuse.W = alpha;
diffuseColorParam.SetValue(diffuse);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting;
using System.Collections.ObjectModel;
namespace System.Management.Automation.Runspaces.Internal
{
/// <summary>
/// PowerShell client side proxy base which handles invocation
/// of powershell on a remote machine.
/// </summary>
internal class ClientRemotePowerShell : IDisposable
{
#region Tracer
[TraceSourceAttribute("CRPS", "ClientRemotePowerShell")]
private static PSTraceSource s_tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase");
#endregion Tracer
#region Constructors
/// <summary>
/// Constructor which creates a client remote powershell.
/// </summary>
/// <param name="shell">Powershell instance.</param>
/// <param name="runspacePool">The runspace pool associated with
/// this shell</param>
internal ClientRemotePowerShell(PowerShell shell, RemoteRunspacePoolInternal runspacePool)
{
this.shell = shell;
clientRunspacePoolId = runspacePool.InstanceId;
this.runspacePool = runspacePool;
// retrieve the computer name from the runspacepool
// information so that it can be used in adding
// warning to host messages
computerName = runspacePool.ConnectionInfo.ComputerName;
}
#endregion Constructors
#region Internal Methods/Properties
/// <summary>
/// Instance Id associated with this
/// client remote powershell.
/// </summary>
internal Guid InstanceId
{
get
{
return PowerShell.InstanceId;
}
}
/// <summary>
/// PowerShell associated with this ClientRemotePowerShell.
/// </summary>
internal PowerShell PowerShell
{
get
{
return shell;
}
}
/// <summary>
/// Set the state information of the client powershell.
/// </summary>
/// <param name="stateInfo">State information to set.</param>
internal void SetStateInfo(PSInvocationStateInfo stateInfo)
{
shell.SetStateChanged(stateInfo);
}
/// <summary>
/// Whether input is available when this object is created.
/// </summary>
internal bool NoInput
{
get
{
return noInput;
}
}
/// <summary>
/// Input stream associated with this object.
/// </summary>
internal ObjectStreamBase InputStream
{
get
{
return inputstream;
}
set
{
inputstream = value;
if (inputstream != null && (inputstream.IsOpen || inputstream.Count > 0))
{
noInput = false;
}
else
{
noInput = true;
}
}
}
/// <summary>
/// Output stream associated with this object.
/// </summary>
internal ObjectStreamBase OutputStream
{
get
{
return outputstream;
}
set
{
outputstream = value;
}
}
/// <summary>
/// Data structure handler object.
/// </summary>
internal ClientPowerShellDataStructureHandler DataStructureHandler
{
get
{
return dataStructureHandler;
}
}
/// <summary>
/// Invocation settings associated with this
/// ClientRemotePowerShell.
/// </summary>
internal PSInvocationSettings Settings
{
get
{
return settings;
}
}
/// <summary>
/// Close the output, error and other collections
/// associated with the shell, so that the
/// enumerator does not block.
/// </summary>
internal void UnblockCollections()
{
shell.ClearRemotePowerShell();
outputstream.Close();
errorstream.Close();
if (inputstream != null)
{
inputstream.Close();
}
}
/// <summary>
/// Stop the remote powershell asynchronously.
/// </summary>
/// <remarks>This method will be called from
/// within the lock on PowerShell. Hence no need
/// to lock</remarks>
internal void StopAsync()
{
// If we are in robust connection retry mode then auto-disconnect this command
// rather than try to stop it.
PSConnectionRetryStatus retryStatus = _connectionRetryStatus;
if ((retryStatus == PSConnectionRetryStatus.NetworkFailureDetected ||
retryStatus == PSConnectionRetryStatus.ConnectionRetryAttempt) &&
this.runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened)
{
// While in robust connection retry mode, this call forces robust connections
// to abort retries and go directly to auto-disconnect.
this.runspacePool.BeginDisconnect(null, null);
return;
}
// powershell CoreStop would have handled cases
// for NotStarted, Stopping and already Stopped
// so at this point, there is no need to make any
// check. The message simply needs to be sent
// across to the server
stopCalled = true;
dataStructureHandler.SendStopPowerShellMessage();
}
/// <summary>
/// </summary>
internal void SendInput()
{
dataStructureHandler.SendInput(this.inputstream);
}
/// <summary>
/// This event is raised, when a host call is for a remote pipeline
/// which this remote powershell wraps.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteHostCall>> HostCallReceived;
/// <summary>
/// Initialize the client remote powershell instance.
/// </summary>
/// <param name="inputstream">Input for execution.</param>
/// <param name="errorstream">error stream to which
/// data needs to be written to</param>
/// <param name="informationalBuffers">informational buffers
/// which will hold debug, verbose and warning messages</param>
/// <param name="settings">settings based on which this powershell
/// needs to be executed</param>
/// <param name="outputstream">output stream to which data
/// needs to be written to</param>
internal void Initialize(
ObjectStreamBase inputstream, ObjectStreamBase outputstream,
ObjectStreamBase errorstream, PSInformationalBuffers informationalBuffers,
PSInvocationSettings settings)
{
initialized = true;
this.informationalBuffers = informationalBuffers;
InputStream = inputstream;
this.errorstream = errorstream;
this.outputstream = outputstream;
this.settings = settings;
if (settings == null || settings.Host == null)
{
hostToUse = runspacePool.Host;
}
else
{
hostToUse = settings.Host;
}
dataStructureHandler = runspacePool.DataStructureHandler.CreatePowerShellDataStructureHandler(this);
// register for events from the data structure handler
dataStructureHandler.InvocationStateInfoReceived +=
new EventHandler<RemoteDataEventArgs<PSInvocationStateInfo>>(HandleInvocationStateInfoReceived);
dataStructureHandler.OutputReceived += new EventHandler<RemoteDataEventArgs<object>>(HandleOutputReceived);
dataStructureHandler.ErrorReceived += new EventHandler<RemoteDataEventArgs<ErrorRecord>>(HandleErrorReceived);
dataStructureHandler.InformationalMessageReceived +=
new EventHandler<RemoteDataEventArgs<InformationalMessage>>(HandleInformationalMessageReceived);
dataStructureHandler.HostCallReceived +=
new EventHandler<RemoteDataEventArgs<RemoteHostCall>>(HandleHostCallReceived);
dataStructureHandler.ClosedNotificationFromRunspacePool +=
new EventHandler<RemoteDataEventArgs<Exception>>(HandleCloseNotificationFromRunspacePool);
dataStructureHandler.BrokenNotificationFromRunspacePool +=
new EventHandler<RemoteDataEventArgs<Exception>>(HandleBrokenNotificationFromRunspacePool);
dataStructureHandler.ConnectCompleted += new EventHandler<RemoteDataEventArgs<Exception>>(HandleConnectCompleted);
dataStructureHandler.ReconnectCompleted += new EventHandler<RemoteDataEventArgs<Exception>>(HandleConnectCompleted);
dataStructureHandler.RobustConnectionNotification +=
new EventHandler<ConnectionStatusEventArgs>(HandleRobustConnectionNotification);
dataStructureHandler.CloseCompleted +=
new EventHandler<EventArgs>(HandleCloseCompleted);
}
/// <summary>
/// Do any clean up operation per initialization here.
/// </summary>
internal void Clear()
{
initialized = false;
}
/// <summary>
/// If this client remote powershell has been initialized.
/// </summary>
internal bool Initialized
{
get
{
return initialized;
}
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
internal static void ExitHandler(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs)
{
RemoteHostCall hostcall = eventArgs.Data;
if (hostcall.IsSetShouldExitOrPopRunspace)
{
return;
}
// use the method from the RemotePowerShell to indeed execute this call
ClientRemotePowerShell remotePowerShell = (ClientRemotePowerShell)sender;
remotePowerShell.ExecuteHostCall(hostcall);
}
/// <summary>
/// Attempts to reconnect or connect to a running command on a remote server,
/// which will resume events and data collection from the server.
/// If connectCmdInfo parameter is null then a reconnection is attempted and
/// it is assumed that the current client state is unchanged since disconnection.
/// If connectCmdInfo parameter is non-null then a connection is attempted to
/// the specified remote running command.
/// This is an asynchronous call and results will be reported in the ReconnectCompleted
/// or the ConnectCompleted call back as appropriate.
/// </summary>
/// <param name="connectCmdInfo">ConnectCommandInfo specifying remote command.</param>
internal void ConnectAsync(ConnectCommandInfo connectCmdInfo)
{
if (connectCmdInfo == null)
{
// Attempt to do a reconnect with the current PSRP client state.
this.dataStructureHandler.ReconnectAsync();
}
else
{
// First add this command DS handler to the remote runspace pool list.
Dbg.Assert(this.shell.RunspacePool != null, "Invalid runspace pool for this powershell object.");
this.shell.RunspacePool.RemoteRunspacePoolInternal.AddRemotePowerShellDSHandler(
this.InstanceId, this.dataStructureHandler);
// Now do the asynchronous connect.
this.dataStructureHandler.ConnectAsync();
}
}
/// <summary>
/// This event is fired when this PowerShell object receives a robust connection
/// notification from the transport.
/// </summary>
internal event EventHandler<PSConnectionRetryStatusEventArgs> RCConnectionNotification;
/// <summary>
/// Current remote connection retry status.
/// </summary>
internal PSConnectionRetryStatus ConnectionRetryStatus
{
get { return _connectionRetryStatus; }
}
#endregion Internal Methods/Properties
#region Private Methods
/// <summary>
/// An error record is received from the powershell at the
/// server side. It is added to the error collection of the
/// client powershell.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleErrorReceived(object sender, RemoteDataEventArgs<ErrorRecord> eventArgs)
{
using (s_tracer.TraceEventHandlers())
{
shell.SetHadErrors(true);
errorstream.Write(eventArgs.Data);
}
}
/// <summary>
/// An output object is received from the powershell at the
/// server side. It is added to the output collection of the
/// client powershell.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleOutputReceived(object sender, RemoteDataEventArgs<object> eventArgs)
{
using (s_tracer.TraceEventHandlers())
{
object data = eventArgs.Data;
try
{
outputstream.Write(data);
}
catch (PSInvalidCastException e)
{
shell.SetStateChanged(new PSInvocationStateInfo(PSInvocationState.Failed, e));
}
}
}
/// <summary>
/// The invocation state of the server powershell has changed.
/// The state of the client powershell is reflected accordingly.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleInvocationStateInfoReceived(object sender,
RemoteDataEventArgs<PSInvocationStateInfo> eventArgs)
{
using (s_tracer.TraceEventHandlers())
{
PSInvocationStateInfo stateInfo = eventArgs.Data;
// we should not receive any transient state from
// the server
Dbg.Assert(!(stateInfo.State == PSInvocationState.Running ||
stateInfo.State == PSInvocationState.Stopping),
"Transient states should not be received from the server");
if (stateInfo.State == PSInvocationState.Disconnected)
{
SetStateInfo(stateInfo);
}
else if (stateInfo.State == PSInvocationState.Stopped ||
stateInfo.State == PSInvocationState.Failed ||
stateInfo.State == PSInvocationState.Completed)
{
// Special case for failure error due to ErrorCode==-2144108453 (no ShellId found).
// In this case terminate session since there is no longer a shell to communicate
// with.
bool terminateSession = false;
if (stateInfo.State == PSInvocationState.Failed)
{
PSRemotingTransportException remotingTransportException = stateInfo.Reason as PSRemotingTransportException;
terminateSession = (remotingTransportException != null) &&
(remotingTransportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST);
}
// if state is completed or failed or stopped,
// then the collections need to be closed as
// well, else the enumerator will block
UnblockCollections();
if (stopCalled || terminateSession)
{
// Reset stop called flag.
stopCalled = false;
// if a Stop method has been called, then powershell
// would have already raised a Stopping event, after
// which only a Stopped should be raised
_stateInfoQueue.Enqueue(new PSInvocationStateInfo(PSInvocationState.Stopped,
stateInfo.Reason));
// If the stop call failed due to network problems then close the runspace
// since it is now unusable.
CheckAndCloseRunspaceAfterStop(stateInfo.Reason);
}
else
{
_stateInfoQueue.Enqueue(stateInfo);
}
// calling close async only after making sure all the internal members are prepared
// to handle close complete.
dataStructureHandler.CloseConnectionAsync(null);
}
}
}
/// <summary>
/// Helper method to check any error condition after a stop call
/// and close the remote runspace/pool if the stop call failed due
/// to network outage problems.
/// </summary>
/// <param name="ex">Exception.</param>
private void CheckAndCloseRunspaceAfterStop(Exception ex)
{
PSRemotingTransportException transportException = ex as PSRemotingTransportException;
if (transportException != null &&
(transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_CONNECT ||
transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_COMPLETE ||
transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST))
{
object rsObject = shell.GetRunspaceConnection();
if (rsObject is Runspace)
{
Runspace runspace = (Runspace)rsObject;
if (runspace.RunspaceStateInfo.State == RunspaceState.Opened)
{
try
{
runspace.Close();
}
catch (PSRemotingTransportException)
{ }
}
}
else if (rsObject is RunspacePool)
{
RunspacePool runspacePool = (RunspacePool)rsObject;
if (runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened)
{
try
{
runspacePool.Close();
}
catch (PSRemotingTransportException)
{ }
}
}
}
}
/// <summary>
/// Handler for handling any informational message received
/// from the server side.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="eventArgs">Arguments describing this event.</param>
private void HandleInformationalMessageReceived(object sender,
RemoteDataEventArgs<InformationalMessage> eventArgs)
{
using (s_tracer.TraceEventHandlers())
{
InformationalMessage infoMessage = eventArgs.Data;
switch (infoMessage.DataType)
{
case RemotingDataType.PowerShellDebug:
{
informationalBuffers.AddDebug((DebugRecord)infoMessage.Message);
}
break;
case RemotingDataType.PowerShellVerbose:
{
informationalBuffers.AddVerbose((VerboseRecord)infoMessage.Message);
}
break;
case RemotingDataType.PowerShellWarning:
{
informationalBuffers.AddWarning((WarningRecord)infoMessage.Message);
}
break;
case RemotingDataType.PowerShellProgress:
{
ProgressRecord progress = (ProgressRecord)LanguagePrimitives.ConvertTo(infoMessage.Message,
typeof(ProgressRecord), System.Globalization.CultureInfo.InvariantCulture);
informationalBuffers.AddProgress(progress);
}
break;
case RemotingDataType.PowerShellInformationStream:
{
informationalBuffers.AddInformation((InformationRecord)infoMessage.Message);
}
break;
}
}
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleHostCallReceived(object sender, RemoteDataEventArgs<RemoteHostCall> eventArgs)
{
using (s_tracer.TraceEventHandlers())
{
Collection<RemoteHostCall> prerequisiteCalls =
eventArgs.Data.PerformSecurityChecksOnHostMessage(computerName);
if (HostCallReceived != null)
{
// raise events for all prerequisite calls
if (prerequisiteCalls.Count > 0)
{
foreach (RemoteHostCall hostcall in prerequisiteCalls)
{
RemoteDataEventArgs<RemoteHostCall> args =
new RemoteDataEventArgs<RemoteHostCall>(hostcall);
HostCallReceived.SafeInvoke(this, args);
}
}
HostCallReceived.SafeInvoke(this, eventArgs);
}
else
{
// execute any prerequisite calls before
// executing this host call
if (prerequisiteCalls.Count > 0)
{
foreach (RemoteHostCall hostcall in prerequisiteCalls)
{
ExecuteHostCall(hostcall);
}
}
ExecuteHostCall(eventArgs.Data);
}
}
}
/// <summary>
/// Handler for ConnectCompleted and ReconnectCompleted events from the
/// PSRP layer.
/// </summary>
/// <param name="sender">Sender of this event, unused.</param>
/// <param name="e">Event arguments.</param>
private void HandleConnectCompleted(object sender, RemoteDataEventArgs<Exception> e)
{
// After initial connect/reconnect set state to "Running". Later events
// will update state to appropriate command execution state.
SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Running, null));
}
/// <summary>
/// This is need for the state change events that resulted in closing the underlying
/// datastructure handler. We cannot send the state back to the upper layers until
/// close is completed from the datastructure/transport layer. We have to send
/// the terminal state only when we know that underlying datastructure/transport
/// is closed.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void HandleCloseCompleted(object sender, EventArgs args)
{
// if state is completed or failed or stopped,
// then the collections need to be closed as
// well, else the enumerator will block
UnblockCollections();
// close the transport manager when CreateCloseAckPacket is received
// otherwise may have race conditions in Server.OutOfProcessMediator
dataStructureHandler.RaiseRemoveAssociationEvent();
if (_stateInfoQueue.Count == 0)
{
// If shell state is not finished on client side and queue is empty
// then set state to stopped unless the current state is Disconnected
// in which case transition state to failed.
if (!IsFinished(shell.InvocationStateInfo.State))
{
// If RemoteSessionStateEventArgs are provided then use them to set the
// session close reason when setting finished state.
RemoteSessionStateEventArgs sessionEventArgs = args as RemoteSessionStateEventArgs;
Exception closeReason = (sessionEventArgs != null) ? sessionEventArgs.SessionStateInfo.Reason : null;
PSInvocationState finishedState = (shell.InvocationStateInfo.State == PSInvocationState.Disconnected) ?
PSInvocationState.Failed : PSInvocationState.Stopped;
SetStateInfo(new PSInvocationStateInfo(finishedState, closeReason));
}
}
else
{
// Apply queued state changes.
while (_stateInfoQueue.Count > 0)
{
PSInvocationStateInfo stateInfo = _stateInfoQueue.Dequeue();
SetStateInfo(stateInfo);
}
}
}
private bool IsFinished(PSInvocationState state)
{
return (state == PSInvocationState.Completed ||
state == PSInvocationState.Failed ||
state == PSInvocationState.Stopped);
}
/// <summary>
/// Execute the specified host call.
/// </summary>
/// <param name="hostcall">Host call to execute.</param>
private void ExecuteHostCall(RemoteHostCall hostcall)
{
if (hostcall.IsVoidMethod)
{
if (hostcall.IsSetShouldExitOrPopRunspace)
{
this.shell.ClearRemotePowerShell();
}
hostcall.ExecuteVoidMethod(hostToUse);
}
else
{
RemoteHostResponse remoteHostResponse = hostcall.ExecuteNonVoidMethod(hostToUse);
dataStructureHandler.SendHostResponseToServer(remoteHostResponse);
}
}
/// <summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
private void HandleCloseNotificationFromRunspacePool(object sender,
RemoteDataEventArgs<Exception> eventArgs)
{
// RunspacePool is closed...so going to set the state of PowerShell
// to stopped here.
// if state is completed or failed or stopped,
// then the collections need to be closed as
// well, else the enumerator will block
UnblockCollections();
// Since this is a terminal state..close the transport manager.
dataStructureHandler.RaiseRemoveAssociationEvent();
// RunspacePool is closed...so going to set the state of PowerShell
// to stopped here.
SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Stopped,
eventArgs.Data));
// Not calling dataStructureHandler.CloseConnection() as this must
// have already been called by RunspacePool.Close()
}
/// <summary>
/// Handles notification from RunspacePool indicating
/// that the pool is broken. This sets the state of
/// all the powershell objects associated with the
/// runspace pool to Failed.
/// </summary>
/// <param name="sender">Sender of this information, unused.</param>
/// <param name="eventArgs">arguments describing this event
/// contains information on the reason associated with the
/// runspace pool entering a Broken state</param>
private void HandleBrokenNotificationFromRunspacePool(object sender,
RemoteDataEventArgs<Exception> eventArgs)
{
// RunspacePool is closed...so going to set the state of PowerShell
// to stopped here.
// if state is completed or failed or stopped,
// then the collections need to be closed as
// well, else the enumerator will block
UnblockCollections();
// Since this is a terminal state..close the transport manager.
dataStructureHandler.RaiseRemoveAssociationEvent();
if (stopCalled)
{
// Reset stop called flag.
stopCalled = false;
// if a Stop method has been called, then powershell
// would have already raised a Stopping event, after
// which only a Stopped should be raised
SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Stopped,
eventArgs.Data));
}
else
{
SetStateInfo(new PSInvocationStateInfo(PSInvocationState.Failed,
eventArgs.Data));
}
// Not calling dataStructureHandler.CloseConnection() as this must
// have already been called by RunspacePool.Close()
}
/// <summary>
/// Handles a robust connection layer notification from the transport
/// manager.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void HandleRobustConnectionNotification(
object sender,
ConnectionStatusEventArgs e)
{
// Create event arguments and warnings/errors for this robust connection notification.
PSConnectionRetryStatusEventArgs connectionRetryStatusArgs = null;
WarningRecord warningRecord = null;
ErrorRecord errorRecord = null;
int maxRetryConnectionTimeMSecs = this.runspacePool.MaxRetryConnectionTime;
int maxRetryConnectionTimeMinutes = maxRetryConnectionTimeMSecs / 60000;
switch (e.Notification)
{
case ConnectionStatus.NetworkFailureDetected:
warningRecord = new WarningRecord(
PSConnectionRetryStatusEventArgs.FQIDNetworkFailureDetected,
StringUtil.Format(RemotingErrorIdStrings.RCNetworkFailureDetected,
this.computerName, maxRetryConnectionTimeMinutes));
connectionRetryStatusArgs =
new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.NetworkFailureDetected,
this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
break;
case ConnectionStatus.ConnectionRetryAttempt:
warningRecord = new WarningRecord(
PSConnectionRetryStatusEventArgs.FQIDConnectionRetryAttempt,
StringUtil.Format(RemotingErrorIdStrings.RCConnectionRetryAttempt, this.computerName));
connectionRetryStatusArgs =
new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetryAttempt,
this.computerName, maxRetryConnectionTimeMSecs, warningRecord);
break;
case ConnectionStatus.ConnectionRetrySucceeded:
warningRecord = new WarningRecord(
PSConnectionRetryStatusEventArgs.FQIDConnectionRetrySucceeded,
StringUtil.Format(RemotingErrorIdStrings.RCReconnectSucceeded, this.computerName));
connectionRetryStatusArgs =
new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.ConnectionRetrySucceeded,
this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
break;
case ConnectionStatus.AutoDisconnectStarting:
{
warningRecord = new WarningRecord(
PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectStarting,
StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingWarning, this.computerName));
connectionRetryStatusArgs =
new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectStarting,
this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
}
break;
case ConnectionStatus.AutoDisconnectSucceeded:
warningRecord = new WarningRecord(
PSConnectionRetryStatusEventArgs.FQIDAutoDisconnectSucceeded,
StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnected, this.computerName));
connectionRetryStatusArgs =
new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.AutoDisconnectSucceeded,
this.computerName, maxRetryConnectionTimeMinutes, warningRecord);
break;
case ConnectionStatus.InternalErrorAbort:
{
string msg = StringUtil.Format(RemotingErrorIdStrings.RCInternalError, this.computerName);
RuntimeException reason = new RuntimeException(msg);
errorRecord = new ErrorRecord(reason,
PSConnectionRetryStatusEventArgs.FQIDNetworkOrDisconnectFailed,
ErrorCategory.InvalidOperation, this);
connectionRetryStatusArgs =
new PSConnectionRetryStatusEventArgs(PSConnectionRetryStatus.InternalErrorAbort,
this.computerName, maxRetryConnectionTimeMinutes, errorRecord);
}
break;
}
if (connectionRetryStatusArgs == null)
{
return;
}
// Update connection status.
_connectionRetryStatus = connectionRetryStatusArgs.Notification;
if (warningRecord != null)
{
RemotingWarningRecord remotingWarningRecord = new RemotingWarningRecord(
warningRecord,
new OriginInfo(this.computerName, this.InstanceId));
// Add warning record to information channel.
HandleInformationalMessageReceived(this,
new RemoteDataEventArgs<InformationalMessage>(
new InformationalMessage(remotingWarningRecord, RemotingDataType.PowerShellWarning)));
// Write warning to host.
RemoteHostCall writeWarning = new RemoteHostCall(
-100,
RemoteHostMethodId.WriteWarningLine,
new object[] { warningRecord.Message });
try
{
HandleHostCallReceived(this,
new RemoteDataEventArgs<RemoteHostCall>(writeWarning));
}
catch (PSNotImplementedException)
{ }
}
if (errorRecord != null)
{
RemotingErrorRecord remotingErrorRecord = new RemotingErrorRecord(
errorRecord,
new OriginInfo(this.computerName, this.InstanceId));
// Add error record to error channel, will also be written to host.
HandleErrorReceived(this,
new RemoteDataEventArgs<ErrorRecord>(remotingErrorRecord));
}
// Raise event.
RCConnectionNotification.SafeInvoke(this, connectionRetryStatusArgs);
}
#endregion Private Methods
#region Protected Members
protected ObjectStreamBase inputstream;
protected ObjectStreamBase errorstream;
protected PSInformationalBuffers informationalBuffers;
protected PowerShell shell;
protected Guid clientRunspacePoolId;
protected bool noInput;
protected PSInvocationSettings settings;
protected ObjectStreamBase outputstream;
protected string computerName;
protected ClientPowerShellDataStructureHandler dataStructureHandler;
protected bool stopCalled = false;
protected PSHost hostToUse;
protected RemoteRunspacePoolInternal runspacePool;
protected const string WRITE_DEBUG_LINE = "WriteDebugLine";
protected const string WRITE_VERBOSE_LINE = "WriteVerboseLine";
protected const string WRITE_WARNING_LINE = "WriteWarningLine";
protected const string WRITE_PROGRESS = "WriteProgress";
protected bool initialized = false;
/// <summary>
/// This queue is for the state change events that resulted in closing the underlying
/// datastructure handler. We cannot send the state back to the upper layers until
/// close is completed from the datastructure/transport layer.
/// </summary>
private Queue<PSInvocationStateInfo> _stateInfoQueue = new Queue<PSInvocationStateInfo>();
private PSConnectionRetryStatus _connectionRetryStatus = PSConnectionRetryStatus.None;
#endregion Protected Members
#region IDisposable
/// <summary>
/// Public interface for dispose.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Release all resources.
/// </summary>
/// <param name="disposing">If true, release all managed resources.</param>
protected void Dispose(bool disposing)
{
if (disposing)
{
// inputstream.Dispose();
// outputstream.Dispose();
// errorstream.Dispose();
}
}
#endregion IDisposable
}
#region PSConnectionRetryStatusEventArgs
/// <summary>
/// Robust Connection notifications.
/// </summary>
internal enum PSConnectionRetryStatus
{
None = 0,
NetworkFailureDetected = 1,
ConnectionRetryAttempt = 2,
ConnectionRetrySucceeded = 3,
AutoDisconnectStarting = 4,
AutoDisconnectSucceeded = 5,
InternalErrorAbort = 6
};
/// <summary>
/// PSConnectionRetryStatusEventArgs.
/// </summary>
internal sealed class PSConnectionRetryStatusEventArgs : EventArgs
{
internal const string FQIDNetworkFailureDetected = "PowerShellNetworkFailureDetected";
internal const string FQIDConnectionRetryAttempt = "PowerShellConnectionRetryAttempt";
internal const string FQIDConnectionRetrySucceeded = "PowerShellConnectionRetrySucceeded";
internal const string FQIDAutoDisconnectStarting = "PowerShellNetworkFailedStartDisconnect";
internal const string FQIDAutoDisconnectSucceeded = "PowerShellAutoDisconnectSucceeded";
internal const string FQIDNetworkOrDisconnectFailed = "PowerShellNetworkOrDisconnectFailed";
internal PSConnectionRetryStatusEventArgs(
PSConnectionRetryStatus notification,
string computerName,
int maxRetryConnectionTime,
object infoRecord)
{
Notification = notification;
ComputerName = computerName;
MaxRetryConnectionTime = maxRetryConnectionTime;
InformationRecord = infoRecord;
}
internal PSConnectionRetryStatus Notification { get; }
internal string ComputerName { get; }
internal int MaxRetryConnectionTime { get; }
internal object InformationRecord { get; }
}
#endregion
}
| |
/*******************************************************************************
* Copyright 2008-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.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
* API Version: 2006-03-01
*
*/
using System;
using System.Xml.Serialization;
using Amazon.Runtime;
using Amazon.S3.Util;
namespace Amazon.S3.Model
{
/// <summary>
/// The parameters to create a pre-signed URL to a bucket or object.
/// </summary>
/// <remarks>
/// For more information, refer to: <see href="http://docs.amazonwebservices.com/AmazonS3/latest/dev/S3_QSAuth.html"/>.
/// <br />Required Parameters: BucketName, Expires
/// <br />Optional Parameters: Key, VersionId, Verb: default is GET
/// </remarks>
public class GetPreSignedUrlRequest : AmazonWebServiceRequest
{
#region Private Members
ResponseHeaderOverrides _responseHeaders;
string bucketName;
string key;
DateTime? expires;
Protocol protocol;
HttpVerb verb;
string versionId;
ServerSideEncryptionMethod encryption;
private string serverSideEncryptionKeyManagementServiceKeyId;
private HeadersCollection headersCollection = new HeadersCollection();
private MetadataCollection metadataCollection = new MetadataCollection();
private ServerSideEncryptionCustomerMethod serverSideCustomerEncryption;
#endregion
#region BucketName
/// <summary>
/// The name of the bucket to create a pre-signed url to, or containing the object.
/// </summary>
public string BucketName
{
get { return this.bucketName; }
set { this.bucketName = value; }
}
/// <summary>
/// Checks if BucketName property is set.
/// </summary>
/// <returns>true if BucketName property is set.</returns>
internal bool IsSetBucketName()
{
return !System.String.IsNullOrEmpty(this.bucketName);
}
#endregion
#region Key
/// <summary>
/// The key to the object for which a pre-signed url should be created.
/// </summary>
public string Key
{
get { return this.key; }
set { this.key = value; }
}
/// <summary>
/// Checks if Key property is set.
/// </summary>
/// <returns>true if Key property is set.</returns>
internal bool IsSetKey()
{
return !System.String.IsNullOrEmpty(this.key);
}
#endregion
#region ContentType
/// <summary>
/// A standard MIME type describing the format of the object data.
/// </summary>
/// <remarks>
/// <para>
/// The content type for the content being uploaded. This property defaults to "binary/octet-stream".
/// For more information, refer to: <see href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17"/>.
/// </para>
/// <para>
/// Note that if content type is specified, it should also be included in the HttpRequest headers
/// of the eventual upload request, otherwise a signature error may result.
/// </para>
/// </remarks>
public string ContentType
{
get { return this.headersCollection.ContentType; }
set { this.headersCollection.ContentType = value; }
}
#endregion
#region Expires
/// <summary>
/// The expiry date and time for the pre-signed url.
/// </summary>
public DateTime Expires
{
get { return this.expires.GetValueOrDefault(); }
set { this.expires = value; }
}
/// <summary>
/// Checks if Expires property is set.
/// </summary>
/// <returns>true if Expires property is set.</returns>
public bool IsSetExpires()
{
return this.expires.HasValue;
}
#endregion
#region Protocol
/// <summary>
/// The requested protocol (http/https) for the pre-signed url.
/// </summary>
/// <remarks>
/// Defaults to https.
/// </remarks>
public Protocol Protocol
{
get { return this.protocol; }
set { this.protocol = value; }
}
#endregion
#region Verb
/// <summary>
/// The verb for the pre-signed url.
/// </summary>
/// <remarks>
/// Accepted verbs are GET, PUT, DELETE and HEAD.
/// Default is GET.
/// </remarks>
public HttpVerb Verb
{
get { return this.verb; }
set { this.verb = value; }
}
#endregion
#region VersionId
/// <summary>
/// Version id for the object that the pre-signed url will reference. If not set,
/// the url will reference the latest version of the object.
/// </summary>
/// <remarks>
/// This is the VersionId for the S3 Object you want to get
/// a PreSigned URL for. The VersionId property will be ignored
/// for PreSigned "PUT" requests and for requests that don't specify
/// the Key property.
/// </remarks>
public string VersionId
{
get { return this.versionId; }
set { this.versionId = value; }
}
/// <summary>
/// Checks if VersionId property is set.
/// </summary>
/// <returns>true if VersionId property is set.</returns>
internal bool IsSetVersionId()
{
return !System.String.IsNullOrEmpty(this.versionId);
}
#endregion
#region ServerSideEncryption
/// <summary>
/// Specifies the encryption used on the server to store the content.
/// </summary>
/// <remarks>
/// <para>
/// Default is None.
/// </para>
/// <para>
/// If specifying encryption (not None), the corresponding request must include header
/// "x-amz-server-side-encryption" with the value of the encryption.
/// </para>
/// </remarks>
public ServerSideEncryptionMethod ServerSideEncryptionMethod
{
get { return this.encryption; }
set { this.encryption = value; }
}
/// <summary>
/// The id of the AWS Key Management Service key that Amazon S3 should use to encrypt and decrypt the object.
/// If a key id is not specified, the default key will be used for encryption and decryption.
/// </summary>
public string ServerSideEncryptionKeyManagementServiceKeyId
{
get { return this.serverSideEncryptionKeyManagementServiceKeyId; }
set { this.serverSideEncryptionKeyManagementServiceKeyId = value; }
}
/// <summary>
/// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set.
/// </summary>
/// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns>
internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId()
{
return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId);
}
#endregion
#region ServerSideEncryption Customer Key
/// <summary>
/// The Server-side encryption algorithm to be used with the customer provided key.
///
/// </summary>
public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod
{
get { return this.serverSideCustomerEncryption; }
set { this.serverSideCustomerEncryption = value; }
}
// Check to see if ServerSideEncryptionCustomerMethod property is set
internal bool IsSetServerSideEncryptionCustomerMethod()
{
return this.serverSideCustomerEncryption != null && this.serverSideCustomerEncryption != ServerSideEncryptionCustomerMethod.None;
}
#endregion
#region Response Headers
/// <summary>
/// A set of response headers that should be returned with the pre-signed url creation response.
/// </summary>
public ResponseHeaderOverrides ResponseHeaderOverrides
{
get
{
if (this._responseHeaders == null)
{
this._responseHeaders = new ResponseHeaderOverrides();
}
return this._responseHeaders;
}
set
{
this._responseHeaders = value;
}
}
#endregion
#region Headers
/// <summary>
/// The collection of headers for the request.
/// </summary>
public HeadersCollection Headers
{
get
{
if (this.headersCollection == null)
this.headersCollection = new HeadersCollection();
return this.headersCollection;
}
internal set
{
this.headersCollection = value;
}
}
#endregion
#region Metadata
/// <summary>
/// The collection of meta data for the request.
/// </summary>
public MetadataCollection Metadata
{
get
{
if (this.metadataCollection == null)
this.metadataCollection = new MetadataCollection();
return this.metadataCollection;
}
internal set
{
this.metadataCollection = value;
}
}
#endregion
}
}
| |
/*
Copyright (c) 2014, Lars Brubaker
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 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
#define ON_IMAGE_CHANGED_ALWAYS_CREATE_IMAGE
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using MatterHackers.Agg.Image;
using MatterHackers.RenderOpenGl.OpenGl;
using MatterHackers.VectorMath;
namespace MatterHackers.RenderOpenGl
{
public class RemoveGlDataCallBackHolder
{
public event EventHandler releaseAllGlData;
public void Release()
{
releaseAllGlData?.Invoke(this, null);
}
}
public class ImageGlPlugin
{
private static ConditionalWeakTable<byte[], ImageGlPlugin> imagesWithCacheData = new ConditionalWeakTable<byte[], ImageGlPlugin>();
internal class glAllocatedData
{
internal int glTextureHandle;
internal int refreshCountCreatedOn;
internal int glContextId;
public float[] textureUVs;
public float[] positions;
internal void DeleteTextureData(object sender, EventArgs e)
{
GL.DeleteTexture(glTextureHandle);
glTextureHandle = -1;
}
}
private static List<glAllocatedData> glDataNeedingToBeDeleted = new List<glAllocatedData>();
private glAllocatedData glData = new glAllocatedData();
private int imageUpdateCount;
private bool createdWithMipMaps;
private bool clamp;
private static int currentGlobalRefreshCount = 0;
public static void MarkAllImagesNeedRefresh()
{
currentGlobalRefreshCount++;
}
private static int contextId;
private static RemoveGlDataCallBackHolder removeGlDataCallBackHolder;
public static void SetCurrentContextData(int inContextId, RemoveGlDataCallBackHolder inCallBackHolder)
{
contextId = inContextId;
removeGlDataCallBackHolder = inCallBackHolder;
}
public static ImageGlPlugin GetImageGlPlugin(ImageBuffer imageToGetDisplayListFor, bool createAndUseMipMaps, bool textureMagFilterLinear = true, bool clamp = true)
{
imagesWithCacheData.TryGetValue(imageToGetDisplayListFor.GetBuffer(), out ImageGlPlugin plugin);
lock (glDataNeedingToBeDeleted)
{
// We run this in here to ensure that we are on the correct thread and have the correct
// glcontext realized.
for (int i = glDataNeedingToBeDeleted.Count - 1; i >= 0; i--)
{
int textureToDelete = glDataNeedingToBeDeleted[i].glTextureHandle;
if (textureToDelete != -1
&& glDataNeedingToBeDeleted[i].glContextId == contextId
&& glDataNeedingToBeDeleted[i].refreshCountCreatedOn == currentGlobalRefreshCount) // this is to leak on purpose on android for some gl that kills textures
{
GL.DeleteTexture(textureToDelete);
if (removeGlDataCallBackHolder != null)
{
removeGlDataCallBackHolder.releaseAllGlData -= glDataNeedingToBeDeleted[i].DeleteTextureData;
}
}
glDataNeedingToBeDeleted.RemoveAt(i);
}
}
if (plugin != null
&& (imageToGetDisplayListFor.ChangedCount != plugin.imageUpdateCount
|| plugin.glData.refreshCountCreatedOn != currentGlobalRefreshCount
|| plugin.glData.glTextureHandle == -1))
{
int textureToDelete = plugin.GLTextureHandle;
if (plugin.glData.refreshCountCreatedOn == currentGlobalRefreshCount)
{
GL.DeleteTexture(textureToDelete);
}
plugin.glData.glTextureHandle = -1;
imagesWithCacheData.Remove(imageToGetDisplayListFor.GetBuffer());
// use the original settings
createAndUseMipMaps = plugin.createdWithMipMaps;
clamp = plugin.clamp;
plugin = null;
}
if (plugin == null)
{
var newPlugin = new ImageGlPlugin();
imagesWithCacheData.Add(imageToGetDisplayListFor.GetBuffer(), newPlugin);
newPlugin.createdWithMipMaps = createAndUseMipMaps;
newPlugin.clamp = clamp;
newPlugin.glData.glContextId = contextId;
newPlugin.CreateGlDataForImage(imageToGetDisplayListFor, textureMagFilterLinear);
newPlugin.imageUpdateCount = imageToGetDisplayListFor.ChangedCount;
newPlugin.glData.refreshCountCreatedOn = currentGlobalRefreshCount;
if (removeGlDataCallBackHolder != null)
{
removeGlDataCallBackHolder.releaseAllGlData += newPlugin.glData.DeleteTextureData;
}
return newPlugin;
}
return plugin;
}
public int GLTextureHandle => glData.glTextureHandle;
private ImageGlPlugin()
{
// This is private as you can't build one of these. You have to call GetImageGlPlugin.
}
~ImageGlPlugin()
{
lock (glDataNeedingToBeDeleted)
{
glDataNeedingToBeDeleted.Add(glData);
}
}
private bool hwSupportsOnlyPowerOfTwoTextures = true;
private bool checkedForHwSupportsOnlyPowerOfTwoTextures = false;
private int SmallestHardwareCompatibleTextureSize(int size)
{
if (!checkedForHwSupportsOnlyPowerOfTwoTextures)
{
{
// Compatible context (GL 1.0-2.1)
string extensions = GL.GetString(StringName.Extensions);
if (extensions.Contains("ARB_texture_non_power_of_two"))
{
hwSupportsOnlyPowerOfTwoTextures = false;
}
}
checkedForHwSupportsOnlyPowerOfTwoTextures = true;
}
if (hwSupportsOnlyPowerOfTwoTextures)
{
return MathHelper.FirstPowerTowGreaterThanOrEqualTo(size);
}
else
{
return size;
}
}
private void CreateGlDataForImage(ImageBuffer bufferedImage, bool textureMagFilterLinear)
{
int imageWidth = bufferedImage.Width;
int imageHeight = bufferedImage.Height;
int hardwareWidth = SmallestHardwareCompatibleTextureSize(imageWidth);
int hardwareHeight = SmallestHardwareCompatibleTextureSize(imageHeight);
bufferedImage = FixImageSizePower2IfRequired(bufferedImage);
FixImageColors(bufferedImage);
GL.Enable(EnableCap.Texture2D);
// Create the texture handle
glData.glTextureHandle = GL.GenTexture();
// Set up some texture parameters for openGL
GL.BindTexture(TextureTarget.Texture2D, glData.glTextureHandle);
if (textureMagFilterLinear)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
}
else
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
}
if (createdWithMipMaps)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
}
else
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
}
if (clamp)
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
}
else
{
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
}
// Create the texture
switch (bufferedImage.BitDepth)
{
case 32:
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, hardwareWidth, hardwareHeight,
0, PixelFormat.Rgba, PixelType.UnsignedByte, bufferedImage.GetBuffer());
break;
default:
throw new NotImplementedException();
}
if (createdWithMipMaps)
{
switch (bufferedImage.BitDepth)
{
case 32:
{
var sourceImage = new ImageBuffer(bufferedImage);
var tempImage = new ImageBuffer(sourceImage.Width / 2, sourceImage.Height / 2);
tempImage.NewGraphics2D().Render(sourceImage, 0, 0, 0, .5, .5);
int mipLevel = 1;
while (sourceImage.Width > 1 || sourceImage.Height > 1)
{
GL.TexImage2D(TextureTarget.Texture2D, mipLevel++, PixelInternalFormat.Rgba, tempImage.Width, tempImage.Height,
0, PixelFormat.Rgba, PixelType.UnsignedByte, tempImage.GetBuffer());
sourceImage = new ImageBuffer(tempImage);
tempImage = new ImageBuffer(Math.Max(1, sourceImage.Width / 2), Math.Max(1, sourceImage.Height / 2));
tempImage.NewGraphics2D().Render(sourceImage, 0, 0,
0,
(double)tempImage.Width / (double)sourceImage.Width,
(double)tempImage.Height / (double)sourceImage.Height);
}
}
break;
default:
throw new NotImplementedException();
}
}
float texCoordX = imageWidth / (float)hardwareWidth;
float texCoordY = imageHeight / (float)hardwareHeight;
float offsetX = (float)bufferedImage.OriginOffset.X;
float offsetY = (float)bufferedImage.OriginOffset.Y;
glData.textureUVs = new float[8];
glData.positions = new float[8];
glData.textureUVs[0] = 0; glData.textureUVs[1] = 0; glData.positions[0] = 0 - offsetX; glData.positions[1] = 0 - offsetY;
glData.textureUVs[2] = 0; glData.textureUVs[3] = texCoordY; glData.positions[2] = 0 - offsetX; glData.positions[3] = imageHeight - offsetY;
glData.textureUVs[4] = texCoordX; glData.textureUVs[5] = texCoordY; glData.positions[4] = imageWidth - offsetX; glData.positions[5] = imageHeight - offsetY;
glData.textureUVs[6] = texCoordX; glData.textureUVs[7] = 0; glData.positions[6] = imageWidth - offsetX; glData.positions[7] = 0 - offsetY;
}
private void FixImageColors(ImageBuffer bufferedImage)
{
// Next we expand the image into an openGL texture
int imageWidth = bufferedImage.Width;
int imageHeight = bufferedImage.Height;
byte[] imageBuffer = bufferedImage.GetBuffer(out _);
switch (bufferedImage.BitDepth)
{
case 32:
for (int y = 0; y < imageHeight; y++)
{
for (int x = 0; x < imageWidth; x++)
{
int pixelIndex = 4 * (x + y * imageWidth);
byte r = imageBuffer[pixelIndex + 2];
byte g = imageBuffer[pixelIndex + 1];
byte b = imageBuffer[pixelIndex + 0];
byte a = imageBuffer[pixelIndex + 3];
imageBuffer[pixelIndex + 0] = r;
imageBuffer[pixelIndex + 1] = g;
imageBuffer[pixelIndex + 2] = b;
imageBuffer[pixelIndex + 3] = a;
}
}
break;
default:
throw new NotImplementedException();
}
}
private ImageBuffer FixImageSizePower2IfRequired(ImageBuffer bufferedImage)
{
// Next we expand the image into an openGL texture
int imageWidth = bufferedImage.Width;
int imageHeight = bufferedImage.Height;
byte[] imageBuffer = bufferedImage.GetBuffer(out _);
int hardwareWidth = SmallestHardwareCompatibleTextureSize(imageWidth);
int hardwareHeight = SmallestHardwareCompatibleTextureSize(imageHeight);
var pow2BufferedImage = new ImageBuffer(hardwareWidth, hardwareHeight, 32, bufferedImage.GetRecieveBlender());
pow2BufferedImage.NewGraphics2D().Render(bufferedImage, 0, 0);
// always return a new image because we are going to modify its colors and don't want to change the original image
return pow2BufferedImage;
}
public void DrawToGL()
{
GL.BindTexture(TextureTarget.Texture2D, GLTextureHandle);
GL.Begin(BeginMode.TriangleFan);
GL.TexCoord2(glData.textureUVs[0], glData.textureUVs[1]);
GL.Vertex2(glData.positions[0], glData.positions[1]);
GL.TexCoord2(glData.textureUVs[2], glData.textureUVs[3]);
GL.Vertex2(glData.positions[2], glData.positions[3]);
GL.TexCoord2(glData.textureUVs[4], glData.textureUVs[5]);
GL.Vertex2(glData.positions[4], glData.positions[5]);
GL.TexCoord2(glData.textureUVs[6], glData.textureUVs[7]);
GL.Vertex2(glData.positions[6], glData.positions[7]);
GL.End();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="DataPortal.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>This is the client-side DataPortal.</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using Csla.Reflection;
using Csla.Properties;
using Csla.Server;
using Csla.Serialization.Mobile;
using System.Threading.Tasks;
namespace Csla
{
/// <summary>
/// This is the client-side DataPortal.
/// </summary>
public static class DataPortal
{
private static readonly EmptyCriteria EmptyCriteria = new EmptyCriteria();
#region DataPortal events
/// <summary>
/// Raised by DataPortal before it starts
/// setting up to call a server-side
/// DataPortal method.
/// </summary>
public static event Action<System.Object> DataPortalInitInvoke;
/// <summary>
/// Raised by DataPortal prior to calling the
/// requested server-side DataPortal method.
/// </summary>
public static event Action<DataPortalEventArgs> DataPortalInvoke;
/// <summary>
/// Raised by DataPortal after the requested
/// server-side DataPortal method call is complete.
/// </summary>
public static event Action<DataPortalEventArgs> DataPortalInvokeComplete;
internal static void OnDataPortalInitInvoke(object e)
{
Action<System.Object> action = DataPortalInitInvoke;
if (action != null)
action(e);
}
internal static void OnDataPortalInvoke(DataPortalEventArgs e)
{
Action<DataPortalEventArgs> action = DataPortalInvoke;
if (action != null)
action(e);
}
internal static void OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
Action<DataPortalEventArgs> action = DataPortalInvokeComplete;
if (action != null)
action(e);
}
#endregion
#region Create
/// <summary>
/// Called by a factory method in a business class to create
/// a new object, which is loaded with default
/// values from the database.
/// </summary>
/// <typeparam name="T">Specific type of the business object.</typeparam>
/// <param name="criteria">Object-specific criteria.</param>
/// <returns>A new object, populated with default values.</returns>
public static T Create<T>(object criteria)
{
var dp = new DataPortal<T>();
return dp.Create(criteria);
}
/// <summary>
/// Called by a factory method in a business class to create
/// a new object, which is loaded with default
/// values from the database.
/// </summary>
/// <typeparam name="T">Specific type of the business object.</typeparam>
/// <returns>A new object, populated with default values.</returns>
public static T Create<T>()
{
return Create<T>(EmptyCriteria);
}
/// <summary>
/// Called by a factory method in a business class to create
/// a new object, which is loaded with default
/// values from the database.
/// </summary>
/// <param name="objectType">Type of business object to create.</param>
/// <param name="criteria">Object-specific criteria.</param>
/// <returns>A new object, populated with default values.</returns>
public static object Create(Type objectType, object criteria)
{
return DataPortal<object>.Create(objectType, criteria);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// create a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginCreate<T>(EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginCreate<T>(DataPortal<T>.EmptyCriteria, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// create a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginCreate<T>(EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
BeginCreate<T>(DataPortal<T>.EmptyCriteria, callback, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// create a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to create.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginCreate<T>(object criteria, EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginCreate<T>(criteria, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// create a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to create.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginCreate<T>(object criteria, EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
DataPortal<T> dp = new DataPortal<T>();
dp.CreateCompleted += callback;
dp.BeginCreate(criteria, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// create a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
public static async Task<T> CreateAsync<T>()
{
DataPortal<T> dp = new DataPortal<T>();
return await dp.CreateAsync();
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// create a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to create.
/// </param>
public static async Task<T> CreateAsync<T>(object criteria)
{
DataPortal<T> dp = new DataPortal<T>();
return await dp.CreateAsync(criteria);
}
#endregion
#region Fetch
/// <summary>
/// Called by a factory method in a business class to retrieve
/// an object, which is loaded with values from the database.
/// </summary>
/// <typeparam name="T">Specific type of the business object.</typeparam>
/// <param name="criteria">Object-specific criteria.</param>
/// <returns>An object populated with values from the database.</returns>
public static T Fetch<T>(object criteria)
{
var dp = new DataPortal<T>();
return dp.Fetch(criteria);
}
/// <summary>
/// Called by a factory method in a business class to retrieve
/// an object, which is loaded with values from the database.
/// </summary>
/// <typeparam name="T">Specific type of the business object.</typeparam>
/// <returns>An object populated with values from the database.</returns>
public static T Fetch<T>()
{
return Fetch<T>(EmptyCriteria);
}
internal static object Fetch(Type objectType, object criteria)
{
return DataPortal<object>.Fetch(objectType, criteria);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// fetch a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to fetch.
/// </typeparam>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginFetch<T>(EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginFetch<T>(DataPortal<T>.EmptyCriteria, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// fetch a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to fetch.
/// </typeparam>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginFetch<T>(EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
BeginFetch<T>(DataPortal<T>.EmptyCriteria, callback, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// fetch a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to fetch.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to fetch.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginFetch<T>(object criteria, EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginFetch<T>(criteria, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// fetch a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to fetch.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to fetch.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginFetch<T>(object criteria, EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
var dp = new DataPortal<T>();
dp.FetchCompleted += callback;
dp.BeginFetch(criteria, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// fetch a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to fetch.
/// </typeparam>
public static async Task<T> FetchAsync<T>()
where T : IMobileObject
{
var dp = new DataPortal<T>();
return await dp.FetchAsync();
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// fetch a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to fetch.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to fetch.
/// </param>
public static async Task<T> FetchAsync<T>(object criteria)
where T : IMobileObject
{
var dp = new DataPortal<T>();
return await dp.FetchAsync(criteria);
}
#endregion
#region Update
/// <summary>
/// Called by the business object's Save() method to
/// insert, update or delete an object in the database.
/// </summary>
/// <remarks>
/// Note that this method returns a reference to the updated business object.
/// If the server-side DataPortal is running remotely, this will be a new and
/// different object from the original, and all object references MUST be updated
/// to use this new object.
/// </remarks>
/// <typeparam name="T">Specific type of the business object.</typeparam>
/// <param name="obj">A reference to the business object to be updated.</param>
/// <returns>A reference to the updated business object.</returns>
public static T Update<T>(T obj)
{
var dp = new DataPortal<T>();
return dp.Update(obj);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// update a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to update.
/// </typeparam>
/// <param name="obj">
/// Business object to update.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginUpdate<T>(T obj, EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginUpdate<T>(obj, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// update a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to update.
/// </typeparam>
/// <param name="obj">
/// Business object to update.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginUpdate<T>(T obj, EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
DataPortal<T> dp = new DataPortal<T>();
dp.UpdateCompleted += callback;
dp.BeginUpdate(obj, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// update a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to update.
/// </typeparam>
/// <param name="obj">
/// Business object to update.
/// </param>
public static async Task<T> UpdateAsync<T>(T obj)
where T : IMobileObject
{
DataPortal<T> dp = new DataPortal<T>();
return await dp.UpdateAsync(obj);
}
#endregion
#region Delete
/// <summary>
/// Called by a Shared (static in C#) method in the business class to cause
/// immediate deletion of a specific object from the database.
/// </summary>
/// <param name="criteria">Object-specific criteria.</param>
public static void Delete<T>(object criteria)
{
var dp = new DataPortal<T>();
dp.Delete(criteria);
}
internal static void Delete(Type objectType, object criteria)
{
DataPortal<object>.Delete(objectType, criteria);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// delete a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to delete.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to delete.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginDelete<T>(object criteria, EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginDelete<T>(criteria, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// delete a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to delete.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to delete.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginDelete<T>(object criteria, EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
var dp = new DataPortal<T>();
dp.DeleteCompleted += callback;
dp.BeginDelete(criteria, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// delete a business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to delete.
/// </typeparam>
/// <param name="criteria">
/// Criteria describing the object to delete.
/// </param>
public static async Task DeleteAsync<T>(object criteria)
where T : IMobileObject
{
var dp = new DataPortal<T>();
await dp.DeleteAsync(criteria);
}
#endregion
#region Execute
/// <summary>
/// Called to execute a Command object on the server.
/// </summary>
/// <remarks>
/// <para>
/// To be a Command object, the object must inherit from
/// CommandBase.
/// </para><para>
/// Note that this method returns a reference to the updated business object.
/// If the server-side DataPortal is running remotely, this will be a new and
/// different object from the original, and all object references MUST be updated
/// to use this new object.
/// </para><para>
/// On the server, the Command object's DataPortal_Execute() method will
/// be invoked and on an ObjectFactory the Execute method will be invoked.
/// Write any server-side code in that method.
/// </para>
/// </remarks>
/// <typeparam name="T">Specific type of the Command object.</typeparam>
/// <param name="obj">A reference to the Command object to be executed.</param>
/// <returns>A reference to the updated Command object.</returns>
public static T Execute<T>(T obj)
{
return Update(obj);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// execute a command object.
/// </summary>
/// <typeparam name="T">
/// Type of object to execute.
/// </typeparam>
/// <param name="obj">
/// Reference to the object to execute.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
public static void BeginExecute<T>(T obj, EventHandler<DataPortalResult<T>> callback)
where T : IMobileObject
{
BeginExecute<T>(obj, callback, null);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// execute a command object.
/// </summary>
/// <typeparam name="T">
/// Type of object to execute.
/// </typeparam>
/// <param name="obj">
/// Reference to the object to execute.
/// </param>
/// <param name="callback">
/// Reference to method that will handle the
/// asynchronous callback when the operation
/// is complete.
/// </param>
/// <param name="userState">User state object.</param>
public static void BeginExecute<T>(T obj, EventHandler<DataPortalResult<T>> callback, object userState)
where T : IMobileObject
{
var dp = new DataPortal<T>();
dp.ExecuteCompleted += callback;
dp.BeginExecute(obj, userState);
}
/// <summary>
/// Starts an asynchronous data portal operation to
/// execute a command object.
/// </summary>
/// <typeparam name="T">
/// Type of object to execute.
/// </typeparam>
/// <param name="command">
/// Reference to the object to execute.
/// </param>
public static async Task<T> ExecuteAsync<T>(T command)
where T : IMobileObject
{
var dp = new DataPortal<T>();
return await dp.ExecuteAsync(command);
}
#endregion
#region Child Data Access methods
/// <summary>
/// Creates and initializes a new
/// child business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
public static T CreateChild<T>()
{
Server.ChildDataPortal portal = new Server.ChildDataPortal();
return (T)(portal.Create(typeof(T)));
}
/// <summary>
/// Creates and initializes a new
/// child business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to create.
/// </typeparam>
/// <param name="parameters">
/// Parameters passed to child create method.
/// </param>
public static T CreateChild<T>(params object[] parameters)
{
Server.ChildDataPortal portal = new Server.ChildDataPortal();
return (T)(portal.Create(typeof(T), parameters));
}
/// <summary>
/// Creates and loads an existing
/// child business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to retrieve.
/// </typeparam>
public static T FetchChild<T>()
{
Server.ChildDataPortal portal = new Server.ChildDataPortal();
return (T)(portal.Fetch(typeof(T)));
}
/// <summary>
/// Creates and loads an existing
/// child business object.
/// </summary>
/// <typeparam name="T">
/// Type of business object to retrieve.
/// </typeparam>
/// <param name="parameters">
/// Parameters passed to child fetch method.
/// </param>
public static T FetchChild<T>(params object[] parameters)
{
Server.ChildDataPortal portal = new Server.ChildDataPortal();
return (T)(portal.Fetch(typeof(T), parameters));
}
/// <summary>
/// Inserts, updates or deletes an existing
/// child business object.
/// </summary>
/// <param name="child">
/// Business object to update.
/// </param>
public static void UpdateChild(object child)
{
Server.ChildDataPortal portal = new Server.ChildDataPortal();
portal.Update(child);
}
/// <summary>
/// Inserts, updates or deletes an existing
/// child business object.
/// </summary>
/// <param name="child">
/// Business object to update.
/// </param>
/// <param name="parameters">
/// Parameters passed to child update method.
/// </param>
public static void UpdateChild(object child, params object[] parameters)
{
Server.ChildDataPortal portal = new Server.ChildDataPortal();
portal.Update(child, parameters);
}
#endregion
#region DataPortal Proxy
private static DataPortalClient.IDataPortalProxyFactory _dataProxyFactory;
/// <summary>
/// Loads the data portal factory.
/// </summary>
internal static void LoadDataPortalProxyFactory()
{
if (_dataProxyFactory == null)
{
if (String.IsNullOrEmpty(ApplicationContext.DataPortalProxyFactory) || ApplicationContext.DataPortalProxyFactory == "Default")
{
_dataProxyFactory = new DataPortalClient.DefaultPortalProxyFactory();
}
else
{
var proxyFactoryType = Type.GetType(ApplicationContext.DataPortalProxyFactory);
_dataProxyFactory = (DataPortalClient.IDataPortalProxyFactory)MethodCaller.CreateInstance(proxyFactoryType);
}
}
}
/// <summary>
/// Gets or sets a reference to a ProxyFactory object
/// that is used to create an instance of the data
/// portal proxy object.
/// </summary>
public static DataPortalClient.IDataPortalProxyFactory ProxyFactory
{
get
{
if (_dataProxyFactory == null)
LoadDataPortalProxyFactory();
return _dataProxyFactory;
}
set
{
_dataProxyFactory = value;
}
}
/// <summary>
/// Gets or sets the assembly qualified type
/// name of the proxy object to be loaded
/// by the data portal. "Local" is a special
/// value used to indicate that the data
/// portal should run in local mode.
/// </summary>
/// <remarks>
/// Deprecated: use ApplicationContext.DataPortalProxy
/// </remarks>
public static string ProxyTypeName
{
get { return ApplicationContext.DataPortalProxy; }
set { ApplicationContext.DataPortalProxy = value; }
}
/// <summary>
/// Resets the data portal proxy type, so the
/// next data portal call will reload the proxy
/// type based on current configuration values.
/// </summary>
public static void ResetProxyFactory()
{
_dataProxyFactory = null;
}
/// <summary>
/// Resets the data portal proxy type, so the
/// next data portal call will reload the proxy
/// type based on current configuration values.
/// </summary>
public static void ResetProxyType()
{
if (_dataProxyFactory != null)
{
_dataProxyFactory.ResetProxyType();
}
}
/// <summary>
/// Releases any remote data portal proxy object, so
/// the next data portal call will create a new
/// proxy instance.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Proxies no longer cached")]
public static void ReleaseProxy()
{ }
#endregion
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using FSWatcher.FS;
namespace FSWatcher.Caching
{
enum ChangeType
{
DirectoryCreated,
DirectoryDeleted,
FileCreated,
FileChanged,
FileDeleted
}
class Change
{
public ChangeType Type { get; private set; }
public string Item { get; private set; }
public Change(ChangeType type, string item)
{
Type = type;
Item = item;
}
}
class Cache
{
private Func<bool> _abortCheck;
private string _dir;
private Action<string, Exception> _onError = null;
private Dictionary<string, string> _directories = new Dictionary<string, string>();
private Dictionary<string, File> _files = new Dictionary<string, File>();
public Cache(string dir, Func<bool> abortCheck)
{
_dir = dir;
_abortCheck = abortCheck;
}
public void Initialize()
{
getSnapshot(_dir, ref _directories, ref _files);
}
public bool IsDirectory(string dir) {
return _directories.ContainsKey(dir.ToString());
}
public void ErrorNotifier(Action<string, Exception> notifier)
{
_onError = notifier;
}
public bool RefreshFromDisk(
Action<string> directoryCreated,
Action<string> directoryDeleted,
Action<string> fileCreated,
Action<string> fileChanged,
Action<string> fileDeleted)
{
while (true)
{
try {
var dirs = new Dictionary<string, string>();
var files = new Dictionary<string, File>();
getSnapshot(_dir, ref dirs, ref files);
var hasChanges = false;
if (handleDeleted(_directories, dirs, directoryDeleted))
hasChanges = true;
if (handleCreated(_directories, dirs, directoryCreated))
hasChanges = true;
if (handleDeleted(_files, files, fileDeleted))
hasChanges = true;
if (handleCreated(_files, files, fileCreated))
hasChanges = true;
if (handleChanged(_files, files, fileChanged))
hasChanges = true;
return hasChanges;
} catch (Exception ex) {
if (_onError != null)
_onError(_dir, ex);
System.Threading.Thread.Sleep(100);
}
}
}
public bool Patch(Change item) {
return applyPatch(item);
}
private bool applyPatch(Change item)
{
if (item == null)
return false;
if (item.Type == ChangeType.DirectoryCreated) {
return add(item.Item, _directories);
}
if (item.Type == ChangeType.DirectoryDeleted) {
return remove(item.Item.ToString(), _directories);
}
if (item.Type == ChangeType.FileCreated) {
return add(getFile(item.Item), _files);
}
if (item.Type == ChangeType.FileChanged) {
return update(getFile(item.Item), _files);
}
if (item.Type == ChangeType.FileDeleted) {
return remove(getFile(item.Item).ToString(), _files);
}
return false;
}
private File getFile(string file)
{
return new File(file, System.IO.Path.GetDirectoryName(file).GetHashCode());
}
private void getSnapshot(
string directory,
ref Dictionary<string, string> dirs,
ref Dictionary<string, File> files)
{
if (_abortCheck())
return;
try {
foreach (var dir in System.IO.Directory.GetDirectories(directory)) {
if (!dirs.ContainsKey(dir.ToString()))
dirs.Add(dir.ToString(), dir);
getSnapshot(dir, ref dirs, ref files);
}
foreach (var filepath in System.IO.Directory.GetFiles(directory)) {
var file = getFile(filepath);
try {
if (!files.ContainsKey(file.ToString()))
files.Add(file.ToString(), file);
} catch (Exception ex) {
if (_onError != null)
_onError(filepath, ex);
}
if (_abortCheck())
return;
}
} catch (Exception ex) {
if (_onError != null)
_onError(directory, ex);
}
}
private bool handleCreated<T>(
Dictionary<string, T> original,
Dictionary<string, T> items,
Action<string> action)
{
var hasChanges = false;
getCreated(original, items)
.ForEach(x => {
if (add(x, original)) {
notify(x.ToString(), action);
hasChanges = true;
}
});
return hasChanges;
}
private bool handleChanged(
Dictionary<string, File> original,
Dictionary<string, File> items,
Action<string> action)
{
var hasChanges = false;
getChanged(original, items)
.ForEach(x => {
if (update(x, original)) {
notify(x.ToString(), action);
hasChanges = true;
}
});
return hasChanges;
}
private bool handleDeleted<T>(
Dictionary<string, T> original,
Dictionary<string, T> items,
Action<string> action)
{
var hasChanges = false;
getDeleted(original, items)
.ForEach(x => {
if (remove(x.ToString(), original)) {
notify(x.ToString(), action);
hasChanges = true;
}
});
return hasChanges;
}
private bool add<T>(T item, Dictionary<string, T> list)
{
lock (list) {
var key = item.ToString();
if (!list.ContainsKey(key)) {
list.Add(key, item);
return true;
}
}
return false;
}
private bool remove<T>(string item, Dictionary<string, T> list)
{
lock (list) {
if (list.ContainsKey(item))
{
list.Remove(item);
return true;
}
}
return false;
}
private bool update(File file, Dictionary<string, File> list)
{
lock (list) {
File originalFile;
if (list.TryGetValue(file.Path, out originalFile)) {
if (!originalFile.Hash.Equals(file.Hash)) {
originalFile.SetHash(file.Hash);
return true;
}
}
}
return false;
}
private void notify(string item, Action<string> action)
{
if (action != null)
action(item.ToString());
}
private List<T> getCreated<T>(
Dictionary<string, T> original,
Dictionary<string, T> items)
{
var added = new List<T>();
foreach (var item in items)
if (!original.ContainsKey(item.Key))
added.Add(item.Value);
return added;
}
private List<File> getChanged(
Dictionary<string, File> original,
Dictionary<string, File> items)
{
var changed = new List<File>();
foreach (var item in items)
{
File val;
if (original.TryGetValue(item.Key, out val))
{
if (val.Hash != item.Value.Hash)
changed.Add(item.Value);
}
}
return changed;
}
private List<T> getDeleted<T>(
Dictionary<string, T> original,
Dictionary<string, T> items)
{
var deleted = new List<T>();
foreach (var item in original)
if (!items.ContainsKey(item.Key))
deleted.Add(item.Value);
return deleted;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using Bloom.Workspace;
using VisualStyles = System.Windows.Forms.VisualStyles;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Windows.Forms.Design;
namespace Messir.Windows.Forms
{
public class SelectedTabChangedEventArgs : EventArgs
{
public readonly TabStripButton SelectedTab;
public SelectedTabChangedEventArgs(TabStripButton tab)
{
SelectedTab = tab;
}
}
/// <summary>
/// Represents a TabStrip control
/// </summary>
public class TabStrip : ToolStrip
{
private TabStripRenderer myRenderer = new TabStripRenderer();
protected TabStripButton mySelTab;
DesignerVerb insPage = null;
public TabStrip() : base()
{
InitControl();
}
public TabStrip(params TabStripButton[] buttons) : base(buttons)
{
InitControl();
}
protected void InitControl()
{
base.RenderMode = ToolStripRenderMode.ManagerRenderMode;
base.Renderer = myRenderer;
myRenderer.RenderMode = this.RenderStyle;
insPage = new DesignerVerb("Insert tab page", new EventHandler(OnInsertPageClicked));
}
public override ISite Site
{
get
{
ISite site = base.Site;
if (site != null && site.DesignMode)
{
IContainer comp = site.Container;
if (comp != null)
{
IDesignerHost host = comp as IDesignerHost;
if (host != null)
{
IDesigner designer = host.GetDesigner(site.Component);
if (designer != null && !designer.Verbs.Contains(insPage))
designer.Verbs.Add(insPage);
}
}
}
return site;
}
set
{
base.Site = value;
}
}
protected void OnInsertPageClicked(object sender, EventArgs e)
{
ISite site = base.Site;
if (site != null && site.DesignMode)
{
IContainer container = site.Container;
if (container != null)
{
TabStripButton btn = new TabStripButton();
container.Add(btn);
btn.Text = btn.Name;
}
}
}
/// <summary>
/// Gets custom renderer for TabStrip. Set operation has no effect
/// </summary>
public new ToolStripRenderer Renderer
{
get { return myRenderer; }
set { base.Renderer = myRenderer; }
}
/// <summary>
/// Gets or sets layout style for TabStrip control
/// </summary>
public new ToolStripLayoutStyle LayoutStyle
{
get { return base.LayoutStyle; }
set
{
switch (value)
{
case ToolStripLayoutStyle.StackWithOverflow:
case ToolStripLayoutStyle.HorizontalStackWithOverflow:
case ToolStripLayoutStyle.VerticalStackWithOverflow:
base.LayoutStyle = ToolStripLayoutStyle.StackWithOverflow;
break;
case ToolStripLayoutStyle.Table:
base.LayoutStyle = ToolStripLayoutStyle.Table;
break;
case ToolStripLayoutStyle.Flow:
base.LayoutStyle = ToolStripLayoutStyle.Flow;
break;
default:
base.LayoutStyle = ToolStripLayoutStyle.StackWithOverflow;
break;
}
}
}
/// <summary>
///
/// </summary>
[Obsolete("Use RenderStyle instead")]
[Browsable(false)]
public new ToolStripRenderMode RenderMode
{
get { return base.RenderMode; }
set { RenderStyle = value; }
}
/// <summary>
/// Gets or sets render style for TabStrip, use it instead of
/// </summary>
[Category("Appearance")]
[Description("Gets or sets render style for TabStrip. You should use this property instead of RenderMode.")]
public ToolStripRenderMode RenderStyle
{
get { return myRenderer.RenderMode; }
set
{
myRenderer.RenderMode = value;
this.Invalidate();
}
}
protected override Padding DefaultPadding
{
get
{
return Padding.Empty;
}
}
[Browsable(false)]
public new Padding Padding
{
get { return DefaultPadding; }
set { }
}
/// <summary>
/// Gets or sets if control should use system visual styles for painting items
/// </summary>
[Category("Appearance")]
[Description("Specifies if TabStrip should use system visual styles for painting items")]
public bool UseVisualStyles
{
get { return myRenderer.UseVisualStyles; }
set
{
myRenderer.UseVisualStyles = value;
this.Invalidate();
}
}
/// <summary>
/// Gets or sets if TabButtons should be drawn flipped
/// </summary>
[Category("Appearance")]
[Description("Specifies if TabButtons should be drawn flipped (for right- and bottom-aligned TabStrips)")]
public bool FlipButtons
{
get { return myRenderer.Mirrored; }
set
{
myRenderer.Mirrored = value;
this.Invalidate();
}
}
/// <summary>
/// Gets or sets currently selected tab
/// </summary>
public TabStripButton SelectedTab
{
get { return mySelTab; }
set
{
if (value == null)
return;
if (mySelTab == value)
return;
if (value.Owner != this)
throw new ArgumentException("Cannot select TabButtons that do not belong to this TabStrip");
OnItemClicked(new ToolStripItemClickedEventArgs(value));
}
}
public event EventHandler<SelectedTabChangedEventArgs> SelectedTabChanged;
protected void OnTabSelected(TabStripButton tab)
{
this.Invalidate();
if (SelectedTabChanged != null)
SelectedTabChanged(this, new SelectedTabChangedEventArgs(tab));
}
protected override void OnItemAdded(ToolStripItemEventArgs e)
{
base.OnItemAdded(e);
if (e.Item is TabStripButton)
SelectedTab = (TabStripButton)e.Item;
}
protected override void OnItemClicked(ToolStripItemClickedEventArgs e)
{
TabStripButton clickedBtn = e.ClickedItem as TabStripButton;
if (clickedBtn != null)
{
this.SuspendLayout();
mySelTab = clickedBtn;
this.ResumeLayout();
OnTabSelected(clickedBtn);
}
base.OnItemClicked(e);
}
}
/// <summary>
/// Represents a TabButton for TabStrip control
/// </summary>
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)]
public class TabStripButton : ToolStripButton
{
public TabStripButton() : base() { InitButton(); }
public TabStripButton(Image image) : base(image) { InitButton(); }
public TabStripButton(string text) : base(text) { InitButton(); }
public TabStripButton(string text, Image image) : base(text, image) { InitButton(); }
public TabStripButton(string Text, Image Image, EventHandler Handler) : base(Text, Image, Handler) { InitButton(); }
public TabStripButton(string Text, Image Image, EventHandler Handler, string name) : base(Text, Image, Handler, name) { InitButton(); }
private void InitButton()
{
m_SelectedFont = this.Font;
}
public override Size GetPreferredSize(Size constrainingSize)
{
Size sz = base.GetPreferredSize(constrainingSize);
if (this.Owner != null && this.Owner.Orientation == Orientation.Vertical)
{
sz.Width += 3;
sz.Height += 10;
}
else
{
sz.Width += 3 + 30;
sz.Height += 10 + 10;
}
return sz;
}
protected override Padding DefaultMargin
{
get
{
return new Padding(0);
}
}
[Browsable(false)]
public new Padding Margin
{
get { return base.Margin; }
set { }
}
[Browsable(false)]
public new Padding Padding
{
get { return base.Padding; }
set { }
}
private Color m_HotTextColor = Control.DefaultForeColor;
[Category("Appearance")]
[Description("Top bar color when this tab is checked")]
public Color BarColor { get; set; }
[Category("Appearance")]
[Description("Text color when TabButton is highlighted")]
public Color HotTextColor
{
get { return m_HotTextColor; }
set { m_HotTextColor = value; }
}
private Color m_SelectedTextColor = Control.DefaultForeColor;
[Category("Appearance")]
[Description("Text color when TabButton is selected")]
public Color SelectedTextColor
{
get { return m_SelectedTextColor; }
set { m_SelectedTextColor = value; }
}
private Font m_SelectedFont;
[Category("Appearance")]
[Description("Font when TabButton is selected")]
public Font SelectedFont
{
get { return (m_SelectedFont == null) ? this.Font : m_SelectedFont; }
set { m_SelectedFont = value; }
}
[Browsable(false)]
[DefaultValue(false)]
public new bool Checked
{
get { return IsSelected; }
set { }
}
/// <summary>
/// Gets or sets if this TabButton is currently selected
/// </summary>
[Browsable(false)]
public bool IsSelected
{
get
{
TabStrip owner = Owner as TabStrip;
if (owner != null)
return (this == owner.SelectedTab);
return false;
}
set
{
if (value == false) return;
TabStrip owner = Owner as TabStrip;
if (owner == null) return;
owner.SelectedTab = this;
}
}
protected override void OnOwnerChanged(EventArgs e)
{
if (Owner != null && !(Owner is TabStrip))
throw new Exception("Cannot add TabStripButton to " + Owner.GetType().Name);
base.OnOwnerChanged(e);
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
/// <summary>
/// Represents a 64-bit signed integer to be stored in or retrieved from a database.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct SqlInt64 : INullable, IComparable, IXmlSerializable
{
private bool m_fNotNull; // false if null. Do not rename (binary serialization)
private long m_value; // Do not rename (binary serialization)
private const long s_lLowIntMask = 0xffffffff;
private const long s_lHighIntMask = unchecked((long)0xffffffff00000000);
// constructor
// construct a Null
private SqlInt64(bool fNull)
{
m_fNotNull = false;
m_value = 0;
}
public SqlInt64(long value)
{
m_value = value;
m_fNotNull = true;
}
// INullable
public bool IsNull
{
get { return !m_fNotNull; }
}
// property: Value
public long Value
{
get
{
if (m_fNotNull)
return m_value;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from long to SqlInt64
public static implicit operator SqlInt64(long x)
{
return new SqlInt64(x);
}
// Explicit conversion from SqlInt64 to long. Throw exception if x is Null.
public static explicit operator long(SqlInt64 x)
{
return x.Value;
}
public override string ToString()
{
return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null);
}
public static SqlInt64 Parse(string s)
{
if (s == SQLResource.NullString)
return SqlInt64.Null;
else
return new SqlInt64(long.Parse(s, null));
}
// Unary operators
public static SqlInt64 operator -(SqlInt64 x)
{
return x.IsNull ? Null : new SqlInt64(-x.m_value);
}
public static SqlInt64 operator ~(SqlInt64 x)
{
return x.IsNull ? Null : new SqlInt64(~x.m_value);
}
// Binary operators
// Arithmetic operators
public static SqlInt64 operator +(SqlInt64 x, SqlInt64 y)
{
if (x.IsNull || y.IsNull)
return Null;
long lResult = x.m_value + y.m_value;
if (SameSignLong(x.m_value, y.m_value) && !SameSignLong(x.m_value, lResult))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64(lResult);
}
public static SqlInt64 operator -(SqlInt64 x, SqlInt64 y)
{
if (x.IsNull || y.IsNull)
return Null;
long lResult = x.m_value - y.m_value;
if (!SameSignLong(x.m_value, y.m_value) && SameSignLong(y.m_value, lResult))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64(lResult);
}
public static SqlInt64 operator *(SqlInt64 x, SqlInt64 y)
{
if (x.IsNull || y.IsNull)
return Null;
bool fNeg = false;
long lOp1 = x.m_value;
long lOp2 = y.m_value;
long lResult;
long lPartialResult = 0;
if (lOp1 < 0)
{
fNeg = true;
lOp1 = -lOp1;
}
if (lOp2 < 0)
{
fNeg = !fNeg;
lOp2 = -lOp2;
}
long lLow1 = lOp1 & s_lLowIntMask;
long lHigh1 = (lOp1 >> 32) & s_lLowIntMask;
long lLow2 = lOp2 & s_lLowIntMask;
long lHigh2 = (lOp2 >> 32) & s_lLowIntMask;
// if both of the high order dwords are non-zero then overflow results
if (lHigh1 != 0 && lHigh2 != 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
lResult = lLow1 * lLow2;
if (lResult < 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
if (lHigh1 != 0)
{
Debug.Assert(lHigh2 == 0);
lPartialResult = lHigh1 * lLow2;
if (lPartialResult < 0 || lPartialResult > long.MaxValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
}
else if (lHigh2 != 0)
{
Debug.Assert(lHigh1 == 0);
lPartialResult = lLow1 * lHigh2;
if (lPartialResult < 0 || lPartialResult > long.MaxValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
}
lResult += lPartialResult << 32;
if (lResult < 0)
throw new OverflowException(SQLResource.ArithOverflowMessage);
if (fNeg)
lResult = -lResult;
return new SqlInt64(lResult);
}
public static SqlInt64 operator /(SqlInt64 x, SqlInt64 y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y.m_value != 0)
{
if ((x.m_value == long.MinValue) && (y.m_value == -1))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlInt64(x.m_value / y.m_value);
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
public static SqlInt64 operator %(SqlInt64 x, SqlInt64 y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y.m_value != 0)
{
if ((x.m_value == long.MinValue) && (y.m_value == -1))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlInt64(x.m_value % y.m_value);
}
else
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
}
// Bitwise operators
public static SqlInt64 operator &(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlInt64(x.m_value & y.m_value);
}
public static SqlInt64 operator |(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlInt64(x.m_value | y.m_value);
}
public static SqlInt64 operator ^(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? Null : new SqlInt64(x.m_value ^ y.m_value);
}
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlInt64
public static explicit operator SqlInt64(SqlBoolean x)
{
return x.IsNull ? Null : new SqlInt64(x.ByteValue);
}
// Implicit conversion from SqlByte to SqlInt64
public static implicit operator SqlInt64(SqlByte x)
{
return x.IsNull ? Null : new SqlInt64(x.Value);
}
// Implicit conversion from SqlInt16 to SqlInt64
public static implicit operator SqlInt64(SqlInt16 x)
{
return x.IsNull ? Null : new SqlInt64(x.Value);
}
// Implicit conversion from SqlInt32 to SqlInt64
public static implicit operator SqlInt64(SqlInt32 x)
{
return x.IsNull ? Null : new SqlInt64(x.Value);
}
// Explicit conversions
// Explicit conversion from SqlSingle to SqlInt64
public static explicit operator SqlInt64(SqlSingle x)
{
if (x.IsNull)
return Null;
float value = x.Value;
if (value > long.MaxValue || value < long.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64((long)value);
}
// Explicit conversion from SqlDouble to SqlInt64
public static explicit operator SqlInt64(SqlDouble x)
{
if (x.IsNull)
return Null;
double value = x.Value;
if (value > long.MaxValue || value < long.MinValue)
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
return new SqlInt64((long)value);
}
// Explicit conversion from SqlMoney to SqlInt64
public static explicit operator SqlInt64(SqlMoney x)
{
return x.IsNull ? Null : new SqlInt64(x.ToInt64());
}
// Explicit conversion from SqlDecimal to SqlInt64
public static explicit operator SqlInt64(SqlDecimal x)
{
if (x.IsNull)
return SqlInt64.Null;
SqlDecimal ssnumTemp = x;
long llRetVal;
// Throw away decimal portion
ssnumTemp.AdjustScale(-ssnumTemp._bScale, false);
// More than 8 bytes of data will always overflow
if (ssnumTemp._bLen > 2)
throw new OverflowException(SQLResource.ConversionOverflowMessage);
// If 8 bytes of data, see if fits in LONGLONG
if (ssnumTemp._bLen == 2)
{
ulong dwl = SqlDecimal.DWL(ssnumTemp._data1, ssnumTemp._data2);
if (dwl > SqlDecimal.s_llMax && (ssnumTemp.IsPositive || dwl != 1 + SqlDecimal.s_llMax))
throw new OverflowException(SQLResource.ConversionOverflowMessage);
llRetVal = (long)dwl;
}
// 4 bytes of data always fits in a LONGLONG
else
llRetVal = ssnumTemp._data1;
//negate result if ssnumTemp negative
if (!ssnumTemp.IsPositive)
llRetVal = -llRetVal;
return new SqlInt64(llRetVal);
}
// Explicit conversion from SqlString to SqlInt
// Throws FormatException or OverflowException if necessary.
public static explicit operator SqlInt64(SqlString x)
{
return x.IsNull ? Null : new SqlInt64(long.Parse(x.Value, null));
}
// Utility functions
private static bool SameSignLong(long x, long y)
{
return ((x ^ y) & unchecked((long)0x8000000000000000L)) == 0;
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value == y.m_value);
}
public static SqlBoolean operator !=(SqlInt64 x, SqlInt64 y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value < y.m_value);
}
public static SqlBoolean operator >(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value > y.m_value);
}
public static SqlBoolean operator <=(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value <= y.m_value);
}
public static SqlBoolean operator >=(SqlInt64 x, SqlInt64 y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value >= y.m_value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator ~
public static SqlInt64 OnesComplement(SqlInt64 x)
{
return ~x;
}
// Alternative method for operator +
public static SqlInt64 Add(SqlInt64 x, SqlInt64 y)
{
return x + y;
}
// Alternative method for operator -
public static SqlInt64 Subtract(SqlInt64 x, SqlInt64 y)
{
return x - y;
}
// Alternative method for operator *
public static SqlInt64 Multiply(SqlInt64 x, SqlInt64 y)
{
return x * y;
}
// Alternative method for operator /
public static SqlInt64 Divide(SqlInt64 x, SqlInt64 y)
{
return x / y;
}
// Alternative method for operator %
public static SqlInt64 Mod(SqlInt64 x, SqlInt64 y)
{
return x % y;
}
public static SqlInt64 Modulus(SqlInt64 x, SqlInt64 y)
{
return x % y;
}
// Alternative method for operator &
public static SqlInt64 BitwiseAnd(SqlInt64 x, SqlInt64 y)
{
return x & y;
}
// Alternative method for operator |
public static SqlInt64 BitwiseOr(SqlInt64 x, SqlInt64 y)
{
return x | y;
}
// Alternative method for operator ^
public static SqlInt64 Xor(SqlInt64 x, SqlInt64 y)
{
return x ^ y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlInt64 x, SqlInt64 y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlInt64 x, SqlInt64 y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlInt64 x, SqlInt64 y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlInt64 x, SqlInt64 y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlInt64 x, SqlInt64 y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlInt64 x, SqlInt64 y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDouble ToSqlDouble()
{
return this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlMoney ToSqlMoney()
{
return this;
}
public SqlDecimal ToSqlDecimal()
{
return this;
}
public SqlSingle ToSqlSingle()
{
return this;
}
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlInt64)
{
SqlInt64 i = (SqlInt64)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlInt64));
}
public int CompareTo(SqlInt64 value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlInt64))
{
return false;
}
SqlInt64 i = (SqlInt64)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
m_fNotNull = false;
}
else
{
m_value = XmlConvert.ToInt64(reader.ReadElementString());
m_fNotNull = true;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(XmlConvert.ToString(m_value));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("long", XmlSchema.Namespace);
}
public static readonly SqlInt64 Null = new SqlInt64(true);
public static readonly SqlInt64 Zero = new SqlInt64(0);
public static readonly SqlInt64 MinValue = new SqlInt64(long.MinValue);
public static readonly SqlInt64 MaxValue = new SqlInt64(long.MaxValue);
} // SqlInt64
} // namespace System.Data.SqlTypes
| |
// This file is part of the C5 Generic Collection Library for C# and CLI
// See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details.
using NUnit.Framework;
using System;
namespace C5.Tests.wrappers
{
namespace events
{
[TestFixture]
public class IList_
{
private ArrayList<int> list;
private ICollectionValue<int> guarded;
private CollectionEventList<int> seen;
[SetUp]
public void Init()
{
list = new ArrayList<int>(TenEqualityComparer.Default);
guarded = new GuardedList<int>(list);
seen = new CollectionEventList<int>(System.Collections.Generic.EqualityComparer<int>.Default);
}
private void listen() { seen.Listen(guarded, EventType.All); }
[Test]
public void Listenable()
{
Assert.AreEqual(EventType.All, guarded.ListenableEvents);
Assert.AreEqual(EventType.None, guarded.ActiveEvents);
listen();
Assert.AreEqual(EventType.All, guarded.ActiveEvents);
}
[Test]
public void SetThis()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list[1] = 45;
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(56, 1), guarded),
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(56,1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(45, 1), guarded),
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(45,1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
}
[Test]
public void Insert()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.Insert(1, 45);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(45,1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(45, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
}
[Test]
public void InsertAll()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.InsertAll(1, new int[] { 666, 777, 888 });
//seen.Print(Console.Error);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(666,1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(666, 1), guarded),
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(777,2), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(777, 1), guarded),
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(888,3), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(888, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.InsertAll(1, new int[] { });
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void InsertFirstLast()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.InsertFirst(45);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(45,0), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(45, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.InsertLast(88);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(88,4), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(88, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
}
[Test]
public void Remove()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.Remove();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(8, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void RemoveFirst()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.RemoveFirst();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(4,0), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(4, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void RemoveLast()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.RemoveLast();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(8,2), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(8, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void Reverse()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.Reverse();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.View(1, 0).Reverse();
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void Sort()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.Sort();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.View(1, 0).Sort();
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void Shuffle()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.Shuffle();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.View(1, 0).Shuffle();
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void RemoveAt()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.RemoveAt(1);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(56,1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(56, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void RemoveInterval()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.RemoveInterval(1, 2);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Cleared, new ClearedRangeEventArgs(false,2,1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.RemoveInterval(1, 0);
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void Update()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.Update(53);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(56, 1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(53, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.Update(67);
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void FindOrAdd()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
int val = 53;
list.FindOrAdd(ref val);
seen.Check(new CollectionEvent<int>[] { });
val = 67;
list.FindOrAdd(ref val);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(67, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
}
[Test]
public void UpdateOrAdd()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
int val = 53;
list.UpdateOrAdd(val);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(56, 1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(53, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
val = 67;
list.UpdateOrAdd(val);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(67, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.UpdateOrAdd(51, out _);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(53, 1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(51, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
// val = 67;
list.UpdateOrAdd(81, out _);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(81, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
}
[Test]
public void RemoveItem()
{
list.Add(4); list.Add(56); list.Add(18);
listen();
list.Remove(53);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(56, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Remove(11);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(18, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void RemoveAll()
{
for (int i = 0; i < 10; i++)
{
list.Add(10 * i + 5);
}
listen();
list.RemoveAll(new int[] { 32, 187, 45 });
//TODO: the order depends on internals of the HashSet
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(35, 1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(45, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.RemoveAll(new int[] { 200, 300 });
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void Clear()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.View(1, 1).Clear();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Cleared, new ClearedRangeEventArgs(false,1,1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.Clear();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Cleared, new ClearedRangeEventArgs(true,2,0), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.Clear();
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void ListDispose()
{
list.Add(4); list.Add(56); list.Add(8);
listen();
list.View(1, 1).Dispose();
seen.Check(new CollectionEvent<int>[] { });
list.Dispose();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Cleared, new ClearedRangeEventArgs(true,3,0), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)
});
list.Dispose();
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void RetainAll()
{
for (int i = 0; i < 10; i++)
{
list.Add(10 * i + 5);
}
listen();
list.RetainAll(new int[] { 32, 187, 45, 62, 82, 95, 2 });
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(15, 1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(25, 1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(55, 1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(75, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.RetainAll(new int[] { 32, 187, 45, 62, 82, 95, 2 });
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void RemoveAllCopies()
{
for (int i = 0; i < 10; i++)
{
list.Add(3 * i + 5);
}
listen();
list.RemoveAllCopies(14);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(11, 1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(14, 1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(17, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.RemoveAllCopies(14);
seen.Check(new CollectionEvent<int>[] { });
}
[Test]
public void Add()
{
listen();
seen.Check(new CollectionEvent<int>[0]);
list.Add(23);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(23, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void AddAll()
{
for (int i = 0; i < 10; i++)
{
list.Add(10 * i + 5);
}
listen();
list.AddAll(new int[] { 45, 56, 67 });
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(45, 1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(56, 1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(67, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.AddAll(new int[] { });
seen.Check(new CollectionEvent<int>[] { });
}
[TearDown]
public void Dispose() { list = null; seen = null; }
[Test]
public void ViewChanged()
{
IList<int> w = list.View(0, 0);
Assert.Throws<UnlistenableEventException>(() => w.CollectionChanged += new CollectionChangedHandler<int>(w_CollectionChanged));
}
[Test]
public void ViewCleared()
{
IList<int> w = list.View(0, 0);
Assert.Throws<UnlistenableEventException>(() => w.CollectionCleared += new CollectionClearedHandler<int>(w_CollectionCleared));
}
[Test]
public void ViewAdded()
{
IList<int> w = list.View(0, 0);
Assert.Throws<UnlistenableEventException>(() => w.ItemsAdded += new ItemsAddedHandler<int>(w_ItemAdded));
}
[Test]
public void ViewInserted()
{
IList<int> w = list.View(0, 0);
Assert.Throws<UnlistenableEventException>(() => w.ItemInserted += new ItemInsertedHandler<int>(w_ItemInserted));
}
[Test]
public void ViewRemoved()
{
IList<int> w = list.View(0, 0);
Assert.Throws<UnlistenableEventException>(() => w.ItemsRemoved += new ItemsRemovedHandler<int>(w_ItemRemoved));
}
[Test]
public void ViewRemovedAt()
{
IList<int> w = list.View(0, 0);
Assert.Throws<UnlistenableEventException>(() => w.ItemRemovedAt += new ItemRemovedAtHandler<int>(w_ItemRemovedAt));
}
private void w_CollectionChanged(object sender)
{
throw new NotImplementedException();
}
private void w_CollectionCleared(object sender, ClearedEventArgs eventArgs)
{
throw new NotImplementedException();
}
private void w_ItemAdded(object sender, ItemCountEventArgs<int> eventArgs)
{
throw new NotImplementedException();
}
private void w_ItemInserted(object sender, ItemAtEventArgs<int> eventArgs)
{
throw new NotImplementedException();
}
private void w_ItemRemoved(object sender, ItemCountEventArgs<int> eventArgs)
{
throw new NotImplementedException();
}
private void w_ItemRemovedAt(object sender, ItemAtEventArgs<int> eventArgs)
{
throw new NotImplementedException();
}
}
[TestFixture]
public class StackQueue
{
private ArrayList<int> list;
private ICollectionValue<int> guarded;
private CollectionEventList<int> seen;
[SetUp]
public void Init()
{
list = new ArrayList<int>(TenEqualityComparer.Default);
guarded = new GuardedList<int>(list);
seen = new CollectionEventList<int>(System.Collections.Generic.EqualityComparer<int>.Default);
}
private void listen() { seen.Listen(guarded, EventType.All); }
[Test]
public void EnqueueDequeue()
{
listen();
list.Enqueue(67);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(67,0), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(67, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Enqueue(2);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(2,1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(2, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Dequeue();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(67,0), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(67, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Dequeue();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(2,0), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(2, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[Test]
public void PushPop()
{
listen();
seen.Check(new CollectionEvent<int>[0]);
list.Push(23);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(23,0), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(23, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Push(-12);
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.Inserted, new ItemAtEventArgs<int>(-12,1), guarded),
new CollectionEvent<int>(EventType.Added, new ItemCountEventArgs<int>(-12, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Pop();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(-12,1), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(-12, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
list.Pop();
seen.Check(new CollectionEvent<int>[] {
new CollectionEvent<int>(EventType.RemovedAt, new ItemAtEventArgs<int>(23,0), guarded),
new CollectionEvent<int>(EventType.Removed, new ItemCountEventArgs<int>(23, 1), guarded),
new CollectionEvent<int>(EventType.Changed, new EventArgs(), guarded)});
}
[TearDown]
public void Dispose() { list = null; seen = null; }
}
}
namespace wrappedarray
{
[TestFixture]
public class Basic
{
[SetUp]
public void Init()
{
}
[TearDown]
public void Dispose()
{
}
[Test]
public void NoExc()
{
WrappedArray<int> wrapped = new WrappedArray<int>(new int[] { 4, 6, 5 });
Assert.AreEqual(6, wrapped[1]);
Assert.IsTrue(IC.Eq(wrapped[1, 2], 6, 5));
//
bool is4(int i) { return i == 4; }
Assert.AreEqual(EventType.None, wrapped.ActiveEvents);
Assert.AreEqual(false, wrapped.All(is4));
Assert.AreEqual(true, wrapped.AllowsDuplicates);
wrapped.Apply(delegate (int i) { });
Assert.AreEqual("{ 5, 6, 4 }", wrapped.Backwards().ToString());
Assert.AreEqual(true, wrapped.Check());
wrapped.Choose();
Assert.AreEqual(true, wrapped.Contains(4));
Assert.AreEqual(true, wrapped.ContainsAll(new ArrayList<int>()));
Assert.AreEqual(1, wrapped.ContainsCount(4));
Assert.AreEqual(Speed.Linear, wrapped.ContainsSpeed);
int[] extarray = new int[5];
wrapped.CopyTo(extarray, 1);
Assert.IsTrue(IC.Eq(extarray, 0, 4, 6, 5, 0));
Assert.AreEqual(3, wrapped.Count);
Assert.AreEqual(Speed.Constant, wrapped.CountSpeed);
Assert.AreEqual(EnumerationDirection.Forwards, wrapped.Direction);
Assert.AreEqual(false, wrapped.DuplicatesByCounting);
Assert.AreEqual(System.Collections.Generic.EqualityComparer<int>.Default, wrapped.EqualityComparer);
Assert.AreEqual(true, wrapped.Exists(is4));
Assert.IsTrue(IC.Eq(wrapped.Filter(is4), 4));
int j = 5;
Assert.AreEqual(true, wrapped.Find(ref j));
Assert.AreEqual(true, wrapped.Find(is4, out j));
Assert.AreEqual("[ 0:4 ]", wrapped.FindAll(is4).ToString());
Assert.AreEqual(0, wrapped.FindIndex(is4));
Assert.AreEqual(true, wrapped.FindLast(is4, out j));
Assert.AreEqual(0, wrapped.FindLastIndex(is4));
Assert.AreEqual(4, wrapped.First);
wrapped.GetEnumerator();
Assert.AreEqual(CHC.SequencedHashCode(4, 6, 5), wrapped.GetSequencedHashCode());
Assert.AreEqual(CHC.UnsequencedHashCode(4, 6, 5), wrapped.GetUnsequencedHashCode());
Assert.AreEqual(Speed.Constant, wrapped.IndexingSpeed);
Assert.AreEqual(2, wrapped.IndexOf(5));
Assert.AreEqual(false, wrapped.IsEmpty);
Assert.AreEqual(true, wrapped.IsReadOnly);
Assert.AreEqual(false, wrapped.IsSorted());
Assert.AreEqual(true, wrapped.IsValid);
Assert.AreEqual(5, wrapped.Last);
Assert.AreEqual(2, wrapped.LastIndexOf(5));
Assert.AreEqual(EventType.None, wrapped.ListenableEvents);
string i2s(int i) { return string.Format("T{0}", i); }
Assert.AreEqual("[ 0:T4, 1:T6, 2:T5 ]", wrapped.Map<string>(i2s).ToString());
Assert.AreEqual(0, wrapped.Offset);
wrapped.Reverse();
Assert.AreEqual("[ 0:5, 1:6, 2:4 ]", wrapped.ToString());
IList<int> other = new ArrayList<int>(); other.AddAll(new int[] { 4, 5, 6 });
Assert.IsFalse(wrapped.SequencedEquals(other));
j = 30;
Assert.AreEqual(true, wrapped.Show(new System.Text.StringBuilder(), ref j, null));
wrapped.Sort();
Assert.AreEqual("[ 0:4, 1:5, 2:6 ]", wrapped.ToString());
Assert.IsTrue(IC.Eq(wrapped.ToArray(), 4, 5, 6));
Assert.AreEqual("[ ... ]", wrapped.ToString("L4", null));
Assert.AreEqual(null, wrapped.Underlying);
Assert.IsTrue(IC.SetEq(wrapped.UniqueItems(), 4, 5, 6));
Assert.IsTrue(wrapped.UnsequencedEquals(other));
wrapped.Shuffle();
Assert.IsTrue(IC.SetEq(wrapped.UniqueItems(), 4, 5, 6));
}
[Test]
public void WithExc()
{
WrappedArray<int> wrapped = new WrappedArray<int>(new int[] { 3, 4, 6, 5, 7 });
//
try { wrapped.Add(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.AddAll(null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Clear(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Dispose(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
int j = 1;
try { wrapped.FindOrAdd(ref j); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Insert(1, 1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Insert(wrapped.View(0, 0), 1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.InsertAll(1, null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.InsertFirst(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.InsertLast(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Remove(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Remove(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveAll(null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveAllCopies(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveAt(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveFirst(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveInterval(0, 0); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveLast(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RetainAll(null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Update(1, out j); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.UpdateOrAdd(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
}
[Test]
public void View()
{
int[] inner = new int[] { 3, 4, 6, 5, 7 };
WrappedArray<int> outerwrapped = new WrappedArray<int>(inner);
WrappedArray<int> wrapped = (WrappedArray<int>)outerwrapped.View(1, 3);
//
Assert.AreEqual(6, wrapped[1]);
Assert.IsTrue(IC.Eq(wrapped[1, 2], 6, 5));
//
bool is4(int i) { return i == 4; }
Assert.AreEqual(EventType.None, wrapped.ActiveEvents);
Assert.AreEqual(false, wrapped.All(is4));
Assert.AreEqual(true, wrapped.AllowsDuplicates);
wrapped.Apply(delegate (int i) { });
Assert.AreEqual("{ 5, 6, 4 }", wrapped.Backwards().ToString());
Assert.AreEqual(true, wrapped.Check());
wrapped.Choose();
Assert.AreEqual(true, wrapped.Contains(4));
Assert.AreEqual(true, wrapped.ContainsAll(new ArrayList<int>()));
Assert.AreEqual(1, wrapped.ContainsCount(4));
Assert.AreEqual(Speed.Linear, wrapped.ContainsSpeed);
int[] extarray = new int[5];
wrapped.CopyTo(extarray, 1);
Assert.IsTrue(IC.Eq(extarray, 0, 4, 6, 5, 0));
Assert.AreEqual(3, wrapped.Count);
Assert.AreEqual(Speed.Constant, wrapped.CountSpeed);
Assert.AreEqual(EnumerationDirection.Forwards, wrapped.Direction);
Assert.AreEqual(false, wrapped.DuplicatesByCounting);
Assert.AreEqual(System.Collections.Generic.EqualityComparer<int>.Default, wrapped.EqualityComparer);
Assert.AreEqual(true, wrapped.Exists(is4));
Assert.IsTrue(IC.Eq(wrapped.Filter(is4), 4));
int j = 5;
Assert.AreEqual(true, wrapped.Find(ref j));
Assert.AreEqual(true, wrapped.Find(is4, out j));
Assert.AreEqual("[ 0:4 ]", wrapped.FindAll(is4).ToString());
Assert.AreEqual(0, wrapped.FindIndex(is4));
Assert.AreEqual(true, wrapped.FindLast(is4, out j));
Assert.AreEqual(0, wrapped.FindLastIndex(is4));
Assert.AreEqual(4, wrapped.First);
wrapped.GetEnumerator();
Assert.AreEqual(CHC.SequencedHashCode(4, 6, 5), wrapped.GetSequencedHashCode());
Assert.AreEqual(CHC.UnsequencedHashCode(4, 6, 5), wrapped.GetUnsequencedHashCode());
Assert.AreEqual(Speed.Constant, wrapped.IndexingSpeed);
Assert.AreEqual(2, wrapped.IndexOf(5));
Assert.AreEqual(false, wrapped.IsEmpty);
Assert.AreEqual(true, wrapped.IsReadOnly);
Assert.AreEqual(false, wrapped.IsSorted());
Assert.AreEqual(true, wrapped.IsValid);
Assert.AreEqual(5, wrapped.Last);
Assert.AreEqual(2, wrapped.LastIndexOf(5));
Assert.AreEqual(EventType.None, wrapped.ListenableEvents);
string i2s(int i) { return string.Format("T{0}", i); }
Assert.AreEqual("[ 0:T4, 1:T6, 2:T5 ]", wrapped.Map<string>(i2s).ToString());
Assert.AreEqual(1, wrapped.Offset);
wrapped.Reverse();
Assert.AreEqual("[ 0:5, 1:6, 2:4 ]", wrapped.ToString());
IList<int> other = new ArrayList<int>(); other.AddAll(new int[] { 4, 5, 6 });
Assert.IsFalse(wrapped.SequencedEquals(other));
j = 30;
Assert.AreEqual(true, wrapped.Show(new System.Text.StringBuilder(), ref j, null));
wrapped.Sort();
Assert.AreEqual("[ 0:4, 1:5, 2:6 ]", wrapped.ToString());
Assert.IsTrue(IC.Eq(wrapped.ToArray(), 4, 5, 6));
Assert.AreEqual("[ ... ]", wrapped.ToString("L4", null));
// TODO: Below line removed as NUnit 3.0 test fails trying to enumerate...
// Assert.AreEqual(outerwrapped, wrapped.Underlying);
Assert.IsTrue(IC.SetEq(wrapped.UniqueItems(), 4, 5, 6));
Assert.IsTrue(wrapped.UnsequencedEquals(other));
//
Assert.IsTrue(wrapped.TrySlide(1));
Assert.IsTrue(IC.Eq(wrapped, 5, 6, 7));
Assert.IsTrue(wrapped.TrySlide(-1, 2));
Assert.IsTrue(IC.Eq(wrapped, 4, 5));
Assert.IsFalse(wrapped.TrySlide(-2));
Assert.IsTrue(IC.Eq(wrapped.Span(outerwrapped.ViewOf(7)), 4, 5, 6, 7));
//
wrapped.Shuffle();
Assert.IsTrue(IC.SetEq(wrapped.UniqueItems(), 4, 5));
Assert.IsTrue(wrapped.IsValid);
wrapped.Dispose();
Assert.IsFalse(wrapped.IsValid);
}
[Test]
public void ViewWithExc()
{
int[] inner = new int[] { 3, 4, 6, 5, 7 };
WrappedArray<int> outerwrapped = new WrappedArray<int>(inner);
WrappedArray<int> wrapped = (WrappedArray<int>)outerwrapped.View(1, 3);
//
try { wrapped.Add(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.AddAll(null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Clear(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
//Should not throw
//try { wrapped.Dispose(); Assert.Fail("No throw"); }
//catch (FixedSizeCollectionException) { }
int j = 1;
try { wrapped.FindOrAdd(ref j); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Insert(1, 1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Insert(wrapped.View(0, 0), 1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.InsertAll(1, null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.InsertFirst(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.InsertLast(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Remove(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Remove(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveAll(null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveAllCopies(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveAt(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveFirst(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveInterval(0, 0); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RemoveLast(); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.RetainAll(null); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.Update(1, out j); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
try { wrapped.UpdateOrAdd(1); Assert.Fail("No throw"); }
catch (FixedSizeCollectionException) { }
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Web.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.StaticWebAssets;
namespace Microsoft.AspNetCore.Components.WebView
{
/// <summary>
/// Manages activities within a web view that hosts Blazor components. Platform authors
/// should subclass this to wire up the abstract and protected methods to the APIs of
/// the platform's web view.
/// </summary>
public abstract class WebViewManager : IAsyncDisposable
{
// These services are not DI services, because their lifetime isn't limited to a single
// per-page-load scope. Instead, their lifetime matches the webview itself.
private readonly IServiceProvider _provider;
private readonly Dispatcher _dispatcher;
private readonly IpcSender _ipcSender;
private readonly IpcReceiver _ipcReceiver;
private readonly Uri _appBaseUri;
private readonly StaticContentProvider _staticContentProvider;
private readonly JSComponentConfigurationStore _jsComponents;
private readonly Dictionary<string, RootComponent> _rootComponentsBySelector = new();
// Each time a web page connects, we establish a new per-page context
private PageContext _currentPageContext;
private bool _disposed;
/// <summary>
/// Constructs an instance of <see cref="WebViewManager"/>.
/// </summary>
/// <param name="provider">The <see cref="IServiceProvider"/> for the application.</param>
/// <param name="dispatcher">A <see cref="Dispatcher"/> instance that can marshal calls to the required thread or sync context.</param>
/// <param name="appBaseUri">The base URI for the application. Since this is a webview, the base URI is typically on a private origin such as http://0.0.0.0/ or app://example/</param>
/// <param name="fileProvider">Provides static content to the webview.</param>
/// <param name="jsComponents">Describes configuration for adding, removing, and updating root components from JavaScript code.</param>
/// <param name="hostPageRelativePath">Path to the host page within the <paramref name="fileProvider"/>.</param>
public WebViewManager(IServiceProvider provider, Dispatcher dispatcher, Uri appBaseUri, IFileProvider fileProvider, JSComponentConfigurationStore jsComponents, string hostPageRelativePath)
{
_provider = provider ?? throw new ArgumentNullException(nameof(provider));
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
_appBaseUri = EnsureTrailingSlash(appBaseUri ?? throw new ArgumentNullException(nameof(appBaseUri)));
fileProvider = StaticWebAssetsLoader.UseStaticWebAssets(fileProvider);
_jsComponents = jsComponents;
_staticContentProvider = new StaticContentProvider(fileProvider, appBaseUri, hostPageRelativePath);
_ipcSender = new IpcSender(_dispatcher, SendMessage);
_ipcReceiver = new IpcReceiver(AttachToPageAsync);
}
/// <summary>
/// Gets the <see cref="Dispatcher"/> used by this <see cref="WebViewManager"/> instance.
/// </summary>
public Dispatcher Dispatcher => _dispatcher;
/// <summary>
/// Instructs the web view to navigate to the specified location, bypassing any
/// client-side routing.
/// </summary>
/// <param name="url">The URL, which may be absolute or relative to the application root.</param>
public void Navigate(string url)
=> NavigateCore(new Uri(_appBaseUri, url));
/// <summary>
/// Instructs the web view to navigate to the specified location, bypassing any
/// client-side routing.
/// </summary>
/// <param name="absoluteUri">The absolute URI.</param>
protected abstract void NavigateCore(Uri absoluteUri);
/// <summary>
/// Sends a message to JavaScript code running in the attached web view. This must
/// be forwarded to the Blazor JavaScript code.
/// </summary>
/// <param name="message">The message.</param>
protected abstract void SendMessage(string message);
/// <summary>
/// Adds a root component to the attached page.
/// </summary>
/// <param name="componentType">The type of the root component. This must implement <see cref="IComponent"/>.</param>
/// <param name="selector">The CSS selector describing where in the page the component should be placed.</param>
/// <param name="parameters">Parameters for the component.</param>
public Task AddRootComponentAsync(Type componentType, string selector, ParameterView parameters)
{
var rootComponent = new RootComponent { ComponentType = componentType, Parameters = parameters };
if (!_rootComponentsBySelector.TryAdd(selector, rootComponent))
{
throw new InvalidOperationException($"There is already a root component with selector '{selector}'.");
}
// If the page is already attached, add the root component to it now. Otherwise we'll
// add it when the page attaches later.
if (_currentPageContext != null)
{
return Dispatcher.InvokeAsync(() =>
{
rootComponent.ComponentId = _currentPageContext.Renderer.AddRootComponent(
componentType, selector);
return _currentPageContext.Renderer.RenderRootComponentAsync(
rootComponent.ComponentId.Value, rootComponent.Parameters);
});
}
else
{
return Task.CompletedTask;
}
}
/// <summary>
/// Removes a previously-attached root component from the current page.
/// </summary>
/// <param name="selector">The CSS selector describing where in the page the component was placed. This must exactly match the selector provided on an earlier call to <see cref="AddRootComponentAsync(Type, string, ParameterView)"/>.</param>
public Task RemoveRootComponentAsync(string selector)
{
if (!_rootComponentsBySelector.Remove(selector, out var rootComponent))
{
throw new InvalidOperationException($"There is no root component with selector '{selector}'.");
}
// If the page is already attached, remove the root component from it now. Otherwise it's
// enough to have updated the dictionary.
if (_currentPageContext != null && rootComponent.ComponentId.HasValue)
{
return Dispatcher.InvokeAsync(() => _currentPageContext.Renderer.RemoveRootComponent(rootComponent.ComponentId.Value));
}
else
{
return Task.CompletedTask;
}
}
/// <summary>
/// Notifies the <see cref="WebViewManager"/> about a message from JavaScript running within the web view.
/// </summary>
/// <param name="sourceUri">The source URI for the message.</param>
/// <param name="message">The message.</param>
protected void MessageReceived(Uri sourceUri, string message)
{
if (!_appBaseUri.IsBaseOf(sourceUri))
{
// It's important that we ignore messages from other origins, otherwise if the webview
// navigates to a remote location, it could send commands that execute locally
return;
}
_ = _dispatcher.InvokeAsync(async () =>
{
// TODO: Verify this produces the correct exception-surfacing behaviors.
// For example, JS interop exceptions should flow back into JS, whereas
// renderer exceptions should be fatal.
try
{
await _ipcReceiver.OnMessageReceivedAsync(_currentPageContext, message);
}
catch (Exception ex)
{
_ipcSender.NotifyUnhandledException(ex);
throw;
}
});
}
/// <summary>
/// Tries to provide the response content for a given network request.
/// </summary>
/// <param name="uri">The uri of the request</param>
/// <param name="allowFallbackOnHostPage">Whether or not to fallback to the host page.</param>
/// <param name="statusCode">The status code of the response.</param>
/// <param name="statusMessage">The response status message.</param>
/// <param name="content">The response content</param>
/// <param name="headers">The response headers</param>
/// <returns><c>true</c> if the response can be provided; <c>false</c> otherwise.</returns>
protected bool TryGetResponseContent(string uri, bool allowFallbackOnHostPage, out int statusCode, out string statusMessage, out Stream content, out IDictionary<string, string> headers)
=> _staticContentProvider.TryGetResponseContent(uri, allowFallbackOnHostPage, out statusCode, out statusMessage, out content, out headers);
internal async Task AttachToPageAsync(string baseUrl, string startUrl)
{
// If there was some previous attached page, dispose all its resources. We're not eagerly disposing
// page contexts when the user navigates away, because we don't get notified about that. We could
// change this if any important reason emerges.
if (_currentPageContext != null)
{
await _currentPageContext.DisposeAsync();
}
var serviceScope = _provider.CreateAsyncScope();
_currentPageContext = new PageContext(_dispatcher, serviceScope, _ipcSender, _jsComponents, baseUrl, startUrl);
// Add any root components that were registered before the page attached. We don't await any of the
// returned render tasks so that the components can be processed in parallel.
var pendingRenders = new List<Task>(_rootComponentsBySelector.Count);
foreach (var (selector, rootComponent) in _rootComponentsBySelector)
{
rootComponent.ComponentId = _currentPageContext.Renderer.AddRootComponent(
rootComponent.ComponentType, selector);
pendingRenders.Add(_currentPageContext.Renderer.RenderRootComponentAsync(
rootComponent.ComponentId.Value, rootComponent.Parameters));
}
// Now we wait for all components to finish rendering.
await Task.WhenAll(pendingRenders);
}
private static Uri EnsureTrailingSlash(Uri uri)
=> uri.AbsoluteUri.EndsWith('/') ? uri : new Uri(uri.AbsoluteUri + '/');
private class RootComponent
{
public Type ComponentType { get; init; }
public ParameterView Parameters { get; init; }
public int? ComponentId { get; set; }
}
/// <summary>
/// Disposes the current <see cref="WebViewManager"/> instance.
/// </summary>
protected virtual async ValueTask DisposeAsyncCore()
{
if (!_disposed)
{
_disposed = true;
if (_currentPageContext != null)
{
await _currentPageContext.DisposeAsync();
}
}
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
// Do not change this code. Put cleanup code in 'DisposeAsync(bool disposing)' method
GC.SuppressFinalize(this);
await DisposeAsyncCore();
}
private class StaticWebAssetsLoader
{
internal static IFileProvider UseStaticWebAssets(IFileProvider fileProvider)
{
var manifestPath = ResolveRelativeToAssembly();
if (File.Exists(manifestPath))
{
using var manifestStream = File.OpenRead(manifestPath);
var manifest = ManifestStaticWebAssetFileProvider.StaticWebAssetManifest.Parse(manifestStream);
if (manifest.ContentRoots.Length > 0)
{
var manifestProvider = new ManifestStaticWebAssetFileProvider(manifest, (path) => new PhysicalFileProvider(path));
return new CompositeFileProvider(manifestProvider, fileProvider);
}
}
return fileProvider;
}
private static string? ResolveRelativeToAssembly()
{
var assembly = Assembly.GetEntryAssembly();
if (string.IsNullOrEmpty(assembly?.Location))
{
return null;
}
var name = Path.GetFileNameWithoutExtension(assembly.Location);
return Path.Combine(Path.GetDirectoryName(assembly.Location)!, $"{name}.staticwebassets.runtime.json");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SuperSocket;
using SuperSocket.Server;
using Xunit;
using Xunit.Abstractions;
namespace SuperSocket.Tests
{
public abstract class ProtocolTestBase : TestClassBase
{
protected ProtocolTestBase(ITestOutputHelper outputHelper) : base(outputHelper)
{
}
protected abstract IServer CreateServer(IHostConfigurator hostConfigurator);
protected abstract string CreateRequest(string sourceLine);
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[InlineData(typeof(GzipSecureHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
[InlineData(typeof(UdpHostConfigurator))]
public virtual async Task TestNormalRequest(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateServer(hostConfigurator))
{
await server.StartAsync();
using (var socket = CreateClient(hostConfigurator))
{
using (var socketStream = await hostConfigurator.GetClientStream(socket))
using (var reader = hostConfigurator.GetStreamReader(socketStream, Utf8Encoding))
using (var writer = new ConsoleWriter(socketStream, Utf8Encoding, 1024 * 8))
{
var line = Guid.NewGuid().ToString();
writer.Write(CreateRequest(line));
writer.Flush();
var receivedLine = await reader.ReadLineAsync();
Assert.Equal(line, receivedLine);
}
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[InlineData(typeof(UdpHostConfigurator))]
[InlineData(typeof(GzipSecureHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
public virtual async Task TestMiddleBreak(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateServer(hostConfigurator))
{
await server.StartAsync();
for (var i = 0; i < 100; i++)
{
using (var socket = CreateClient(hostConfigurator))
{
using (var socketStream = await hostConfigurator.GetClientStream(socket))
using (var reader = hostConfigurator.GetStreamReader(socketStream, Utf8Encoding))
using (var writer = new ConsoleWriter(socketStream, Utf8Encoding, 1024 * 8))
{
var line = Guid.NewGuid().ToString();
var sendingLine = CreateRequest(line);
writer.Write(sendingLine.Substring(0, sendingLine.Length / 2));
writer.Flush();
await hostConfigurator.KeepSequence();
}
}
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[InlineData(typeof(UdpHostConfigurator))]
[InlineData(typeof(GzipSecureHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
public virtual async Task TestFragmentRequest(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateServer(hostConfigurator))
{
await server.StartAsync();
using (var socket = CreateClient(hostConfigurator))
{
using (var socketStream = await hostConfigurator.GetClientStream(socket))
using (var reader = hostConfigurator.GetStreamReader(socketStream, Utf8Encoding))
using (var writer = new ConsoleWriter(socketStream, Utf8Encoding, 1024 * 8))
{
var line = Guid.NewGuid().ToString();
var request = CreateRequest(line);
for (var i = 0; i < request.Length; i++)
{
writer.Write(request[i]);
writer.Flush();
Thread.Sleep(50);
await hostConfigurator.KeepSequence();
}
var receivedLine = await reader.ReadLineAsync();
Assert.Equal(line, receivedLine);
}
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[InlineData(typeof(UdpHostConfigurator))]
[InlineData(typeof(GzipSecureHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
public virtual async Task TestBatchRequest(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateServer(hostConfigurator))
{
await server.StartAsync();
using (var socket = CreateClient(hostConfigurator))
{
using (var socketStream = await hostConfigurator.GetClientStream(socket))
using (var reader = hostConfigurator.GetStreamReader(socketStream, Utf8Encoding))
using (var writer = new ConsoleWriter(socketStream, Utf8Encoding, 1024 * 8))
{
int size = 100;
var lines = new string[size];
for (var i = 0; i < size; i++)
{
var line = Guid.NewGuid().ToString();
lines[i] = line;
var request = CreateRequest(line);
writer.Write(request);
await hostConfigurator.KeepSequence();
}
writer.Flush();
await hostConfigurator.KeepSequence();
for (var i = 0; i < size; i++)
{
var receivedLine = await reader.ReadLineAsync();
Assert.Equal(lines[i], receivedLine);
}
}
}
await server.StopAsync();
}
}
[Theory]
[InlineData(typeof(RegularHostConfigurator))]
[InlineData(typeof(SecureHostConfigurator))]
[InlineData(typeof(GzipSecureHostConfigurator))]
[InlineData(typeof(GzipHostConfigurator))]
//[InlineData(typeof(UdpHostConfigurator))]
public virtual async Task TestBreakRequest(Type hostConfiguratorType)
{
var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType);
using (var server = CreateServer(hostConfigurator))
{
await server.StartAsync();
using (var socket = CreateClient(hostConfigurator))
{
using (var socketStream = await hostConfigurator.GetClientStream(socket))
using (var reader = hostConfigurator.GetStreamReader(socketStream, Utf8Encoding))
using (var writer = new ConsoleWriter(socketStream, Utf8Encoding, 1024 * 8))
{
int size = 1000;
var lines = new string[size];
var sb = new StringBuilder();
for (var i = 0; i < size; i++)
{
var line = Guid.NewGuid().ToString();
lines[i] = line;
sb.Append(CreateRequest(line));
}
var source = sb.ToString();
var rd = new Random();
var rounds = new List<KeyValuePair<int, int>>();
var rest = source.Length;
while (rest > 0)
{
if (rest == 1)
{
rounds.Add(new KeyValuePair<int, int>(source.Length - rest, 1));
rest = 0;
break;
}
var thisRound = rd.Next(1, rest);
rounds.Add(new KeyValuePair<int, int>(source.Length - rest, thisRound));
rest -= thisRound;
}
for (var i = 0; i < rounds.Count; i++)
{
var r = rounds[i];
writer.Write(source.Substring(r.Key, r.Value));
writer.Flush();
await hostConfigurator.KeepSequence();
}
for (var i = 0; i < size; i++)
{
var receivedLine = await reader.ReadLineAsync();
Assert.Equal(lines[i], receivedLine);
}
}
}
await server.StopAsync();
}
}
}
}
| |
using EasyLOB.Library;
using FluentFTP;
using System;
using System.IO;
using System.Net;
// Install-Package FluentFTP
/*
/a/b/c.xlsx
Directory
a
b
File
c.xlsx
DirectoryPath
/a
/a/b
FilePath
/a/b/c.xlsx
FTP
/EDM <= Root Directory
/Entity1
000000000 <= Key 0 to 99
000000100 <= Key 100 to 199
...
/Entity2
000000000
000000100
...
*/
namespace EasyLOB.Extensions.Edm
{
public partial class EdmManagerFTP : IEdmManager
{
#region Properties
private FtpClient ftpClient;
#endregion Properties
#region Properties Interface
public string RootDirectory { get; }
#endregion Properties Interface
#region Methods
public EdmManagerFTP()
{
RootDirectory = ConfigurationHelper.AppSettings<string>("EDM.FTP.Root");
ftpClient = new FtpClient();
ftpClient.Host = ConfigurationHelper.AppSettings<string>("EDM.FTP.Server");
ftpClient.Port = ConfigurationHelper.AppSettings<int>("EDM.FTP.Port");
ftpClient.Credentials = new NetworkCredential(ConfigurationHelper.AppSettings<string>("EDM.FTP.User"),
ConfigurationHelper.AppSettings<string>("EDM.FTP.Password"));
ftpClient.Connect();
}
public EdmManagerFTP(string rootDirectory)
: this()
{
RootDirectory = rootDirectory;
}
protected bool FTPCreateDirectory(string directory)
{
ftpClient.CreateDirectory(directory);
return FTPDirectoryExists(directory);
}
protected bool FTPCreateDirectoryPath(string directoryPath)
{
string workingDirectory = "";
try
{
workingDirectory = ftpClient.GetWorkingDirectory();
ftpClient.SetWorkingDirectory("/");
string currentDirectory = "";
var separators = new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar };
string[] directories = directoryPath.Split(separators);
foreach (string directory in directories)
{
if (!ftpClient.DirectoryExists(directory))
{
ftpClient.CreateDirectory(directory);
}
currentDirectory += "/" + directory;
ftpClient.SetWorkingDirectory(currentDirectory);
}
}
finally
{
if (!String.IsNullOrEmpty(workingDirectory))
{
ftpClient.SetWorkingDirectory(workingDirectory);
}
}
return FTPDirectoryExists(directoryPath);
}
protected bool FTPDirectoryExists(string directory)
{
bool result;
string workingDirectory = "";
try
{
workingDirectory = ftpClient.GetWorkingDirectory();
ftpClient.SetWorkingDirectory("/");
result = ftpClient.DirectoryExists(directory);
}
finally
{
if (!String.IsNullOrEmpty(workingDirectory))
{
ftpClient.SetWorkingDirectory(workingDirectory);
}
}
return result;
}
protected bool FTPFileExists(string filePath)
{
bool result;
string workingDirectory = "";
try
{
workingDirectory = ftpClient.GetWorkingDirectory();
ftpClient.SetWorkingDirectory("/");
result = ftpClient.FileExists(filePath);
}
finally
{
if (!String.IsNullOrEmpty(workingDirectory))
{
ftpClient.SetWorkingDirectory(workingDirectory);
}
}
return result;
}
#endregion Methods
#region Methods IDispose
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
if (ftpClient != null)
{
ftpClient.Disconnect();
}
}
disposed = true;
}
}
#endregion Methods IDispose
#region Methods Interface
public bool DeleteFile(int key, ZFileTypes fileType)
{
return DeleteFile("", key, fileType);
}
public bool DeleteFile(string entityName, int key, ZFileTypes fileType)
{
bool result;
string filePath = GetFilePath(entityName, key, fileType, false);
if (FTPFileExists(filePath))
{
ftpClient.DeleteFile(filePath);
result = true;
}
else
{
result = false;
}
return result;
}
public bool DeleteFile(string edmFilePath)
{
bool result;
string filePath = GetFilePath(edmFilePath, false);
if (FTPFileExists(filePath))
{
ftpClient.DeleteFile(filePath);
result = true;
}
else
{
result = false;
}
return result;
}
public bool FileExists(int key, ZFileTypes fileType)
{
return FileExists("", key, fileType);
}
public bool FileExists(string entityName, int key, ZFileTypes fileType)
{
return FTPFileExists(GetFilePath(entityName, key, fileType, false));
}
public bool FileExists(string edmFilePath)
{
return FTPFileExists(GetFilePath(edmFilePath, false));
}
public string GetFilePath(int key, ZFileTypes fileType, bool create)
{
return GetFilePath("", key, fileType, create);
}
public string GetFilePath(string entityName, int key, ZFileTypes fileType, bool create)
{
string filePath = "";
string extension = LibraryHelper.GetFileExtension(fileType);
string workingDirectory = "";
try
{
workingDirectory = ftpClient.GetWorkingDirectory();
entityName = (entityName == null) ? "" : entityName;
string entityKey = String.Format("{0:000000000}", (key / 100) * 100);
string directoryPath = LibraryHelper.AddDirectorySeparator(RootDirectory) +
((entityName == "") ? entityName : entityName + "/") +
entityKey;
FTPCreateDirectoryPath(directoryPath);
/*
ftpClient.SetWorkingDirectory("/");
if (!FTPDirectoryExists(path) && create) // /root/entityName/entityTree
{
if (FTPCreateDirectory(RootDirectory))
{
ftpClient.SetWorkingDirectory(RootDirectory);
if (FTPCreateDirectory(entityName))
{
ftpClient.SetWorkingDirectory(entityName);
FTPCreateDirectory(entityTree);
}
}
}
*/
ftpClient.SetWorkingDirectory("/");
if (FTPDirectoryExists(directoryPath))
{
filePath = directoryPath + "/" + String.Format("{0:000000000}", key) + extension;
}
}
finally
{
if (!String.IsNullOrEmpty(workingDirectory))
{
ftpClient.SetWorkingDirectory(workingDirectory);
}
}
return filePath;
}
public string GetFilePath(string edmFilePath, bool create)
{
string filePath = "";
string directoryPath = Path.GetDirectoryName(LibraryHelper.AddDirectorySeparator(RootDirectory) + edmFilePath);
if (!FTPDirectoryExists(directoryPath) && create)
{
FTPCreateDirectoryPath(directoryPath);
}
if (FTPDirectoryExists(directoryPath))
{
filePath = LibraryHelper.AddDirectorySeparator(RootDirectory) + edmFilePath;
}
return filePath;
}
public byte[] ReadFile(int key, ZFileTypes fileType)
{
return ReadFile("", key, fileType);
}
public byte[] ReadFile(string entityName, int key, ZFileTypes fileType)
{
byte[] file = new byte[0];
string path = GetFilePath(entityName, key, fileType, false);
if (FTPFileExists(path))
{
ftpClient.SetWorkingDirectory("/");
using (var ftpStream = ftpClient.OpenRead(path))
using (var memoryStream = new MemoryStream((int)ftpStream.Length))
{
int count;
byte[] buffer = new byte[8 * 1024];
while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, count);
}
file = memoryStream.ToArray();
}
}
return file;
}
public byte[] ReadFile(string filePath)
{
return new byte[0] { };
}
public bool WriteFile(int key, ZFileTypes fileType, byte[] file)
{
return WriteFile("", key, fileType, file);
}
public bool WriteFile(int key, ZFileTypes fileType, string filePath)
{
return WriteFile("", key, fileType, filePath);
}
public bool WriteFile(string entityName, int key, ZFileTypes fileType, byte[] file)
{
bool result = false;
ftpClient.SetWorkingDirectory("/");
using (var memoryStream = new MemoryStream(file))
using (var ftpStream = ftpClient.OpenWrite(GetFilePath(entityName, key, fileType, true)))
{
int count;
byte[] buffer = new byte[8 * 1024];
while ((count = memoryStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
}
}
result = true;
return result;
}
public bool WriteFile(string entityName, int key, ZFileTypes fileType, string filePath)
{
bool result = false;
if (File.Exists(filePath))
{
ftpClient.SetWorkingDirectory("/");
using (var fileStream = File.OpenRead(filePath))
using (var ftpStream = ftpClient.OpenWrite(GetFilePath(entityName, key, fileType, true)))
{
int count;
byte[] buffer = new byte[8 * 1024];
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
}
}
result = true;
}
return result;
}
public bool WriteFile(string edmFilePath, byte[] file)
{
bool result = false;
ftpClient.SetWorkingDirectory("/");
using (var memoryStream = new MemoryStream(file))
using (var ftpStream = ftpClient.OpenWrite(GetFilePath(edmFilePath, true)))
{
int count;
byte[] buffer = new byte[8 * 1024];
while ((count = memoryStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
}
}
result = true;
return result;
}
public bool WriteFile(string edmFilePath, string filePath)
{
bool result = false;
if (File.Exists(filePath))
{
ftpClient.SetWorkingDirectory("/");
using (var fileStream = File.OpenRead(filePath))
using (var ftpStream = ftpClient.OpenWrite(GetFilePath(edmFilePath, true)))
{
int count;
byte[] buffer = new byte[8 * 1024];
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
ftpStream.Write(buffer, 0, count);
}
}
result = true;
}
return result;
}
#endregion Methods Interface
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using StructureMap.Graph;
using StructureMap.Interceptors;
using StructureMap.Pipeline;
using StructureMap.Util;
using StructureMap.Construction;
namespace StructureMap
{
public class BuildSession : IContext
{
private readonly ObjectBuilder _builder;
private readonly InstanceCache _cache = new InstanceCache();
private readonly Cache<Type, Func<object>> _defaults;
private readonly PipelineGraph _pipelineGraph;
protected BuildStack _buildStack = new BuildStack();
public BuildSession(PipelineGraph pipelineGraph, InterceptorLibrary interceptorLibrary)
{
_builder = new ObjectBuilder(pipelineGraph, interceptorLibrary);
_pipelineGraph = pipelineGraph;
_defaults = new Cache<Type, Func<object>>(t =>
{
Instance instance = _pipelineGraph.GetDefault(t);
if (instance == null)
{
throw new StructureMapException(202, t);
}
return () => CreateInstance(t, instance);
});
}
public BuildSession(PluginGraph graph)
: this(new PipelineGraph(graph), graph.InterceptorLibrary)
{
}
public BuildSession()
: this(new PluginGraph())
{
}
protected PipelineGraph pipelineGraph { get { return _pipelineGraph; } }
#region IContext Members
public string RequestedName { get; set; }
public BuildStack BuildStack { get { return _buildStack; } }
public Type ParentType
{
get
{
if (_buildStack.Parent != null) return _buildStack.Parent.ConcreteType;
return null;
}
}
public void BuildUp(object target)
{
Type pluggedType = target.GetType();
IConfiguredInstance instance = _pipelineGraph.GetDefault(pluggedType) as IConfiguredInstance
?? new ConfiguredInstance(pluggedType);
IInstanceBuilder builder = PluginCache.FindBuilder(pluggedType);
var arguments = new Arguments(instance, this);
builder.BuildUp(arguments, target);
}
public T GetInstance<T>()
{
return (T) CreateInstance(typeof (T));
}
public object GetInstance(Type pluginType)
{
return CreateInstance(pluginType);
}
public T GetInstance<T>(string name)
{
return (T) CreateInstance(typeof (T), name);
}
BuildFrame IContext.Root { get { return _buildStack.Root; } }
public virtual void RegisterDefault(Type pluginType, object defaultObject)
{
RegisterDefault(pluginType, () => defaultObject);
}
public T TryGetInstance<T>() where T : class
{
if (_defaults.Has(typeof (T)))
{
return (T) _defaults[typeof (T)]();
}
return _pipelineGraph.HasDefaultForPluginType(typeof (T))
? ((IContext) this).GetInstance<T>()
: null;
}
public T TryGetInstance<T>(string name) where T : class
{
return _pipelineGraph.HasInstance(typeof (T), name) ? ((IContext) this).GetInstance<T>(name) : null;
}
public IEnumerable<T> All<T>() where T : class
{
var list = new List<T>();
_cache.Each<T>(list.Add);
return list;
}
#endregion
public IEnumerable<T> GetAllInstances<T>()
{
return (IEnumerable<T>) forType(typeof (T)).AllInstances.Select(x => (T)CreateInstance(typeof(T), x));
}
protected void clearBuildStack()
{
_buildStack = new BuildStack();
}
public virtual object CreateInstance(Type pluginType, string name)
{
Instance instance = forType(pluginType).FindInstance(name);
if (instance == null)
{
throw new StructureMapException(200, name, pluginType.FullName);
}
return CreateInstance(pluginType, instance);
}
// This is where all Creation happens
public virtual object CreateInstance(Type pluginType, Instance instance)
{
object result = _cache.Get(pluginType, instance);
if (result == null)
{
result = _builder.Resolve(pluginType, instance, this);
// TODO: HACK ATTACK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
bool isUnique = forType(pluginType).Lifecycle is UniquePerRequestLifecycle;
if (!isUnique)
{
_cache.Set(pluginType, instance, result);
}
}
return result;
}
[Obsolete("Move all of this into the new EnumerableInstance")]
public virtual Array CreateInstanceArray(Type pluginType, Instance[] instances)
{
if (instances == null)
{
instances = forType(pluginType).AllInstances;
}
Array array = Array.CreateInstance(pluginType, instances.Length);
for (int i = 0; i < instances.Length; i++)
{
Instance instance = instances[i];
object arrayValue = CreateInstance(pluginType, instance);
array.SetValue(arrayValue, i);
}
return array;
}
public IEnumerable<object> GetAllInstances(Type pluginType)
{
return forType(pluginType).AllInstances.Select(x => CreateInstance(pluginType, x));
}
public virtual object CreateInstance(Type pluginType)
{
return _defaults[pluginType]();
}
public virtual void RegisterDefault(Type pluginType, Func<object> creator)
{
_defaults[pluginType] = creator;
}
private IInstanceFactory forType(Type pluginType)
{
return _pipelineGraph.ForType(pluginType);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using StudentSystemServices.Areas.HelpPage.Models;
namespace StudentSystemServices.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
// Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors.
// Contributors can be discovered using the 'git log' command.
// All rights reserved.
// </copyright>
// <license>
// The software is licensed under the Apache 2.0 License (the "License")
// You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------
namespace ClrPlus.Core.Collections {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Extensions;
/// <summary>
/// This behaves like a regular dictionary, except:
/// - add operations will silently replace existing values the
/// - inedexer [] will silently add values
/// - Getting values will return default(TValue) instead of throwing on no element.
/// - setting a value to default(TValue) removes the key
/// </summary>
/// <typeparam name="TKey"> </typeparam>
/// <typeparam name="TValue"> </typeparam>
[XmlRoot("Dictionary")]
public class XDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ISerializable, IDictionary, IXmlSerializable {
public delegate void CollectionChanged(IDictionary<TKey, TValue> source);
private readonly InternalDictionary<TKey, TValue> _base;
public event CollectionChanged Changed = (collection) => {};
/// <summary>
/// Creates a new instance of Dictionary.
/// </summary>
/// <param name="defaultValue"> Default value to use when a requested key is not present in the collection. </param>
public XDictionary(TValue defaultValue)
: this() {
Default = defaultValue;
}
public XDictionary() {
_base = new InternalDictionary<TKey, TValue>();
}
public XDictionary(int capacity) {
_base = new InternalDictionary<TKey, TValue>(capacity);
}
public XDictionary(IEqualityComparer<TKey> comparer) {
_base = new InternalDictionary<TKey, TValue>(comparer);
}
public XDictionary(IDictionary<TKey, TValue> dictionary) {
_base = new InternalDictionary<TKey, TValue>(dictionary);
}
protected XDictionary(SerializationInfo info, StreamingContext context) {
_base = new InternalDictionary<TKey, TValue>(info, context);
}
/// <summary>
/// Gets or sets the default value returned when a non-existing key is requested from the Dictionary.
/// </summary>
public TValue Default {get; set;}
/// <summary>
/// Gets or sets the value associated with the key.
/// </summary>
/// <param name="key"> Key into the collection. </param>
/// <returns> Value associated with the key, or if the key is not a part of the collection, then the value specified by the Default property. </returns>
public virtual TValue this[TKey key] {
get {
return _base.ContainsKey(key) ? _base[key] : Default;
}
set {
if (!_base.ContainsKey(key)) {
_base.Add(key, value);
} else {
_base[key] = value;
}
Changed(this);
}
}
public int RemoveAll(ICollection<TValue> values) {
if (values == null) {
throw new ArgumentNullException("values");
}
var keys = new List<TKey>(values.Count);
keys.AddRange(from entry in this from value in values where entry.Value.Equals(value) select entry.Key);
// get matching keys for the specified values
return RemoveAll(keys);
}
public int RemoveAll(ICollection<TKey> keys) {
if (keys == null) {
throw new ArgumentNullException("keys");
}
var ret = keys.Count(key => _base.Remove(key));
Changed(this);
return ret;
}
public bool ContainsKey(TKey key) {
return _base.ContainsKey(key);
}
public void AddPair(object k, object v) {
Add((TKey)k, (TValue)v);
}
public void Add(TKey key, TValue value) {
object o = value;
if (o == null || value.Equals(Default)) {
_base.Remove(key);
Changed(this);
return;
}
if (_base.ContainsKey(key)) {
_base[key] = value;
} else {
_base.Add(key, value);
}
Changed(this);
}
public void Add(KeyValuePair<TKey, TValue> item) {
this[item.Key] = item.Value;
}
public bool Remove(TKey key) {
var result = _base.Remove(key);
Changed(this);
return result;
}
public bool TryGetValue(TKey key, out TValue value) {
return _base.TryGetValue(key, out value);
}
public ICollection<TKey> Keys {
get {
return _base.Keys;
}
}
public ICollection<TValue> Values {
get {
return _base.Values;
}
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
((ICollection<KeyValuePair<TKey, TValue>>)_base).Add(item);
Changed(this);
}
public void Clear() {
_base.Clear();
Changed(this);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
return ((ICollection<KeyValuePair<TKey, TValue>>)_base).Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
((ICollection<KeyValuePair<TKey, TValue>>)_base).CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
var result = ((ICollection<KeyValuePair<TKey, TValue>>)_base).Remove(item);
Changed(this);
return result;
}
public int Count {
get {
return _base.Count;
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
get {
return ((ICollection<KeyValuePair<TKey, TValue>>)_base).IsReadOnly;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
return _base.GetEnumerator();
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
_base.GetObjectData(info, context);
}
XmlSchema IXmlSerializable.GetSchema() {
return null;
}
void IXmlSerializable.ReadXml(XmlReader reader) {
// some types can be stored easily as attributes while others require their own XML rendering
Func<TKey> readKey;
Func<TValue> readValue;
var isAttributable = new {
Key = typeof (TKey).IsParsable(),
Value = typeof (TValue).IsParsable()
};
// keys
if (isAttributable.Key) {
//readKey = () => (TKey)Convert.ChangeType(reader.GetAttribute("key"), typeof (TKey));
readKey = () => (TKey)typeof (TKey).ParseString(reader.GetAttribute("key"));
} else {
var keySerializer = new XmlSerializer(typeof (TKey));
readKey = () => {
while (reader.Name != "key") {
reader.Read();
}
reader.ReadStartElement("key");
var key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
return key;
};
}
// values
if (isAttributable.Value && isAttributable.Key) {
// readValue = () => (TValue)Convert.ChangeType(reader.GetAttribute("value"), typeof (TValue));
readValue = () => (TValue)typeof (TValue).ParseString(reader.GetAttribute("value"));
} else {
var valueSerializer = new XmlSerializer(typeof (TValue));
readValue = () => {
while (reader.Name == "item") {
reader.Read();
}
// reader.ReadStartElement("value");
var value = (TValue)valueSerializer.Deserialize(reader);
// reader.ReadEndElement();
return value;
};
}
var wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty) {
return;
}
while (reader.NodeType != XmlNodeType.EndElement) {
//while (reader.Name != "item" || reader.NodeType == System.Xml.XmlNodeType.EndElement)
// reader.Read();
while (reader.NodeType == XmlNodeType.Whitespace) {
reader.Read();
}
var key = readKey();
var value = readValue();
Add(key, value);
if (!isAttributable.Key || !isAttributable.Value) {
reader.ReadEndElement();
} else {
reader.Read();
}
while (reader.NodeType == XmlNodeType.Whitespace) {
reader.Read();
}
}
reader.ReadEndElement();
}
void IXmlSerializable.WriteXml(XmlWriter writer) {
Action<TKey> writeKey;
Action<TValue> writeValue;
var isAttributable = new {
Key = typeof (TKey).IsParsable(),
Value = typeof (TValue).IsParsable()
};
if (isAttributable.Key) {
writeKey = v => writer.WriteAttributeString("key", v.ToString());
} else {
var keySerializer = new XmlSerializer(typeof (TKey));
writeKey = v => {
writer.WriteStartElement("key");
keySerializer.Serialize(writer, v);
writer.WriteEndElement();
};
}
// when keys aren't attributable, neither are values
if (isAttributable.Value && isAttributable.Key) {
writeValue = v => writer.WriteAttributeString("value", v.ToString());
} else {
var valueSerializer = new XmlSerializer(typeof (TValue));
writeValue = v => {
// writer.WriteStartElement("value");
valueSerializer.Serialize(writer, v);
// writer.WriteEndElement();
};
}
foreach (var key in Keys) {
writer.WriteStartElement("item");
writeKey(key);
writeValue(this[key]);
writer.WriteEndElement();
}
}
#if false
/// <summary>
/// Determines if a type is simple enough to where it can be stored as an attribute instead of in its own node.
/// </summary>
/// <returns> True if the type can be stored as an attribute of a node instead of its own dedicated node (and thus requiring more serialization work). </returns>
// private static bool IsAttributable(Type t) {
// return _attributableTypes.Contains(t);
// }
#endif
void IDictionary.Add(object key, object value) {
this.Add((TKey)key, (TValue)value);
}
void IDictionary.Clear() {
this.Clear();
}
bool IDictionary.Contains(object key) {
return this.ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
throw new NotImplementedException();
}
bool IDictionary.IsFixedSize {
get {
return false;
}
}
bool IDictionary.IsReadOnly {
get {
return ((ICollection<KeyValuePair<TKey, TValue>>)this).IsReadOnly;
}
}
ICollection IDictionary.Keys {
get {
return (ICollection)this.Keys;
}
}
void IDictionary.Remove(object key) {
this.Remove((TKey)key);
}
ICollection IDictionary.Values {
get {
return (ICollection)this.Values;
}
}
object IDictionary.this[object key] {
get {
return this[(TKey)key];
}
set {
this[(TKey)key] = (TValue)value;
}
}
void ICollection.CopyTo(Array array, int index) {
var pos = index;
foreach (var value in this.Values) {
array.SetValue(value, pos);
pos++;
}
}
int ICollection.Count {
get {
return this.Count;
}
}
bool ICollection.IsSynchronized {
get {
throw new NotImplementedException();
}
}
object ICollection.SyncRoot {
get {
throw new NotImplementedException();
}
}
public IDisposable Subscribe(IObserver<IDictionary<TKey, TValue>> observer) {
throw new NotImplementedException();
}
}
}
| |
public static class GlobalMembersGdimagepolygon3
{
#if __cplusplus
#endif
#define GD_H
#define GD_MAJOR_VERSION
#define GD_MINOR_VERSION
#define GD_RELEASE_VERSION
#define GD_EXTRA_VERSION
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_VERSION_STR(mjr, mnr, rev, ext) mjr "." mnr "." rev ext
#define GDXXX_VERSION_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_STR(s) gd.gdXXX_SSTR(s)
#define GDXXX_STR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdXXX_SSTR(s) #s
#define GDXXX_SSTR
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define GD_VERSION_STRING "GD_MAJOR_VERSION" "." "GD_MINOR_VERSION" "." "GD_RELEASE_VERSION" GD_EXTRA_VERSION
#define GD_VERSION_STRING
#if _WIN32 || CYGWIN || _WIN32_WCE
#if BGDWIN32
#if NONDLL
#define BGD_EXPORT_DATA_PROT
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllexport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
#else
#if __GNUC__
#define BGD_EXPORT_DATA_PROT
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_EXPORT_DATA_PROT __declspec(dllimport)
#define BGD_EXPORT_DATA_PROT
#endif
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_STDCALL __stdcall
#define BGD_STDCALL
#define BGD_EXPORT_DATA_IMPL
#else
#if HAVE_VISIBILITY
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#else
#define BGD_EXPORT_DATA_PROT
#define BGD_EXPORT_DATA_IMPL
#endif
#define BGD_STDCALL
#endif
#if BGD_EXPORT_DATA_PROT_ConditionalDefinition1
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition2
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition3
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllexport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#elif BGD_EXPORT_DATA_PROT_ConditionalDefinition4
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) __declspec(dllimport) rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#else
#if BGD_STDCALL_ConditionalDefinition1
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt __stdcall
#define BGD_DECLARE
#elif BGD_STDCALL_ConditionalDefinition2
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define BGD_DECLARE (rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt
#define BGD_DECLARE
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define Bgd.gd_DECLARE(rt) BGD_EXPORT_DATA_PROTTangibleTempImmunity rt BGD_STDCALLTangibleTempImmunity
#define BGD_DECLARE
#endif
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GD_IO_H
#if VMS
#endif
#if __cplusplus
#endif
#define gdMaxColors
#define gdAlphaMax
#define gdAlphaOpaque
#define gdAlphaTransparent
#define gdRedMax
#define gdGreenMax
#define gdBlueMax
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetAlpha(c) (((c) & 0x7F000000) >> 24)
#define gdTrueColorGetAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetRed(c) (((c) & 0xFF0000) >> 16)
#define gdTrueColorGetRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetGreen(c) (((c) & 0x00FF00) >> 8)
#define gdTrueColorGetGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorGetBlue(c) ((c) & 0x0000FF)
#define gdTrueColorGetBlue
#define gdEffectReplace
#define gdEffectAlphaBlend
#define gdEffectNormal
#define gdEffectOverlay
#define GD_TRUE
#define GD_FALSE
#define GD_EPSILON
#define M_PI
#define gdDashSize
#define gdStyled
#define gdBrushed
#define gdStyledBrushed
#define gdTiled
#define gdTransparent
#define gdAntiAliased
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdImageCreatePalette gdImageCreate
#define gdImageCreatePalette
#define gdFTEX_LINESPACE
#define gdFTEX_CHARMAP
#define gdFTEX_RESOLUTION
#define gdFTEX_DISABLE_KERNING
#define gdFTEX_XSHOW
#define gdFTEX_FONTPATHNAME
#define gdFTEX_FONTCONFIG
#define gdFTEX_RETURNFONTPATHNAME
#define gdFTEX_Unicode
#define gdFTEX_Shift_JIS
#define gdFTEX_Big5
#define gdFTEX_Adobe_Custom
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColor(r, g, b) (((r) << 16) + ((g) << 8) + (b))
#define gdTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTrueColorAlpha(r, g, b, a) (((a) << 24) + ((r) << 16) + ((g) << 8) + (b))
#define gdTrueColorAlpha
#define gdArc
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gdPie gdArc
#define gdPie
#define gdChord
#define gdNoFill
#define gdEdged
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColor(im) ((im)->trueColor)
#define gdImageTrueColor
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSX(im) ((im)->sx)
#define gdImageSX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageSY(im) ((im)->sy)
#define gdImageSY
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageColorsTotal(im) ((im)->colorsTotal)
#define gdImageColorsTotal
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageRed(im, c) ((im)->trueColor ? (((c) & 0xFF0000) >> 16) : (im)->red[(c)])
#define gdImageRed
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGreen(im, c) ((im)->trueColor ? (((c) & 0x00FF00) >> 8) : (im)->green[(c)])
#define gdImageGreen
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageBlue(im, c) ((im)->trueColor ? ((c) & 0x0000FF) : (im)->blue[(c)])
#define gdImageBlue
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageAlpha(im, c) ((im)->trueColor ? (((c) & 0x7F000000) >> 24) : (im)->alpha[(c)])
#define gdImageAlpha
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetTransparent(im) ((im)->transparent)
#define gdImageGetTransparent
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageGetInterlaced(im) ((im)->interlace)
#define gdImageGetInterlaced
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImagePalettePixel(im, x, y) (im)->pixels[(y)][(x)]
#define gdImagePalettePixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageTrueColorPixel(im, x, y) (im)->tpixels[(y)][(x)]
#define gdImageTrueColorPixel
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionX(im) (im)->res_x
#define gdImageResolutionX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdImageResolutionY(im) (im)->res_y
#define gdImageResolutionY
#define GD2_CHUNKSIZE
#define GD2_CHUNKSIZE_MIN
#define GD2_CHUNKSIZE_MAX
#define GD2_VERS
#define GD2_ID
#define GD2_FMT_RAW
#define GD2_FMT_COMPRESSED
#define GD_FLIP_HORINZONTAL
#define GD_FLIP_VERTICAL
#define GD_FLIP_BOTH
#define GD_CMP_IMAGE
#define GD_CMP_NUM_COLORS
#define GD_CMP_COLOR
#define GD_CMP_SIZE_X
#define GD_CMP_SIZE_Y
#define GD_CMP_TRANSPARENT
#define GD_CMP_BACKGROUND
#define GD_CMP_INTERLACE
#define GD_CMP_TRUECOLOR
#define GD_RESOLUTION
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDFX_H
#if __cplusplus
#endif
#if __cplusplus
#endif
#if __cplusplus
#endif
#define GDHELPERS_H
#if ! _WIN32_WCE
#else
#endif
#if _WIN32
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexDeclare(x) CRITICAL_SECTION x
#define gdMutexDeclare
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexSetup(x) InitializeCriticalSection(&x)
#define gdMutexSetup
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexShutdown(x) DeleteCriticalSection(&x)
#define gdMutexShutdown
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexLock(x) EnterCriticalSection(&x)
#define gdMutexLock
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexUnlock(x) LeaveCriticalSection(&x)
#define gdMutexUnlock
#elif HAVE_PTHREAD
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexDeclare(x) pthread_mutex_t x
#define gdMutexDeclare
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexSetup(x) pthread_mutex_init(&x, 0)
#define gdMutexSetup
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexShutdown(x) pthread_mutex_destroy(&x)
#define gdMutexShutdown
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexLock(x) pthread_mutex_lock(&x)
#define gdMutexLock
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexUnlock(x) pthread_mutex_unlock(&x)
#define gdMutexUnlock
#else
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexDeclare(x)
#define gdMutexDeclare
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexSetup(x)
#define gdMutexSetup
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexShutdown(x)
#define gdMutexShutdown
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexLock(x)
#define gdMutexLock
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdMutexUnlock(x)
#define gdMutexUnlock
#endif
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define DPCM2DPI(dpcm) (unsigned int)((dpcm)*2.54 + 0.5)
#define DPCM2DPI
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define DPM2DPI(dpm) (unsigned int)((dpm)*0.0254 + 0.5)
#define DPM2DPI
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define DPI2DPCM(dpi) (unsigned int)((dpi)/2.54 + 0.5)
#define DPI2DPCM
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define DPI2DPM(dpi) (unsigned int)((dpi)/0.0254 + 0.5)
#define DPI2DPM
#if __cplusplus
#endif
#define GDTEST_TOP_DIR
#define GDTEST_STRING_MAX
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsToFile(ex,ac) gd.gdTestImageCompareToFile(__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEqualsToFile
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageFileEqualsMsg(ex,ac) gd.gdTestImageCompareFiles(__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageFileEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEquals(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,NULL,(ex),(ac))
#define gdAssertImageEquals
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdAssertImageEqualsMsg(tc,ex,ac) CuAssertImageEquals_LineMsg((tc),__FILE__,__LINE__,(ms),(ex),(ac))
#define gdAssertImageEqualsMsg
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestAssert(cond) _gd.gdTestAssert(__FILE__, __LINE__, "assert failed in <%s:%i>\n", (cond))
#define gdTestAssert
//C++ TO C# CONVERTER NOTE: The following #define macro was replaced in-line:
//ORIGINAL LINE: #define gd.gdTestErrorMsg(...) _gd.gdTestErrorMsg(__FILE__, __LINE__, __VA_ARGS__)
#define gdTestErrorMsg
static int Main()
{
gdImageStruct im;
int white;
int black;
int r;
gdPoint points;
im = gd.gdImageCreate(100, 100);
if (im == null)
Environment.Exit(1);
white = gd.gdImageColorAllocate(im, 0xff, 0xff, 0xff);
black = gd.gdImageColorAllocate(im, 0, 0, 0);
gd.gdImageFilledRectangle(im, 0, 0, 99, 99, white);
//C++ TO C# CONVERTER TODO TASK: The memory management function 'calloc' has no equivalent in C#:
points = (gdPoint)calloc(3, sizeof(gdPoint));
if (points == null)
{
gd.gdImageDestroy(im);
Environment.Exit(1);
}
points[0].x = 10;
points[0].y = 10;
points[1].x = 50;
points[1].y = 70;
points[2].x = 90;
points[2].y = 30;
gd.gdImagePolygon(im, points, 3, black);
//C++ TO C# CONVERTER TODO TASK: There is no direct equivalent in C# to the following C++ macro:
r = GlobalMembersGdtest.gd.gdTestImageCompareToFile(__FILE__, __LINE__, null, (DefineConstants.GDTEST_TOP_DIR "/gdimagepolygon/gdimagepolygon3.png"), (im));
//C++ TO C# CONVERTER TODO TASK: The memory management function 'free' has no equivalent in C#:
free(points);
gd.gdImageDestroy(im);
if (r == 0)
Environment.Exit(1);
return EXIT_SUCCESS;
}
}
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.EventSystems;
/// Draws a circular reticle in front of any object that the user points at.
/// The circle dilates if the object is clickable.
public class GvrReticlePointer : GvrBasePointer {
// The constants below are expsed for testing.
// Minimum inner angle of the reticle (in degrees).
public const float RETICLE_MIN_INNER_ANGLE = 0.0f;
// Minimum outer angle of the reticle (in degrees).
public const float RETICLE_MIN_OUTER_ANGLE = 0.5f;
// Angle at which to expand the reticle when intersecting with an object
// (in degrees).
public const float RETICLE_GROWTH_ANGLE = 1.5f;
// Minimum distance of the reticle (in meters).
public float RETICLE_DISTANCE_MIN = 0.45f;
// Maximum distance of the reticle (in meters).
public float RETICLE_DISTANCE_MAX = 10.0f;
/// Number of segments making the reticle circle.
public int reticleSegments = 20;
/// Growth speed multiplier for the reticle/
public float reticleGrowthSpeed = 8.0f;
/// Sorting order to use for the reticle's renderer.
/// Range values come from https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html.
/// Default value 32767 ensures gaze reticle is always rendered on top.
[Range(-32767, 32767)]
public int reticleSortingOrder = 32767;
public Material MaterialComp { private get; set; }
// Current inner angle of the reticle (in degrees).
// Exposed for testing.
public float ReticleInnerAngle { get; private set; }
// Current outer angle of the reticle (in degrees).
// Exposed for testing.
public float ReticleOuterAngle { get; private set; }
// Current distance of the reticle (in meters).
// Getter exposed for testing.
public float ReticleDistanceInMeters { get; private set; }
// Current inner and outer diameters of the reticle, before distance multiplication.
// Getters exposed for testing.
public float ReticleInnerDiameter { get; private set; }
public float ReticleOuterDiameter { get; private set; }
public override float MaxPointerDistance { get { return RETICLE_DISTANCE_MAX; } }
public override void OnPointerEnter(RaycastResult raycastResultResult, bool isInteractive) {
SetPointerTarget(raycastResultResult.worldPosition, isInteractive);
}
public override void OnPointerHover(RaycastResult raycastResultResult, bool isInteractive) {
SetPointerTarget(raycastResultResult.worldPosition, isInteractive);
}
public override void OnPointerExit(GameObject previousObject) {
ReticleDistanceInMeters = RETICLE_DISTANCE_MAX;
ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE;
ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE;
}
public override void OnPointerClickDown() {}
public override void OnPointerClickUp() {}
public override void GetPointerRadius(out float enterRadius, out float exitRadius) {
float min_inner_angle_radians = Mathf.Deg2Rad * RETICLE_MIN_INNER_ANGLE;
float max_inner_angle_radians = Mathf.Deg2Rad * (RETICLE_MIN_INNER_ANGLE + RETICLE_GROWTH_ANGLE);
enterRadius = 2.0f * Mathf.Tan(min_inner_angle_radians);
exitRadius = 2.0f * Mathf.Tan(max_inner_angle_radians);
}
public void UpdateDiameters() {
ReticleDistanceInMeters =
Mathf.Clamp(ReticleDistanceInMeters, RETICLE_DISTANCE_MIN, RETICLE_DISTANCE_MAX);
if (ReticleInnerAngle < RETICLE_MIN_INNER_ANGLE) {
ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE;
}
if (ReticleOuterAngle < RETICLE_MIN_OUTER_ANGLE) {
ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE;
}
float inner_half_angle_radians = Mathf.Deg2Rad * ReticleInnerAngle * 0.5f;
float outer_half_angle_radians = Mathf.Deg2Rad * ReticleOuterAngle * 0.5f;
float inner_diameter = 2.0f * Mathf.Tan(inner_half_angle_radians);
float outer_diameter = 2.0f * Mathf.Tan(outer_half_angle_radians);
ReticleInnerDiameter =
Mathf.Lerp(ReticleInnerDiameter, inner_diameter, Time.deltaTime * reticleGrowthSpeed);
ReticleOuterDiameter =
Mathf.Lerp(ReticleOuterDiameter, outer_diameter, Time.deltaTime * reticleGrowthSpeed);
MaterialComp.SetFloat("_InnerDiameter", ReticleInnerDiameter * ReticleDistanceInMeters);
MaterialComp.SetFloat("_OuterDiameter", ReticleOuterDiameter * ReticleDistanceInMeters);
MaterialComp.SetFloat("_DistanceInMeters", ReticleDistanceInMeters);
}
void Awake() {
ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE;
ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE;
}
protected override void Start() {
base.Start();
Renderer rendererComponent = GetComponent<Renderer>();
rendererComponent.sortingOrder = reticleSortingOrder;
MaterialComp = rendererComponent.material;
CreateReticleVertices();
}
void Update() {
UpdateDiameters();
}
private bool SetPointerTarget(Vector3 target, bool interactive) {
if (base.PointerTransform == null) {
Debug.LogWarning("Cannot operate on a null pointer transform");
return false;
}
Vector3 targetLocalPosition = base.PointerTransform.InverseTransformPoint(target);
ReticleDistanceInMeters =
Mathf.Clamp(targetLocalPosition.z, RETICLE_DISTANCE_MIN, RETICLE_DISTANCE_MAX);
if (interactive) {
ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE + RETICLE_GROWTH_ANGLE;
ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE + RETICLE_GROWTH_ANGLE;
} else {
ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE;
ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE;
}
return true;
}
private void CreateReticleVertices() {
Mesh mesh = new Mesh();
gameObject.AddComponent<MeshFilter>();
GetComponent<MeshFilter>().mesh = mesh;
int segments_count = reticleSegments;
int vertex_count = (segments_count+1)*2;
#region Vertices
Vector3[] vertices = new Vector3[vertex_count];
const float kTwoPi = Mathf.PI * 2.0f;
int vi = 0;
for (int si = 0; si <= segments_count; ++si) {
// Add two vertices for every circle segment: one at the beginning of the
// prism, and one at the end of the prism.
float angle = (float)si / (float)(segments_count) * kTwoPi;
float x = Mathf.Sin(angle);
float y = Mathf.Cos(angle);
vertices[vi++] = new Vector3(x, y, 0.0f); // Outer vertex.
vertices[vi++] = new Vector3(x, y, 1.0f); // Inner vertex.
}
#endregion
#region Triangles
int indices_count = (segments_count+1)*3*2;
int[] indices = new int[indices_count];
int vert = 0;
int idx = 0;
for (int si = 0; si < segments_count; ++si) {
indices[idx++] = vert+1;
indices[idx++] = vert;
indices[idx++] = vert+2;
indices[idx++] = vert+1;
indices[idx++] = vert+2;
indices[idx++] = vert+3;
vert += 2;
}
#endregion
mesh.vertices = vertices;
mesh.triangles = indices;
mesh.RecalculateBounds();
#if !UNITY_5_5_OR_NEWER
// Optimize() is deprecated as of Unity 5.5.0p1.
mesh.Optimize();
#endif // !UNITY_5_5_OR_NEWER
}
}
| |
//
// Mono.Unix/UnixPath.cs
//
// Authors:
// Jonathan Pryor (jonpryor@vt.edu)
//
// (C) 2004 Jonathan Pryor
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Text;
using Mono.Unix;
namespace Mono.Unix {
public sealed class UnixPath
{
private UnixPath () {}
public static readonly char DirectorySeparatorChar = '/';
public static readonly char AltDirectorySeparatorChar = '/';
public static readonly char[] InvalidPathChars = new char[]{'\0'};
public static readonly char PathSeparator = ':';
public static readonly char VolumeSeparatorChar = '/';
public static string Combine (string path1, params string[] paths)
{
if (path1 == null)
throw new ArgumentNullException ("path1");
if (paths == null)
throw new ArgumentNullException ("paths");
if (path1.IndexOfAny (InvalidPathChars) != -1)
throw new ArgumentException ("Illegal characters in path", "path1");
int len = path1.Length + 1;
for (int i = 0; i < paths.Length; ++i) {
if (paths [i] == null)
throw new ArgumentNullException ("paths");
len += paths [i].Length + 1;
}
StringBuilder sb = new StringBuilder (len);
sb.Append (path1);
for (int i = 0; i < paths.Length; ++i)
Combine (sb, paths [i]);
return sb.ToString ();
}
private static void Combine (StringBuilder path, string part)
{
if (part.IndexOfAny (InvalidPathChars) != -1)
throw new ArgumentException ("Illegal characters in path", "path1");
char end = path [path.Length-1];
if (end != DirectorySeparatorChar &&
end != AltDirectorySeparatorChar &&
end != VolumeSeparatorChar)
path.Append (DirectorySeparatorChar);
path.Append (part);
}
public static string GetDirectoryName (string path)
{
CheckPath (path);
int lastDir = path.LastIndexOf (DirectorySeparatorChar);
if (lastDir > 0)
return path.Substring (0, lastDir);
return "";
}
public static string GetFileName (string path)
{
if (path == null || path.Length == 0)
return path;
int lastDir = path.LastIndexOf (DirectorySeparatorChar);
if (lastDir >= 0)
return path.Substring (lastDir+1);
return path;
}
public static string GetFullPath (string path)
{
path = _GetFullPath (path);
return GetCanonicalPath (path);
}
private static string _GetFullPath (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
if (!IsPathRooted (path))
path = UnixDirectory.GetCurrentDirectory() + DirectorySeparatorChar + path;
return path;
}
public static string GetCanonicalPath (string path)
{
string [] dirs;
int lastIndex;
GetPathComponents (path, out dirs, out lastIndex);
string end = string.Join ("/", dirs, 0, lastIndex);
return IsPathRooted (path) ? "/" + end : end;
}
private static void GetPathComponents (string path,
out string[] components, out int lastIndex)
{
string [] dirs = path.Split (DirectorySeparatorChar);
int target = 0;
for (int i = 0; i < dirs.Length; ++i) {
if (dirs [i] == "." || dirs [i] == string.Empty) continue;
else if (dirs [i] == "..") {
if (target != 0) --target;
else ++target;
}
else
dirs [target++] = dirs [i];
}
components = dirs;
lastIndex = target;
}
public static string GetPathRoot (string path)
{
if (path == null)
return null;
if (!IsPathRooted (path))
return "";
return "/";
}
public static string GetCompleteRealPath (string path)
{
if (path == null)
throw new ArgumentNullException ("path");
string [] dirs;
int lastIndex;
GetPathComponents (path, out dirs, out lastIndex);
StringBuilder realPath = new StringBuilder ();
if (dirs.Length > 0) {
string dir = IsPathRooted (path) ? "/" : "";
dir += dirs [0];
realPath.Append (GetRealPath (dir));
}
for (int i = 1; i < lastIndex; ++i) {
realPath.Append ("/").Append (dirs [i]);
string p = GetRealPath (realPath.ToString());
realPath.Remove (0, realPath.Length);
realPath.Append (p);
}
return realPath.ToString ();
}
public static string GetRealPath (string path)
{
do {
string name = ReadSymbolicLink (path);
if (name == null)
return path;
if (IsPathRooted (name))
path = name;
else {
path = GetDirectoryName (path) + DirectorySeparatorChar + name;
path = GetCanonicalPath (path);
}
} while (true);
}
// Read the specified symbolic link. If the file isn't a symbolic link,
// return null; otherwise, return the contents of the symbolic link.
//
// readlink(2) is horribly evil, as there is no way to query how big the
// symlink contents are. Consequently, it's trial and error...
internal static string ReadSymbolicLink (string path)
{
StringBuilder buf = new StringBuilder (256);
do {
int r = Syscall.readlink (path, buf);
if (r < 0) {
Error e;
switch (e = Syscall.GetLastError()) {
case Error.EINVAL:
// path isn't a symbolic link
return null;
default:
UnixMarshal.ThrowExceptionForError (e);
break;
}
}
else if (r == buf.Capacity) {
buf.Capacity *= 2;
}
else
return buf.ToString (0, r);
} while (true);
}
public static bool IsPathRooted (string path)
{
if (path == null || path.Length == 0)
return false;
return path [0] == DirectorySeparatorChar;
}
internal static void CheckPath (string path)
{
if (path == null)
throw new ArgumentNullException ();
if (path.IndexOfAny (UnixPath.InvalidPathChars) != -1)
throw new ArgumentException ("Invalid characters in path.");
}
}
}
// vim: noexpandtab
| |
// 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.Globalization;
using System.IO;
using System.Xml;
namespace System.Configuration
{
// A utility class for writing XML to a TextWriter.
//
// When this class is used to copy an XML document that may include a "<!DOCTYPE" directive,
// we must track what is written until the "<!DOCTYPE" or first document element is found.
// This is needed because the XML reader does not give us accurate spacing information
// for the beginning of the "<!DOCTYPE" element.
//
// Note that tracking this information is expensive, as it requires a scan of everything that is written
// until "<!DOCTYPE" or the first element is found.
//
// Note also that this class is used at runtime to copy sections, so performance of all
// writing functions directly affects application startup time.
internal class XmlUtilWriter
{
private const char Space = ' ';
private const string NewLine = "\r\n";
private static readonly string s_spaces8;
private static readonly string s_spaces4;
private static readonly string s_spaces2;
private readonly Stream _baseStream; // stream under TextWriter when tracking position
private object _lineStartCheckpoint; // checkpoint taken at the start of each line
static XmlUtilWriter()
{
s_spaces8 = new string(Space, 8);
s_spaces4 = new string(Space, 4);
s_spaces2 = new string(Space, 2);
}
internal XmlUtilWriter(TextWriter writer, bool trackPosition)
{
Writer = writer;
TrackPosition = trackPosition;
LineNumber = 1;
LinePosition = 1;
IsLastLineBlank = true;
if (TrackPosition)
{
_baseStream = ((StreamWriter)Writer).BaseStream;
_lineStartCheckpoint = CreateStreamCheckpoint();
}
}
internal TextWriter Writer { get; }
internal bool TrackPosition { get; }
internal int LineNumber { get; private set; }
internal int LinePosition { get; private set; }
internal bool IsLastLineBlank { get; private set; }
// Update the position after the character is written to the stream.
private void UpdatePosition(char ch)
{
switch (ch)
{
case '\r':
LineNumber++;
LinePosition = 1;
IsLastLineBlank = true;
break;
case '\n':
_lineStartCheckpoint = CreateStreamCheckpoint();
break;
case Space:
case '\t':
LinePosition++;
break;
default:
LinePosition++;
IsLastLineBlank = false;
break;
}
}
// Write a string to _writer.
// If we are tracking position, determine the line number and position
internal int Write(string s)
{
if (TrackPosition)
{
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
Writer.Write(ch);
UpdatePosition(ch);
}
}
else Writer.Write(s);
return s.Length;
}
// Write a character to _writer.
// If we are tracking position, determine the line number and position
internal int Write(char ch)
{
Writer.Write(ch);
if (TrackPosition) UpdatePosition(ch);
return 1;
}
internal void Flush()
{
Writer.Flush();
}
// Escape a text string
internal int AppendEscapeTextString(string s)
{
return AppendEscapeXmlString(s, false, 'A');
}
// Escape a XML string to preserve XML markup.
internal int AppendEscapeXmlString(string s, bool inAttribute, char quoteChar)
{
int charactersWritten = 0;
for (int i = 0; i < s.Length; i++)
{
char ch = s[i];
bool appendCharEntity = false;
string entityRef = null;
if (((ch < 32) && (ch != '\t') && (ch != '\r') && (ch != '\n')) || (ch > 0xFFFD))
appendCharEntity = true;
else
{
switch (ch)
{
case '<':
entityRef = "lt";
break;
case '>':
entityRef = "gt";
break;
case '&':
entityRef = "amp";
break;
case '\'':
if (inAttribute && (quoteChar == ch)) entityRef = "apos";
break;
case '"':
if (inAttribute && (quoteChar == ch)) entityRef = "quot";
break;
case '\n':
case '\r':
appendCharEntity = inAttribute;
break;
}
}
if (appendCharEntity) charactersWritten += AppendCharEntity(ch);
else
{
if (entityRef != null) charactersWritten += AppendEntityRef(entityRef);
else charactersWritten += Write(ch);
}
}
return charactersWritten;
}
internal int AppendEntityRef(string entityRef)
{
Write('&');
Write(entityRef);
Write(';');
return entityRef.Length + 2;
}
internal int AppendCharEntity(char ch)
{
string numberToWrite = ((int)ch).ToString("X", CultureInfo.InvariantCulture);
Write('&');
Write('#');
Write('x');
Write(numberToWrite);
Write(';');
return numberToWrite.Length + 4;
}
internal int AppendCData(string cdata)
{
Write("<![CDATA[");
Write(cdata);
Write("]]>");
return cdata.Length + 12;
}
internal int AppendProcessingInstruction(string name, string value)
{
Write("<?");
Write(name);
AppendSpace();
Write(value);
Write("?>");
return name.Length + value.Length + 5;
}
internal int AppendComment(string comment)
{
Write("<!--");
Write(comment);
Write("-->");
return comment.Length + 7;
}
internal int AppendAttributeValue(XmlTextReader reader)
{
int charactersWritten = 0;
char quote = reader.QuoteChar;
// In !DOCTYPE, quote is '\0' for second public attribute.
// Protect ourselves from writing invalid XML by always
// supplying a valid quote char.
if ((quote != '"') && (quote != '\'')) quote = '"';
charactersWritten += Write(quote);
while (reader.ReadAttributeValue())
if (reader.NodeType == XmlNodeType.Text)
charactersWritten += AppendEscapeXmlString(reader.Value, true, quote);
else charactersWritten += AppendEntityRef(reader.Name);
charactersWritten += Write(quote);
return charactersWritten;
}
// Append whitespace, ensuring there is at least one space.
internal int AppendRequiredWhiteSpace(int fromLineNumber, int fromLinePosition, int toLineNumber,
int toLinePosition)
{
int charactersWritten = AppendWhiteSpace(fromLineNumber, fromLinePosition, toLineNumber, toLinePosition);
if (charactersWritten == 0) charactersWritten += AppendSpace();
return charactersWritten;
}
internal int AppendWhiteSpace(int fromLineNumber, int fromLinePosition, int toLineNumber, int toLinePosition)
{
int charactersWritten = 0;
while (fromLineNumber++ < toLineNumber)
{
charactersWritten += AppendNewLine();
fromLinePosition = 1;
}
charactersWritten += AppendSpaces(toLinePosition - fromLinePosition);
return charactersWritten;
}
// Append indent
// linePosition - starting line position
// indent - number of spaces to indent each unit of depth
// depth - depth to indent
// newLine - insert new line before indent?
internal int AppendIndent(int linePosition, int indent, int depth, bool newLine)
{
int charactersWritten = 0;
if (newLine) charactersWritten += AppendNewLine();
int c = linePosition - 1 + indent * depth;
charactersWritten += AppendSpaces(c);
return charactersWritten;
}
// Write spaces up to the line position, taking into account the
// current line position of the writer.
internal int AppendSpacesToLinePosition(int linePosition)
{
if (linePosition <= 0) return 0;
int delta = linePosition - LinePosition;
if ((delta < 0) && IsLastLineBlank) SeekToLineStart();
return AppendSpaces(linePosition - LinePosition);
}
internal int AppendNewLine()
{
return Write(NewLine);
}
// Write spaces to the writer provided. Since we do not want waste
// memory by allocating do not use "new String(' ', count)".
internal int AppendSpaces(int count)
{
int c = count;
while (c > 0)
if (c >= 8)
{
Write(s_spaces8);
c -= 8;
}
else
{
if (c >= 4)
{
Write(s_spaces4);
c -= 4;
}
else
{
if (c >= 2)
{
Write(s_spaces2);
c -= 2;
}
else
{
Write(Space);
break;
}
}
}
return count > 0 ? count : 0;
}
internal int AppendSpace()
{
return Write(Space);
}
// Reset the stream to the beginning of the current blank line.
internal void SeekToLineStart()
{
RestoreStreamCheckpoint(_lineStartCheckpoint);
}
// Create a checkpoint that can be restored with RestoreStreamCheckpoint().
internal object CreateStreamCheckpoint()
{
return new StreamWriterCheckpoint(this);
}
// Restore the writer state that was recorded with CreateStreamCheckpoint().
internal void RestoreStreamCheckpoint(object o)
{
StreamWriterCheckpoint checkpoint = (StreamWriterCheckpoint)o;
Flush();
LineNumber = checkpoint._lineNumber;
LinePosition = checkpoint._linePosition;
IsLastLineBlank = checkpoint._isLastLineBlank;
_baseStream.Seek(checkpoint._streamPosition, SeekOrigin.Begin);
_baseStream.SetLength(checkpoint._streamLength);
_baseStream.Flush();
}
// Class that contains the state of the writer and its underlying stream.
private class StreamWriterCheckpoint
{
internal readonly bool _isLastLineBlank;
internal readonly int _lineNumber;
internal readonly int _linePosition;
internal readonly long _streamLength;
internal readonly long _streamPosition;
internal StreamWriterCheckpoint(XmlUtilWriter writer)
{
writer.Flush();
_lineNumber = writer.LineNumber;
_linePosition = writer.LinePosition;
_isLastLineBlank = writer.IsLastLineBlank;
writer._baseStream.Flush();
_streamPosition = writer._baseStream.Position;
_streamLength = writer._baseStream.Length;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.OpenGL.Textures;
using osu.Framework.Graphics.Textures;
using osu.Game.Configuration;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Tests.Visual.Background
{
public class TestSceneSeasonalBackgroundLoader : ScreenTestScene
{
[Resolved]
private OsuConfigManager config { get; set; }
[Resolved]
private SessionStatics statics { get; set; }
[Cached(typeof(LargeTextureStore))]
private LookupLoggingTextureStore textureStore = new LookupLoggingTextureStore();
private DummyAPIAccess dummyAPI => (DummyAPIAccess)API;
private SeasonalBackgroundLoader backgroundLoader;
private Container backgroundContainer;
// in real usages these would be online URLs, but correct execution of this test
// shouldn't be coupled to existence of online assets.
private static readonly List<string> seasonal_background_urls = new List<string>
{
"Backgrounds/bg2",
"Backgrounds/bg4",
"Backgrounds/bg3"
};
[BackgroundDependencyLoader]
private void load(LargeTextureStore wrappedStore)
{
textureStore.AddStore(wrappedStore);
Add(backgroundContainer = new Container
{
RelativeSizeAxes = Axes.Both
});
}
[SetUp]
public void SetUp() => Schedule(() =>
{
// reset API response in statics to avoid test crosstalk.
statics.SetValue<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null);
textureStore.PerformedLookups.Clear();
dummyAPI.SetState(APIState.Online);
backgroundContainer.Clear();
});
[TestCase(-5)]
[TestCase(5)]
public void TestAlwaysSeasonal(int daysOffset)
{
registerBackgroundsResponse(DateTimeOffset.Now.AddDays(daysOffset));
setSeasonalBackgroundMode(SeasonalBackgroundMode.Always);
createLoader();
for (int i = 0; i < 4; ++i)
loadNextBackground();
AddAssert("all backgrounds cycled", () => new HashSet<string>(textureStore.PerformedLookups).SetEquals(seasonal_background_urls));
}
[TestCase(-5)]
[TestCase(5)]
public void TestNeverSeasonal(int daysOffset)
{
registerBackgroundsResponse(DateTimeOffset.Now.AddDays(daysOffset));
setSeasonalBackgroundMode(SeasonalBackgroundMode.Never);
createLoader();
assertNoBackgrounds();
}
[Test]
public void TestSometimesInSeason()
{
registerBackgroundsResponse(DateTimeOffset.Now.AddDays(5));
setSeasonalBackgroundMode(SeasonalBackgroundMode.Sometimes);
createLoader();
assertAnyBackground();
}
[Test]
public void TestSometimesOutOfSeason()
{
registerBackgroundsResponse(DateTimeOffset.Now.AddDays(-10));
setSeasonalBackgroundMode(SeasonalBackgroundMode.Sometimes);
createLoader();
assertNoBackgrounds();
}
[Test]
public void TestDelayedConnectivity()
{
registerBackgroundsResponse(DateTimeOffset.Now.AddDays(30));
setSeasonalBackgroundMode(SeasonalBackgroundMode.Always);
AddStep("go offline", () => dummyAPI.SetState(APIState.Offline));
createLoader();
assertNoBackgrounds();
AddStep("go online", () => dummyAPI.SetState(APIState.Online));
assertAnyBackground();
}
private void registerBackgroundsResponse(DateTimeOffset endDate)
=> AddStep("setup request handler", () =>
{
dummyAPI.HandleRequest = request =>
{
if (dummyAPI.State.Value != APIState.Online || !(request is GetSeasonalBackgroundsRequest backgroundsRequest))
return false;
backgroundsRequest.TriggerSuccess(new APISeasonalBackgrounds
{
Backgrounds = seasonal_background_urls.Select(url => new APISeasonalBackground { Url = url }).ToList(),
EndDate = endDate
});
return true;
};
});
private void setSeasonalBackgroundMode(SeasonalBackgroundMode mode)
=> AddStep($"set seasonal mode to {mode}", () => config.SetValue(OsuSetting.SeasonalBackgroundMode, mode));
private void createLoader()
=> AddStep("create loader", () =>
{
if (backgroundLoader != null)
Remove(backgroundLoader);
Add(backgroundLoader = new SeasonalBackgroundLoader());
});
private void loadNextBackground()
{
SeasonalBackground previousBackground = null;
SeasonalBackground background = null;
AddStep("create next background", () =>
{
previousBackground = (SeasonalBackground)backgroundContainer.SingleOrDefault();
background = backgroundLoader.LoadNextBackground();
LoadComponentAsync(background, bg => backgroundContainer.Child = bg);
});
AddUntilStep("background loaded", () => background.IsLoaded);
AddAssert("background is different", () => !background.Equals(previousBackground));
}
private void assertAnyBackground()
{
loadNextBackground();
AddAssert("background looked up", () => textureStore.PerformedLookups.Any());
}
private void assertNoBackgrounds()
{
AddAssert("no background available", () => backgroundLoader.LoadNextBackground() == null);
AddAssert("no lookups performed", () => !textureStore.PerformedLookups.Any());
}
private class LookupLoggingTextureStore : LargeTextureStore
{
public List<string> PerformedLookups { get; } = new List<string>();
public override Texture Get(string name, WrapMode wrapModeS, WrapMode wrapModeT)
{
PerformedLookups.Add(name);
return base.Get(name, wrapModeS, wrapModeT);
}
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using log4net;
using MindTouch.Deki.Script;
using MindTouch.Deki.Script.Expr;
using MindTouch.Deki.Script.Runtime.Library;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Deki.Services.Extension {
using Yield = IEnumerator<IYield>;
[DreamService("MindTouch Web Cache Extension", "Copyright (c) 2010 MindTouch Inc.",
Info = "http://developer.mindtouch.com/App_Catalog/WebCache",
SID = new string[] { "sid://mindtouch.com/2009/02/extension/webcache" }
)]
[DreamServiceConfig("max-size", "long?", "Maximum file size (in bytes) to cache (default: 512KB)")]
[DreamServiceConfig("memory-cache-time", "double?", "Seconds to keep cache in memory (in addition to disk) after access (default: 60)")]
[DreamServiceBlueprint("deki/service-type", "extension")]
[DekiExtLibrary(
Label = "Web Cache",
Namespace = "webcache",
Description = "This extension contains functions caching documents fetched from the web using a disk-backed store."
)]
public class WebCacheService : DekiExtService {
//--- Constants ---
private const double DEFAULT_MEMORY_CACHE_TIME = 60;
private const double DEFAULT_CACHE_TTL = 5 * 60;
private const long DEFAULT_TEXT_LIMIT = 512 * 1024;
private const string CACHE_DATA = "cache-data";
private const string CACHE_INFO = "cache-info";
private static readonly TimeSpan DEFAULT_WEB_TIMEOUT = TimeSpan.FromSeconds(60);
private static double _memoryCacheTime;
// NOTE (steveb): XSS vulnerability check: detect 'expressions', 'url(' and 'http(s)://' links in style attributes
private static readonly Regex STYLE_XSS_CHECK = new Regex(@"(?:expression|tps*://|url\s*\().*", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Compiled);
//--- Types ---
public class CacheEntry {
//--- Fields ---
public readonly string Id;
public readonly Guid Guid;
public string Cache;
public readonly DateTime Expires;
private readonly TaskTimer _memoryExpire;
//--- Constructors ---
public CacheEntry(string id, double? ttl) : this() {
Id = id;
Guid = Guid.NewGuid();
Expires = DateTime.UtcNow.Add(TimeSpan.FromSeconds(ttl ?? DEFAULT_CACHE_TTL));
ResetMemoryExpiration();
}
public CacheEntry(string id, Guid guid, DateTime expires) : this() {
Id = id;
Guid = guid;
Expires = expires;
}
private CacheEntry() {
_memoryExpire = new TaskTimer(delegate(TaskTimer tt) {
_log.DebugFormat("flushing memory cache for '{0}'", Id);
Cache = null;
}, null);
}
//--- Methods ---
public void ResetMemoryExpiration() {
_memoryExpire.Change(TimeSpan.FromSeconds(_memoryCacheTime), TaskEnv.Clone());
}
}
//--- Class Fields ---
private new static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly Dictionary<string, CacheEntry> _cacheLookup = new Dictionary<string, CacheEntry>(StringComparer.OrdinalIgnoreCase);
private Sgml.SgmlDtd _htmlEntitiesDtd;
private long _insertTextLimit;
//--- Functions ---
[DekiExtFunction("clear", "Remove a uri from the cache")]
public object Clear(
[DekiExtParam("source uri")] string source
) {
lock(_cacheLookup) {
CacheEntry entry;
if(!_cacheLookup.TryGetValue(source, out entry)) {
return null;
}
_log.DebugFormat("Removed from cache: '{0}'", source);
_cacheLookup.Remove(source);
DeleteCacheEntry(entry.Guid);
}
return null;
}
[DekiExtFunction("text", "Get a text value from a web-service.")]
public string WebText(
[DekiExtParam("source text or source uri (default: none)", true)] string source,
[DekiExtParam("xpath to value (default: none)", true)] string xpath,
[DekiExtParam("namespaces (default: none)", true)] Hashtable namespaces,
[DekiExtParam("capture enclosing XML element (default: false)", true)] bool? xml,
[DekiExtParam("caching duration in seconds (range: 300+; default: 300)", true)] double? ttl
) {
// NOTE (steveb): the following cases need to be covered
// * source is a string and no xpath given -> return source as is
// * source is a string and xpath given -> convert source to an XML document and apply xpath
// * source is a uri pointing to text document and xpath given -> fetch source and convert to string (ignore xpath)
// * source is a uri pointing to xml document and xpath given -> fetch source, convert to XML document, and apply xpath
// * source is a uri pointing to text document and no xpath given -> fetch source and convert to string
// * source is a uri pointing to xml document and no xpath given -> fetch source and convert to string
source = source ?? string.Empty;
XUri uri = XUri.TryParse(source);
if(uri == null) {
if(xpath == null) {
// source is a string and no xpath given -> return source as is
return source;
} else {
// source is a string and xpath given -> convert sourcwe to an XML document and apply xpath
XDoc doc = XDocFactory.From(source, MimeType.XML);
if((doc == null) || doc.IsEmpty) {
return "(source is not an xml document)";
}
return AtXPath(doc, xpath, namespaces, xml ?? false);
}
} else {
// we need to fetch an online document
string response = CachedWebGet(uri, ttl);
if(xpath == null) {
// source is a uri pointing to text document and no xpath given -> fetch source and convert to string
// source is a uri pointing to xml document and no xpath given -> fetch source and convert to string
return response;
} else {
XDoc doc = XDocFactory.From(response, MimeType.XML);
if(doc.IsEmpty) {
doc = XDocFactory.From(response, MimeType.HTML);
}
if(doc.IsEmpty) {
// * source is a uri pointing to text document and xpath given -> fetch source and convert to string (ignore xpath)
return response;
}
// * source is a uri pointing to xml document and xpath given -> fetch source, convert to XML document, and apply xpath
return AtXPath(doc, xpath, namespaces, xml ?? false);
}
}
}
[DekiExtFunction("html", "Convert text to HTML. The text value can optionally be retrieved from a web-service.")]
public XDoc WebHtml(
[DekiExtParam("HTML source text or source uri (default: none)", true)] string source,
[DekiExtParam("xpath to value (default: none)", true)] string xpath,
[DekiExtParam("namespaces (default: none)", true)] Hashtable namespaces,
[DekiExtParam("caching duration in seconds (range: 300+; default: 300)", true)] double? ttl
) {
string text = WebText(source, xpath, namespaces, true, ttl);
// convert text to html
XDoc result = XDoc.Empty;
using(TextReader reader = new StringReader("<html><body>" + text + "</body></html>")) {
// NOTE (steveb): we create the sgml reader explicitly since we don't want a DTD to be associated with it; the DTD would force a potentially unwanted HTML structure
// check if HTML entities DTD has already been loaded
if(_htmlEntitiesDtd == null) {
using(StreamReader dtdReader = new StreamReader(Plug.New("resource://mindtouch.deki.script/MindTouch.Deki.Script.HtmlEntities.dtd").Get().AsStream())) {
_htmlEntitiesDtd = Sgml.SgmlDtd.Parse(null, "HTML", dtdReader, null, null, XDoc.XmlNameTable);
}
}
Sgml.SgmlReader sgmlReader = new Sgml.SgmlReader(XDoc.XmlNameTable);
sgmlReader.Dtd = _htmlEntitiesDtd;
sgmlReader.DocType = "HTML";
sgmlReader.WhitespaceHandling = WhitespaceHandling.All;
sgmlReader.CaseFolding = Sgml.CaseFolding.ToLower;
sgmlReader.InputStream = reader;
try {
XmlDocument doc = new XmlDocument(XDoc.XmlNameTable);
doc.PreserveWhitespace = true;
doc.XmlResolver = null;
doc.Load(sgmlReader);
// check if a valid document was created
if(doc.DocumentElement != null) {
result = new XDoc(doc);
}
} catch(Exception) {
// swallow parsing exceptions
}
}
return DekiScriptLibrary.CleanseHtmlDocument(result);
}
[DekiExtFunction("list", "Get list of values from an XML document or web-service.")]
public ArrayList WebList(
[DekiExtParam("XML source text or source uri")] string source,
[DekiExtParam("xpath to list of values")] string xpath,
[DekiExtParam("namespaces (default: none)", true)] Hashtable namespaces,
[DekiExtParam("capture enclosing XML element (default: false)", true)] bool? xml,
[DekiExtParam("caching duration in seconds (range: 300+; default: 300)", true)] double? ttl
) {
XUri uri = XUri.TryParse(source);
ArrayList result;
if(uri == null) {
// source is a string -> convert sourcwe to an XML document and apply xpath
XDoc doc = XDocFactory.From(source, MimeType.XML);
if((doc == null) || doc.IsEmpty) {
result = new ArrayList();
} else {
result = AtXPathList(doc, xpath, namespaces, xml ?? false);
}
} else {
// we need to fetch an online document
string response = CachedWebGet(uri, ttl);
XDoc doc = XDocFactory.From(response, MimeType.XML);
if(doc.IsEmpty) {
doc = XDocFactory.From(response, MimeType.HTML);
}
if(doc.IsEmpty) {
// * source is a uri pointing to text document -> fetch source and convert to string (ignore xpath)
result = new ArrayList();
result.Add(response.ToString());
} else {
// * source is a uri pointing to xml document -> fetch source, convert to XML document, and apply xpath
result = AtXPathList(doc, xpath, namespaces, xml ?? false);
}
}
return result;
}
[DekiExtFunction("xml", "Get an XML document from a web-service.")]
public XDoc WebXml(
[DekiExtParam("XML source text or source uri")] string source,
[DekiExtParam("xpath to value (default: none)", true)] string xpath,
[DekiExtParam("namespaces (default: none)300+", true)] Hashtable namespaces,
[DekiExtParam("caching duration in seconds (range: 300+; default: 300)", true)] double? ttl
) {
string text = WebText(source, xpath, namespaces, true, ttl);
XDoc result = XDocFactory.From(text, MimeType.XML);
if(result.IsEmpty) {
// try again assuming the input is HTML
result = XDocFactory.From(text, MimeType.HTML);
}
if(result.HasName("html")) {
result = DekiScriptLibrary.CleanseHtmlDocument(result);
}
return result;
}
[DekiExtFunction("json", "Get a JSON value from a web-service.")]
public object WebJson(
[DekiExtParam("source text or source uri (default: none)", true)] string source,
[DekiExtParam("caching duration in seconds (range: 300+; default: 300)", true)] double? ttl,
DekiScriptRuntime runtime
) {
source = source ?? string.Empty;
XUri uri = XUri.TryParse(source);
if(uri == null) {
return DekiScriptLibrary.JsonParse(source, runtime);
}
// we need to fetch an online document
string response = CachedWebGet(uri, ttl);
return DekiScriptLibrary.JsonParse(response, runtime);
}
[DekiExtFunction("fetch", "Fetch a document from the cache.")]
public object Fetch(
[DekiExtParam("document id")] string id
) {
// fetch response from cache
CacheEntry result;
lock(_cacheLookup) {
_cacheLookup.TryGetValue(id, out result);
}
// check if we have a cached entry
XDoc document = null;
if(result != null) {
_log.DebugFormat("cache hit for '{0}'", result.Id);
result.ResetMemoryExpiration();
if(result.Cache != null) {
_log.DebugFormat("cache data in memory '{0}'", result.Id);
document = XDocFactory.From(result.Cache, MimeType.XML);
} else {
// we have the result on disk, so let's fetch it
DreamMessage msg = Storage.At(CACHE_DATA, result.Guid + ".bin").GetAsync().Wait();
if(msg.IsSuccessful) {
_log.DebugFormat("cache data pulled from disk");
result.Cache = Encoding.UTF8.GetString(msg.AsBytes());
document = XDocFactory.From(result.Cache, MimeType.XML);
} else {
_log.DebugFormat("unable to fetch cache data from disk: {0}", msg.Status);
}
}
}
// check if we have a document to convert
if(document != null) {
try {
DekiScriptList list = (DekiScriptList)DekiScriptLiteral.FromXml(document);
return list[0];
} catch {
// the cached entry is corrupted, remove it
Clear(id);
}
}
return null;
}
[DekiExtFunction("store", "Store a document in the cache.")]
public object Store(
[DekiExtParam("document id")] string id,
[DekiExtParam("document to cache", true)] object document,
[DekiExtParam("caching duration in seconds (range: 300+; default: 300)", true)] double? ttl
) {
if(document == null) {
return Clear(id);
}
// fetch entry from cache
CacheEntry result;
bool isNew = true;
lock(_cacheLookup) {
_cacheLookup.TryGetValue(id, out result);
}
// check if we have a cached entry
if(result != null) {
_log.DebugFormat("cache hit for '{0}'", result.Id);
isNew = false;
result.ResetMemoryExpiration();
} else {
_log.DebugFormat("new cache item for '{0}'", id);
result = new CacheEntry(id, ttl);
}
// update cache with document
DekiScriptLiteral literal = DekiScriptLiteral.FromNativeValue(document);
XDoc xml = new DekiScriptList().Add(literal).ToXml();
result.Cache = xml.ToString();
// start timer to clean-up cached result
if(result.Cache != null) {
XDoc infoDoc = new XDoc("cache-entry")
.Elem("guid", result.Guid)
.Elem("id", result.Id)
.Elem("expires", result.Expires);
lock(result) {
Storage.At(CACHE_DATA, result.Guid + ".bin").PutAsync(new DreamMessage(DreamStatus.Ok, null, MimeType.BINARY, Encoding.UTF8.GetBytes(result.Cache))).Wait();
Storage.At(CACHE_INFO, result.Guid + ".xml").PutAsync(infoDoc).Wait();
}
if(isNew) {
lock(_cacheLookup) {
_cacheLookup[id] = result;
}
// this timer removes the cache entry from disk
SetupCacheTimer(result);
}
}
return document;
}
//--- Methods ---
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
// set up defaults
_insertTextLimit = config["max-size"].AsLong ?? DEFAULT_TEXT_LIMIT;
_memoryCacheTime = config["memory-cache-time"].AsDouble ?? DEFAULT_MEMORY_CACHE_TIME;
_log.DebugFormat("max-size: {0}, memory-cache-time: {1}", _insertTextLimit, _memoryCacheTime);
// load current cache state
Async.Fork(() => Coroutine.Invoke(RefreshCache, new Result(TimeSpan.MaxValue)), TaskEnv.Clone(), null);
result.Return();
}
protected override Yield Stop(Result result) {
_cacheLookup.Clear();
yield return Coroutine.Invoke(base.Stop, new Result());
result.Return();
}
private Yield RefreshCache(Result result) {
XDoc cacheCatalog = null;
yield return Storage.At(CACHE_INFO).GetAsync().Set(v => cacheCatalog = v.ToDocument());
int itemCount = 0;
foreach(XDoc file in cacheCatalog["file/name"]) {
string filename = file.AsText;
// request cach-info file
Result<DreamMessage> cacheInfo;
yield return cacheInfo = Storage.At(CACHE_INFO, filename).GetAsync();
XDoc doc = null;
Guid guid = Guid.Empty;
try {
doc = cacheInfo.Value.ToDocument();
guid = new Guid(doc["guid"].AsText);
string id = doc["id"].AsText;
// check if cache entry has already expired
DateTime expires = doc["expires"].AsDate.Value;
CacheEntry entry = new CacheEntry(id, guid, expires);
if(entry.Expires < DateTime.UtcNow) {
_log.DebugFormat("removing stale cache item '{0}' at startup", id);
DeleteCacheEntry(guid);
continue;
}
// try adding the cache-entry; this might fail if the entry has already been re-added
lock(_cacheLookup) {
_cacheLookup[id] = entry;
++itemCount;
SetupCacheTimer(entry);
}
} catch(Exception e) {
_log.Error(string.Format("Bad cacheinfo doc '{0}': {1}", filename, doc), e);
if(guid != Guid.Empty) {
DeleteCacheEntry(guid);
}
}
}
_log.DebugFormat("loaded {0} cache items", itemCount);
result.Return();
}
private string CachedWebGet(XUri uri, double? ttl) {
string id = uri.ToString();
// fetch message from cache or from the web
CacheEntry result;
bool isNew = true;
lock(_cacheLookup) {
_cacheLookup.TryGetValue(id, out result);
}
// check if we have a cached entry
if(result != null) {
_log.DebugFormat("cache hit for '{0}'", result.Id);
isNew = false;
result.ResetMemoryExpiration();
if(result.Cache != null) {
_log.DebugFormat("cache data in memory '{0}'", result.Id);
return result.Cache;
}
// we have the result on disk, so let's fetch it
DreamMessage msg = Storage.At(CACHE_DATA, result.Guid + ".bin").GetAsync().Wait();
if(msg.IsSuccessful) {
_log.DebugFormat("cache data pulled from disk");
result.Cache = Encoding.UTF8.GetString(msg.AsBytes());
return result.Cache;
}
_log.DebugFormat("unable to fetch cache data from disk: {0}", msg.Status);
} else {
_log.DebugFormat("new cache item for '{0}'", id);
result = new CacheEntry(id, ttl);
}
// do the web request
Result<DreamMessage> response = new Result<DreamMessage>();
Plug.New(uri).WithTimeout(DEFAULT_WEB_TIMEOUT).InvokeEx("GET", DreamMessage.Ok(), response);
DreamMessage message = response.Wait();
try {
// check message status
if(!message.IsSuccessful) {
return message.Status == DreamStatus.UnableToConnect
? string.Format("(unable to fetch text document from uri [status: {0} ({1}), message: \"{2}\"])", (int)message.Status, message.Status, message.ToDocument()["message"].AsText)
: string.Format("(unable to fetch text document from uri [status: {0} ({1})])", (int)message.Status, message.Status);
}
// check message size
Result resMemorize = message.Memorize(_insertTextLimit, new Result()).Block();
if(resMemorize.HasException) {
return "(text document is too large)";
}
// check if response is an XML document
result.Cache = message.AsText() ?? string.Empty;
} finally {
message.Close();
}
// start timer to clean-up cached result
if(result.Cache != null) {
XDoc infoDoc = new XDoc("cache-entry")
.Elem("guid", result.Guid)
.Elem("id", result.Id)
.Elem("expires", result.Expires);
lock(result) {
Storage.At(CACHE_DATA, result.Guid + ".bin").PutAsync(new DreamMessage(DreamStatus.Ok, null, MimeType.BINARY, Encoding.UTF8.GetBytes(result.Cache))).Wait();
Storage.At(CACHE_INFO, result.Guid + ".xml").PutAsync(infoDoc).Wait();
}
if(isNew) {
lock(_cacheLookup) {
_cacheLookup[id] = result;
}
// this timer removes the cache entry from disk
SetupCacheTimer(result);
}
}
return result.Cache;
}
private void SetupCacheTimer(CacheEntry cacheEntry) {
TaskTimer.New(cacheEntry.Expires, timer => {
var entry = (CacheEntry)timer.State;
_log.DebugFormat("removing '{0}' from cache", entry.Id);
lock(entry) {
// removing from lookup first, since a false return value on Remove indicates that we shouldn't
// try to delete the file from disk
if(_cacheLookup.Remove(entry.Id)) {
DeleteCacheEntry(entry.Guid);
}
}
}, cacheEntry, TaskEnv.None);
}
private void DeleteCacheEntry(Guid guid) {
DreamMessage msg = Storage.WithCookieJar(Cookies).At(CACHE_DATA, guid + ".bin").DeleteAsync().Wait();
if(!msg.IsSuccessful) {
_log.WarnFormat("Unable to delete cache data for {0}: {1}", guid, msg);
}
msg = Storage.WithCookieJar(Cookies).At(CACHE_INFO, guid + ".xml").DeleteAsync().Wait();
if(!msg.IsSuccessful) {
_log.WarnFormat("Unable to delete cache info for {0}: {1}", guid, msg);
}
}
private XDoc AtXPathNode(XDoc doc, string xpath, Hashtable namespaces) {
XDoc result = doc;
if(namespaces != null) {
// initialize a namespace manager
XmlNamespaceManager nsm = new XmlNamespaceManager(SysUtil.NameTable);
foreach(DictionaryEntry ns in namespaces) {
nsm.AddNamespace((string)ns.Key, SysUtil.ChangeType<string>(ns.Value));
}
result = doc.AtPath(xpath, nsm);
} else if(!StringUtil.EqualsInvariant(xpath, ".")) {
// use default namespace manager
result = doc[xpath];
}
return result;
}
private string AtXPath(XDoc doc, string xpath, Hashtable namespaces, bool asXml) {
XDoc node = AtXPathNode(doc, xpath, namespaces);
if(asXml && !node.IsEmpty) {
if(node.AsXmlNode.NodeType == XmlNodeType.Attribute) {
return ((XmlAttribute)node.AsXmlNode).OwnerElement.OuterXml;
} else {
return node.AsXmlNode.OuterXml;
}
} else {
return node.AsText;
}
}
private ArrayList AtXPathList(XDoc doc, string xpath, Hashtable namespaces, bool asXml) {
XDoc node;
if(namespaces != null) {
// initialize a namespace manager
XmlNamespaceManager nsm = new XmlNamespaceManager(SysUtil.NameTable);
foreach(DictionaryEntry ns in namespaces) {
nsm.AddNamespace((string)ns.Key, SysUtil.ChangeType<string>(ns.Value));
}
node = doc.AtPath(xpath, nsm);
} else {
// use default namespace manager
node = doc[xpath];
}
// iterate over all matches
ArrayList result = new ArrayList();
foreach(XDoc item in node) {
if(asXml) {
if(item.AsXmlNode.NodeType == XmlNodeType.Attribute) {
result.Add(((XmlAttribute)item.AsXmlNode).OwnerElement.OuterXml);
} else {
result.Add(item.AsXmlNode.OuterXml);
}
} else {
result.Add(item.AsText);
}
}
return result;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// Creates projects within the solution
/// </summary>
[CLSCompliant(false)]
public abstract class ProjectFactory : Microsoft.VisualStudio.Shell.Flavor.FlavoredProjectFactoryBase
{
#region fields
private Microsoft.VisualStudio.Shell.Package package;
private System.IServiceProvider site;
private static readonly IVsTaskSchedulerService taskSchedulerService ;
static ProjectFactory()
{
ThreadHelper.ThrowIfNotOnUIThread();
taskSchedulerService= Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SVsTaskSchedulerService)) as IVsTaskSchedulerService;
}
/// <summary>
/// The msbuild engine that we are going to use.
/// </summary>
private MSBuild.ProjectCollection buildEngine;
/// <summary>
/// The msbuild project for the project file.
/// </summary>
private MSBuild.Project buildProject;
#endregion
#region properties
protected Microsoft.VisualStudio.Shell.Package Package
{
get
{
return this.package;
}
}
protected System.IServiceProvider Site
{
get
{
return this.site;
}
}
/// <summary>
/// The msbuild engine that we are going to use.
/// </summary>
protected MSBuild.ProjectCollection BuildEngine
{
get
{
return this.buildEngine;
}
}
/// <summary>
/// The msbuild project for the temporary project file.
/// </summary>
protected MSBuild.Project BuildProject
{
get
{
return this.buildProject;
}
set
{
this.buildProject = value;
}
}
#endregion
#region ctor
protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package)
{
this.package = package;
this.site = package;
// Please be aware that this methods needs that ServiceProvider is valid, thus the ordering of calls in the ctor matters.
this.buildEngine = Utilities.InitializeMsBuildEngine(this.buildEngine, this.site);
}
#endregion
#region abstract methods
protected abstract ProjectNode CreateProject();
#endregion
#region overriden methods
/// <summary>
/// Rather than directly creating the project, ask VS to initate the process of
/// creating an aggregated project in case we are flavored. We will be called
/// on the IVsAggregatableProjectFactory to do the real project creation.
/// </summary>
/// <param name="fileName">Project file</param>
/// <param name="location">Path of the project</param>
/// <param name="name">Project Name</param>
/// <param name="flags">Creation flags</param>
/// <param name="projectGuid">Guid of the project</param>
/// <param name="project">Project that end up being created by this method</param>
/// <param name="canceled">Was the project creation canceled</param>
protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled)
{
project = IntPtr.Zero;
canceled = 0;
// Get the list of GUIDs from the project/template
string guidsList = this.ProjectTypeGuids(fileName);
ThreadHelper.ThrowIfNotOnUIThread();
// Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation)
IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject));
Assumes.Present(aggregateProjectFactory);
int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project);
if(hr == VSConstants.E_ABORT)
canceled = 1;
ErrorHandler.ThrowOnFailure(hr);
// This needs to be done after the aggregation is completed (to avoid creating a non-aggregated CCW) and as a result we have to go through the interface
IProjectEventsProvider eventsProvider = (IProjectEventsProvider)Marshal.GetTypedObjectForIUnknown(project, typeof(IProjectEventsProvider));
eventsProvider.ProjectEventsProvider = this.GetProjectEventsProvider();
this.buildProject = null;
}
/// <summary>
/// Instantiate the project class, but do not proceed with the
/// initialization just yet.
/// Delegate to CreateProject implemented by the derived class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification="The global property handles is instantiated here and used in the project node that will Dispose it")]
protected override object PreCreateForOuter(IntPtr outerProjectIUnknown)
{
Utilities.CheckNotNull(this.buildProject, "The build project should have been initialized before calling PreCreateForOuter.");
// Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node.
// The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail
// Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method.
ProjectNode node = this.CreateProject();
Utilities.CheckNotNull(node, "The project failed to be created");
node.BuildEngine = this.buildEngine;
node.BuildProject = this.buildProject;
node.Package = this.package as AsyncProjectPackage;
node.InitializeGlobals();
return node;
}
/// <summary>
/// Retrives the list of project guids from the project file.
/// If you don't want your project to be flavorable, override
/// to only return your project factory Guid:
/// return this.GetType().GUID.ToString("B");
/// </summary>
/// <param name="file">Project file to look into to find the Guid list</param>
/// <returns>List of semi-colon separated GUIDs</returns>
protected override string ProjectTypeGuids(string file)
{
// Load the project so we can extract the list of GUIDs
this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject);
// Retrieve the list of GUIDs, if it is not specify, make it our GUID
string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids);
if(String.IsNullOrEmpty(guids))
guids = this.GetType().GUID.ToString("B");
return guids;
}
#endregion
#region helpers
private IProjectEvents GetProjectEventsProvider()
{
AsyncProjectPackage projectPackage = this.package as AsyncProjectPackage;
Debug.Assert(projectPackage != null, "Package not inherited from framework");
if(projectPackage != null)
{
foreach(SolutionListener listener in projectPackage.SolutionListeners)
{
IProjectEvents projectEvents = listener as IProjectEvents;
if(projectEvents != null)
{
return projectEvents;
}
}
}
return null;
}
#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.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using Amazon.CloudFront.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.CloudFront.Model.Internal.MarshallTransformations
{
/// <summary>
/// Create Streaming Distribution Request Marshaller
/// </summary>
public class CreateStreamingDistributionRequestMarshaller : IMarshaller<IRequest, CreateStreamingDistributionRequest>
{
public IRequest Marshall(CreateStreamingDistributionRequest createStreamingDistributionRequest)
{
IRequest request = new DefaultRequest(createStreamingDistributionRequest, "AmazonCloudFront");
request.HttpMethod = "POST";
string uriResourcePath = "2013-08-26/streaming-distribution";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
StringWriter stringWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
xmlWriter.Namespaces = true;
if (createStreamingDistributionRequest != null)
{
StreamingDistributionConfig streamingDistributionConfigStreamingDistributionConfig = createStreamingDistributionRequest.StreamingDistributionConfig;
if (streamingDistributionConfigStreamingDistributionConfig != null)
{
xmlWriter.WriteStartElement("StreamingDistributionConfig", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (streamingDistributionConfigStreamingDistributionConfig.IsSetCallerReference())
{
xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingDistributionConfigStreamingDistributionConfig.CallerReference.ToString());
}
if (streamingDistributionConfigStreamingDistributionConfig != null)
{
S3Origin s3OriginS3Origin = streamingDistributionConfigStreamingDistributionConfig.S3Origin;
if (s3OriginS3Origin != null)
{
xmlWriter.WriteStartElement("S3Origin", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (s3OriginS3Origin.IsSetDomainName())
{
xmlWriter.WriteElementString("DomainName", "http://cloudfront.amazonaws.com/doc/2013-08-26/", s3OriginS3Origin.DomainName.ToString());
}
if (s3OriginS3Origin.IsSetOriginAccessIdentity())
{
xmlWriter.WriteElementString("OriginAccessIdentity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", s3OriginS3Origin.OriginAccessIdentity.ToString());
}
xmlWriter.WriteEndElement();
}
}
if (streamingDistributionConfigStreamingDistributionConfig != null)
{
Aliases aliasesAliases = streamingDistributionConfigStreamingDistributionConfig.Aliases;
if (aliasesAliases != null)
{
xmlWriter.WriteStartElement("Aliases", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (aliasesAliases.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", aliasesAliases.Quantity.ToString());
}
if (aliasesAliases != null)
{
List<string> aliasesAliasesitemsList = aliasesAliases.Items;
if (aliasesAliasesitemsList != null && aliasesAliasesitemsList.Count > 0)
{
int aliasesAliasesitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string aliasesAliasesitemsListValue in aliasesAliasesitemsList)
{
xmlWriter.WriteStartElement("CNAME", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(aliasesAliasesitemsListValue);
xmlWriter.WriteEndElement();
aliasesAliasesitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (streamingDistributionConfigStreamingDistributionConfig.IsSetComment())
{
xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingDistributionConfigStreamingDistributionConfig.Comment.ToString());
}
if (streamingDistributionConfigStreamingDistributionConfig != null)
{
StreamingLoggingConfig streamingLoggingConfigLogging = streamingDistributionConfigStreamingDistributionConfig.Logging;
if (streamingLoggingConfigLogging != null)
{
xmlWriter.WriteStartElement("Logging", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (streamingLoggingConfigLogging.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingLoggingConfigLogging.Enabled.ToString().ToLower());
}
if (streamingLoggingConfigLogging.IsSetBucket())
{
xmlWriter.WriteElementString("Bucket", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingLoggingConfigLogging.Bucket.ToString());
}
if (streamingLoggingConfigLogging.IsSetPrefix())
{
xmlWriter.WriteElementString("Prefix", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingLoggingConfigLogging.Prefix.ToString());
}
xmlWriter.WriteEndElement();
}
}
if (streamingDistributionConfigStreamingDistributionConfig != null)
{
TrustedSigners trustedSignersTrustedSigners = streamingDistributionConfigStreamingDistributionConfig.TrustedSigners;
if (trustedSignersTrustedSigners != null)
{
xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
if (trustedSignersTrustedSigners.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Enabled.ToString().ToLower());
}
if (trustedSignersTrustedSigners.IsSetQuantity())
{
xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2013-08-26/", trustedSignersTrustedSigners.Quantity.ToString());
}
if (trustedSignersTrustedSigners != null)
{
List<string> trustedSignersTrustedSignersitemsList = trustedSignersTrustedSigners.Items;
if (trustedSignersTrustedSignersitemsList != null && trustedSignersTrustedSignersitemsList.Count > 0)
{
int trustedSignersTrustedSignersitemsListIndex = 1;
xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
foreach (string trustedSignersTrustedSignersitemsListValue in trustedSignersTrustedSignersitemsList)
{
xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2013-08-26/");
xmlWriter.WriteValue(trustedSignersTrustedSignersitemsListValue);
xmlWriter.WriteEndElement();
trustedSignersTrustedSignersitemsListIndex++;
}
xmlWriter.WriteEndElement();
}
}
xmlWriter.WriteEndElement();
}
}
if (streamingDistributionConfigStreamingDistributionConfig.IsSetPriceClass())
{
xmlWriter.WriteElementString("PriceClass", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingDistributionConfigStreamingDistributionConfig.PriceClass.ToString());
}
if (streamingDistributionConfigStreamingDistributionConfig.IsSetEnabled())
{
xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2013-08-26/", streamingDistributionConfigStreamingDistributionConfig.Enabled.ToString().ToLower());
}
xmlWriter.WriteEndElement();
}
}
try
{
request.Content = System.Text.Encoding.UTF8.GetBytes(stringWriter.ToString());
request.Headers.Add("Content-Type", "application/xml");
}
catch (EncoderFallbackException e)
{
throw new AmazonServiceException("Unable to marshall request to XML", e);
}
return request;
}
}
}
| |
/*
* 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 System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI80;
using NUnit.Framework;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI80
{
/// <summary>
/// C_DigestEncryptUpdate and C_DecryptDigestUpdate tests.
/// </summary>
[TestFixture()]
public class _23_DigestEncryptAndDecryptDigestTest
{
/// <summary>
/// Basic C_DigestEncryptUpdate and C_DecryptDigestUpdate test.
/// </summary>
[Test()]
public void _01_BasicDigestEncryptAndDecryptDigestTest()
{
if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs80);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
ulong slotId = Helpers.GetUsableSlot(pkcs11);
ulong session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate symetric key
ulong keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate random initialization vector
byte[] iv = new byte[8];
rv = pkcs11.C_GenerateRandom(session, iv, Convert.ToUInt64(iv.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify encryption mechanism with initialization vector as parameter.
// Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory.
CK_MECHANISM encryptionMechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv);
// Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM digestingMechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password");
byte[] encryptedData = null;
byte[] digest1 = null;
byte[] decryptedData = null;
byte[] digest2 = null;
// Multipart digesting and encryption function C_DigestEncryptUpdate can be used i.e. for digesting and encryption of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream())
{
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize encryption operation
rv = pkcs11.C_EncryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
ulong encryptedPartLen = Convert.ToUInt64(encryptedPart.Length);
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Process each individual source data part
encryptedPartLen = Convert.ToUInt64(encryptedPart.Length);
rv = pkcs11.C_DigestEncryptUpdate(session, part, Convert.ToUInt64(bytesRead), encryptedPart, ref encryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append encrypted data part to the output stream
outputStream.Write(encryptedPart, 0, Convert.ToInt32(encryptedPartLen));
}
// Get length of digest value in first call
ulong digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest1 = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest1, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get the length of last encrypted data part in first call
byte[] lastEncryptedPart = null;
ulong lastEncryptedPartLen = 0;
rv = pkcs11.C_EncryptFinal(session, null, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last encrypted data part
lastEncryptedPart = new byte[lastEncryptedPartLen];
// Get the last encrypted data part in second call
rv = pkcs11.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last encrypted data part to the output stream
outputStream.Write(lastEncryptedPart, 0, Convert.ToInt32(lastEncryptedPartLen));
// Read whole output stream to the byte array so we can compare results more easily
encryptedData = outputStream.ToArray();
}
// Do something interesting with encrypted data and digest
// Multipart decryption and digesting function C_DecryptDigestUpdate can be used i.e. for digesting and decryption of streamed data
using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream())
{
// Initialize decryption operation
rv = pkcs11.C_DecryptInit(session, ref encryptionMechanism, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref digestingMechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for encrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] encryptedPart = new byte[8];
// Prepare buffer for decrypted data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
ulong partLen = Convert.ToUInt64(part.Length);
// Read input stream with encrypted data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0)
{
// Process each individual encrypted data part
partLen = Convert.ToUInt64(part.Length);
rv = pkcs11.C_DecryptDigestUpdate(session, encryptedPart, Convert.ToUInt64(bytesRead), part, ref partLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append decrypted data part to the output stream
outputStream.Write(part, 0, Convert.ToInt32(partLen));
}
// Get the length of last decrypted data part in first call
byte[] lastPart = null;
ulong lastPartLen = 0;
rv = pkcs11.C_DecryptFinal(session, null, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Allocate array for the last decrypted data part
lastPart = new byte[lastPartLen];
// Get the last decrypted data part in second call
rv = pkcs11.C_DecryptFinal(session, lastPart, ref lastPartLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Append the last decrypted data part to the output stream
outputStream.Write(lastPart, 0, Convert.ToInt32(lastPartLen));
// Read whole output stream to the byte array so we can compare results more easily
decryptedData = outputStream.ToArray();
// Get length of digest value in first call
ulong digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest2 = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest2, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with decrypted data and digest
Assert.IsTrue(Convert.ToBase64String(sourceData) == Convert.ToBase64String(decryptedData));
Assert.IsTrue(Convert.ToBase64String(digest1) == Convert.ToBase64String(digest2));
// In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case)
UnmanagedMemory.Free(ref encryptionMechanism.Parameter);
encryptionMechanism.ParameterLen = 0;
rv = pkcs11.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
// Copyright (c) Microsoft. 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.Diagnostics;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableListTest : ImmutableListTestBase
{
private enum Operation
{
Add,
AddRange,
Insert,
InsertRange,
RemoveAt,
RemoveRange,
Last,
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new List<int>();
var actual = ImmutableList<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the list.", value);
expected.Add(value);
actual = actual.Add(value);
VerifyBalanced(actual);
break;
case Operation.AddRange:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the list.", inputLength);
expected.AddRange(values);
actual = actual.AddRange(values);
VerifyBalanced(actual);
break;
case Operation.Insert:
int position = random.Next(expected.Count + 1);
value = random.Next();
Debug.WriteLine("Adding \"{0}\" to position {1} in the list.", value, position);
expected.Insert(position, value);
actual = actual.Insert(position, value);
VerifyBalanced(actual);
break;
case Operation.InsertRange:
inputLength = random.Next(100);
values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
position = random.Next(expected.Count + 1);
Debug.WriteLine("Adding {0} elements to position {1} in the list.", inputLength, position);
expected.InsertRange(position, values);
actual = actual.InsertRange(position, values);
VerifyBalanced(actual);
break;
case Operation.RemoveAt:
if (expected.Count > 0)
{
position = random.Next(expected.Count);
Debug.WriteLine("Removing element at position {0} from the list.", position);
expected.RemoveAt(position);
actual = actual.RemoveAt(position);
VerifyBalanced(actual);
}
break;
case Operation.RemoveRange:
position = random.Next(expected.Count);
inputLength = random.Next(expected.Count - position);
Debug.WriteLine("Removing {0} elements starting at position {1} from the list.", inputLength, position);
expected.RemoveRange(position, inputLength);
actual = actual.RemoveRange(position, inputLength);
VerifyBalanced(actual);
break;
}
Assert.Equal<int>(expected, actual);
}
}
[Fact]
public void EmptyTest()
{
var empty = ImmutableList<GenericParameterHelper>.Empty;
Assert.Same(empty, ImmutableList<GenericParameterHelper>.Empty);
Assert.Same(empty, empty.Clear());
Assert.Same(empty, ((IImmutableList<GenericParameterHelper>)empty).Clear());
Assert.True(empty.IsEmpty);
Assert.Equal(0, empty.Count);
Assert.Equal(-1, empty.IndexOf(new GenericParameterHelper()));
Assert.Equal(-1, empty.IndexOf(null));
}
[Fact]
public void GetHashCodeVariesByInstance()
{
Assert.NotEqual(ImmutableList.Create<int>().GetHashCode(), ImmutableList.Create(5).GetHashCode());
}
[Fact]
public void AddAndIndexerTest()
{
var list = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
Assert.False(list.IsEmpty);
Assert.Equal(i, list.Count);
}
for (int i = 1; i <= 10; i++)
{
Assert.Equal(i * 10, list[i - 1]);
}
var bulkList = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10).Select(i => i * 10));
Assert.Equal<int>(list.ToArray(), bulkList.ToArray());
}
[Fact]
public void AddRangeTest()
{
var list = ImmutableList<int>.Empty;
list = list.AddRange(new[] { 1, 2, 3 });
list = list.AddRange(Enumerable.Range(4, 2));
list = list.AddRange(ImmutableList<int>.Empty.AddRange(new[] { 6, 7, 8 }));
list = list.AddRange(new int[0]);
list = list.AddRange(ImmutableList<int>.Empty.AddRange(Enumerable.Range(9, 1000)));
Assert.Equal(Enumerable.Range(1, 1008), list);
}
[Fact]
public void AddRangeOptimizationsTest()
{
// All these optimizations are tested based on filling an empty list.
var emptyList = ImmutableList.Create<string>();
// Adding an empty list to an empty list should yield the original list.
Assert.Same(emptyList, emptyList.AddRange(new string[0]));
// Adding a non-empty immutable list to an empty one should return the added list.
var nonEmptyListDefaultComparer = ImmutableList.Create("5");
Assert.Same(nonEmptyListDefaultComparer, emptyList.AddRange(nonEmptyListDefaultComparer));
// Adding a Builder instance to an empty list should be seen through.
var builderOfNonEmptyListDefaultComparer = nonEmptyListDefaultComparer.ToBuilder();
Assert.Same(nonEmptyListDefaultComparer, emptyList.AddRange(builderOfNonEmptyListDefaultComparer));
}
[Fact]
public void AddRangeBalanceTest()
{
int randSeed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
int expectedTotalSize = 0;
var list = ImmutableList<int>.Empty;
// Add some small batches, verifying balance after each
for (int i = 0; i < 128; i++)
{
int batchSize = random.Next(32);
Debug.WriteLine("Adding {0} elements to the list", batchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, batchSize));
VerifyBalanced(list);
expectedTotalSize += batchSize;
}
// Add a single large batch to the end
int largeBatchSize = random.Next(32768) + 32768;
Debug.WriteLine("Adding {0} elements to the list", largeBatchSize);
list = list.AddRange(Enumerable.Range(expectedTotalSize + 1, largeBatchSize));
VerifyBalanced(list);
expectedTotalSize += largeBatchSize;
Assert.Equal(Enumerable.Range(1, expectedTotalSize), list);
list.Root.VerifyHeightIsWithinTolerance();
}
[Fact]
public void InsertRangeRandomBalanceTest()
{
int randSeed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Random seed: {0}", randSeed);
var random = new Random(randSeed);
var immutableList = ImmutableList.CreateBuilder<int>();
var list = new List<int>();
const int maxBatchSize = 32;
int valueCounter = 0;
for (int i = 0; i < 24; i++)
{
int startPosition = random.Next(list.Count + 1);
int length = random.Next(maxBatchSize + 1);
int[] values = new int[length];
for (int j = 0; j < length; j++)
{
values[j] = ++valueCounter;
}
immutableList.InsertRange(startPosition, values);
list.InsertRange(startPosition, values);
Assert.Equal(list, immutableList);
immutableList.Root.VerifyBalanced();
}
immutableList.Root.VerifyHeightIsWithinTolerance();
}
[Fact]
public void InsertTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, 5));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, 5));
list = list.Insert(0, 10);
list = list.Insert(1, 20);
list = list.Insert(2, 30);
list = list.Insert(2, 25);
list = list.Insert(1, 15);
list = list.Insert(0, 5);
Assert.Equal(6, list.Count);
var expectedList = new[] { 5, 10, 15, 20, 25, 30 };
var actualList = list.ToArray();
Assert.Equal<int>(expectedList, actualList);
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(7, 5));
Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, 5));
}
[Fact]
public void InsertBalanceTest()
{
var list = ImmutableList.Create(1);
list = list.Insert(0, 2);
list = list.Insert(1, 3);
VerifyBalanced(list);
}
[Fact]
public void InsertRangeTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { 1 }));
list = list.InsertRange(0, new[] { 1, 4, 5 });
list = list.InsertRange(1, new[] { 2, 3 });
list = list.InsertRange(2, new int[0]);
Assert.Equal(Enumerable.Range(1, 5), list);
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(6, new[] { 1 }));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { 1 }));
}
[Fact]
public void InsertRangeImmutableTest()
{
var list = ImmutableList<int>.Empty;
var nonEmptyList = ImmutableList.Create(1);
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, nonEmptyList));
list = list.InsertRange(0, ImmutableList.Create(1, 104, 105));
list = list.InsertRange(1, ImmutableList.Create(2, 3));
list = list.InsertRange(2, ImmutableList<int>.Empty);
list = list.InsertRange(3, ImmutableList<int>.Empty.InsertRange(0, Enumerable.Range(4, 100)));
Assert.Equal(Enumerable.Range(1, 105), list);
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(106, nonEmptyList));
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, nonEmptyList));
}
[Fact]
public void NullHandlingTest()
{
var list = ImmutableList<GenericParameterHelper>.Empty;
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
list = list.Add((GenericParameterHelper)null);
Assert.Equal(1, list.Count);
Assert.Null(list[0]);
Assert.True(list.Contains(null));
Assert.Equal(0, list.IndexOf(null));
list = list.Remove((GenericParameterHelper)null);
Assert.Equal(0, list.Count);
Assert.True(list.IsEmpty);
Assert.False(list.Contains(null));
Assert.Equal(-1, list.IndexOf(null));
}
[Fact]
public void RemoveTest()
{
ImmutableList<int> list = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.Remove(30);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.Remove(100);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.Remove(10);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
var removeList = new int[] { 20, 70 };
list = list.RemoveAll(removeList.Contains);
Assert.Equal(5, list.Count);
Assert.False(list.Contains(20));
Assert.False(list.Contains(70));
IImmutableList<int> list2 = ImmutableList<int>.Empty;
for (int i = 1; i <= 10; i++)
{
list2 = list2.Add(i * 10);
}
list2 = list2.Remove(30);
Assert.Equal(9, list2.Count);
Assert.False(list2.Contains(30));
list2 = list2.Remove(100);
Assert.Equal(8, list2.Count);
Assert.False(list2.Contains(100));
list2 = list2.Remove(10);
Assert.Equal(7, list2.Count);
Assert.False(list2.Contains(10));
list2 = list2.RemoveAll(removeList.Contains);
Assert.Equal(5, list2.Count);
Assert.False(list2.Contains(20));
Assert.False(list2.Contains(70));
}
[Fact]
public void RemoveNonExistentKeepsReference()
{
var list = ImmutableList<int>.Empty;
Assert.Same(list, list.Remove(3));
}
[Fact]
public void RemoveAtTest()
{
var list = ImmutableList<int>.Empty;
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(1));
for (int i = 1; i <= 10; i++)
{
list = list.Add(i * 10);
}
list = list.RemoveAt(2);
Assert.Equal(9, list.Count);
Assert.False(list.Contains(30));
list = list.RemoveAt(8);
Assert.Equal(8, list.Count);
Assert.False(list.Contains(100));
list = list.RemoveAt(0);
Assert.Equal(7, list.Count);
Assert.False(list.Contains(10));
}
[Fact]
public void IndexOfAndContainsTest()
{
var expectedList = new List<string>(new[] { "Microsoft", "Windows", "Bing", "Visual Studio", "Comics", "Computers", "Laptops" });
var list = ImmutableList<string>.Empty;
foreach (string newElement in expectedList)
{
Assert.False(list.Contains(newElement));
list = list.Add(newElement);
Assert.True(list.Contains(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement));
Assert.Equal(expectedList.IndexOf(newElement), list.IndexOf(newElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(newElement.ToUpperInvariant()));
foreach (string existingElement in expectedList.TakeWhile(v => v != newElement))
{
Assert.True(list.Contains(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement));
Assert.Equal(expectedList.IndexOf(existingElement), list.IndexOf(existingElement.ToUpperInvariant(), StringComparer.OrdinalIgnoreCase));
Assert.Equal(-1, list.IndexOf(existingElement.ToUpperInvariant()));
}
}
}
[Fact]
public void Indexer()
{
var list = ImmutableList.CreateRange(Enumerable.Range(1, 3));
Assert.Equal(1, list[0]);
Assert.Equal(2, list[1]);
Assert.Equal(3, list[2]);
Assert.Throws<ArgumentOutOfRangeException>(() => list[3]);
Assert.Throws<ArgumentOutOfRangeException>(() => list[-1]);
Assert.Equal(3, ((IList)list)[2]);
Assert.Equal(3, ((IList<int>)list)[2]);
}
[Fact]
public void IndexOf()
{
IndexOfTests.IndexOfTest(
seq => ImmutableList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
IndexOfTests.IndexOfTest(
seq => (IImmutableList<int>)ImmutableList.CreateRange(seq),
(b, v) => b.IndexOf(v),
(b, v, i) => b.IndexOf(v, i),
(b, v, i, c) => b.IndexOf(v, i, c),
(b, v, i, c, eq) => b.IndexOf(v, i, c, eq));
}
[Fact]
public void LastIndexOf()
{
IndexOfTests.LastIndexOfTest(
seq => ImmutableList.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
IndexOfTests.LastIndexOfTest(
seq => (IImmutableList<int>)ImmutableList.CreateRange(seq),
(b, v) => b.LastIndexOf(v),
(b, v, eq) => b.LastIndexOf(v, eq),
(b, v, i) => b.LastIndexOf(v, i),
(b, v, i, c) => b.LastIndexOf(v, i, c),
(b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq));
}
[Fact]
public void ReplaceTest()
{
// Verify replace at beginning, middle, and end.
var list = ImmutableList<int>.Empty.Add(3).Add(5).Add(8);
Assert.Equal<int>(new[] { 4, 5, 8 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, list.Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, list.Replace(8, 9));
Assert.Equal<int>(new[] { 4, 5, 8 }, ((IImmutableList<int>)list).Replace(3, 4));
Assert.Equal<int>(new[] { 3, 6, 8 }, ((IImmutableList<int>)list).Replace(5, 6));
Assert.Equal<int>(new[] { 3, 5, 9 }, ((IImmutableList<int>)list).Replace(8, 9));
// Verify replacement of first element when there are duplicates.
list = ImmutableList<int>.Empty.Add(3).Add(3).Add(5);
Assert.Equal<int>(new[] { 4, 3, 5 }, list.Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, list.Replace(3, 4).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 3, 5 }, ((IImmutableList<int>)list).Replace(3, 4));
Assert.Equal<int>(new[] { 4, 4, 5 }, ((IImmutableList<int>)list).Replace(3, 4).Replace(3, 4));
}
[Fact]
public void ReplaceWithEqualityComparerTest()
{
var list = ImmutableList.Create(new Person { Name = "Andrew", Age = 20 });
var newAge = new Person { Name = "Andrew", Age = 21 };
var updatedList = list.Replace(newAge, newAge, new NameOnlyEqualityComparer());
Assert.Equal(newAge.Age, updatedList[0].Age);
}
[Fact]
public void ReplaceMissingThrowsTest()
{
Assert.Throws<ArgumentException>(() => ImmutableList<int>.Empty.Replace(5, 3));
}
[Fact]
public void EqualsTest()
{
Assert.False(ImmutableList<int>.Empty.Equals(null));
Assert.False(ImmutableList<int>.Empty.Equals("hi"));
Assert.True(ImmutableList<int>.Empty.Equals(ImmutableList<int>.Empty));
Assert.False(ImmutableList<int>.Empty.Add(3).Equals(ImmutableList<int>.Empty.Add(3)));
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
ImmutableList<string> list = ImmutableList.Create<string>();
Assert.Equal(0, list.Count);
list = ImmutableList.Create("a");
Assert.Equal(1, list.Count);
list = ImmutableList.Create("a", "b");
Assert.Equal(2, list.Count);
list = ImmutableList.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableList()
{
ImmutableList<string> list = new[] { "a", "b" }.ToImmutableList();
Assert.Equal(2, list.Count);
list = new[] { "a", "b" }.ToImmutableList();
Assert.Equal(2, list.Count);
}
[Fact]
public void ToImmutableListOfSameType()
{
var list = ImmutableList.Create("a");
Assert.Same(list, list.ToImmutableList());
}
[Fact]
public void RemoveAllNullTest()
{
Assert.Throws<ArgumentNullException>(() => ImmutableList<int>.Empty.RemoveAll(null));
}
[Fact]
public void RemoveRangeArrayTest()
{
var list = ImmutableList.Create(1, 2, 3);
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(-1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(4, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(0, 4));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveRange(2, 2));
list.RemoveRange(3, 0);
Assert.Equal(3, list.Count);
}
[Fact]
public void RemoveRangeEnumerableTest()
{
var list = ImmutableList.Create(1, 2, 3);
Assert.Throws<ArgumentNullException>(() => list.RemoveRange(null));
ImmutableList<int> removed2 = list.RemoveRange(new[] { 2 });
Assert.Equal(2, removed2.Count);
Assert.Equal(new[] { 1, 3 }, removed2);
ImmutableList<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 });
Assert.Equal(1, removed13.Count);
Assert.Equal(new[] { 2 }, removed13);
Assert.Equal(new[] { 2 }, ((IImmutableList<int>)list).RemoveRange(new[] { 1, 3, 5 }));
Assert.Same(list, list.RemoveRange(new[] { 5 }));
Assert.Same(ImmutableList.Create<int>(), ImmutableList.Create<int>().RemoveRange(new[] { 1 }));
var listWithDuplicates = ImmutableList.Create(1, 2, 2, 3);
Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 }));
Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 }));
Assert.Throws<ArgumentNullException>(() => ((IImmutableList<int>)ImmutableList.Create(1, 2, 3)).RemoveRange(null));
Assert.Equal(new[] { 1, 3 }, ((IImmutableList<int>)ImmutableList.Create(1, 2, 3)).RemoveRange(new[] { 2 }));
}
[Fact]
public void EnumeratorTest()
{
var list = ImmutableList.Create("a");
var enumerator = list.GetEnumerator();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableList.Create(1);
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.True(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.True(enumerator.MoveNext());
Assert.Equal(collection[0], enumerator.Current);
enumerator.Dispose();
}
[Fact]
public void ReverseTest2()
{
var emptyList = ImmutableList.Create<int>();
Assert.Same(emptyList, emptyList.Reverse());
var populatedList = ImmutableList.Create(3, 2, 1);
Assert.Equal(Enumerable.Range(1, 3), populatedList.Reverse());
}
[Fact]
public void SetItem()
{
var emptyList = ImmutableList.Create<int>();
Assert.Throws<ArgumentOutOfRangeException>(() => emptyList[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => emptyList[0]);
Assert.Throws<ArgumentOutOfRangeException>(() => emptyList[1]);
var listOfOne = emptyList.Add(5);
Assert.Throws<ArgumentOutOfRangeException>(() => listOfOne[-1]);
Assert.Equal(5, listOfOne[0]);
Assert.Throws<ArgumentOutOfRangeException>(() => listOfOne[1]);
}
[Fact]
public void IsSynchronized()
{
ICollection collection = ImmutableList.Create<int>();
Assert.True(collection.IsSynchronized);
}
[Fact]
public void IListIsReadOnly()
{
IList list = ImmutableList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.True(list.IsFixedSize);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void IListOfTIsReadOnly()
{
IList<int> list = ImmutableList.Create<int>();
Assert.True(list.IsReadOnly);
Assert.Throws<NotSupportedException>(() => list.Add(1));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, 1));
Assert.Throws<NotSupportedException>(() => list.Remove(1));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list[0] = 1);
}
[Fact]
public void DebuggerAttributesValid()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableList.Create<int>());
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableList.Create<double>(1, 2, 3));
object rootNode = DebuggerAttributes.GetFieldValue(ImmutableList.Create<string>("1", "2", "3"), "_root");
DebuggerAttributes.ValidateDebuggerDisplayReferences(rootNode);
}
protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents)
{
return ImmutableList<T>.Empty.AddRange(contents);
}
protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test)
{
var expected = list.ToList();
expected.RemoveAll(test);
var actual = list.RemoveAll(test);
Assert.Equal<T>(expected, actual.ToList());
}
protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count)
{
var expected = list.ToList();
expected.Reverse(index, count);
var actual = list.Reverse(index, count);
Assert.Equal<T>(expected, actual.ToList());
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list)
{
return list.Sort().ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison)
{
return list.Sort(comparison).ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer)
{
return list.Sort(comparer).ToList();
}
protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer)
{
return list.Sort(index, count, comparer).ToList();
}
internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list)
{
return list;
}
private static void VerifyBalanced<T>(ImmutableList<T> tree)
{
tree.Root.VerifyBalanced();
}
private struct Person
{
public string Name { get; set; }
public int Age { get; set; }
}
private class NameOnlyEqualityComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.Name == y.Name;
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.