context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
//
// AnimatedWidget.cs
//
// Authors:
// Scott Peterson <lunchtimemama@gmail.com>
//
// Copyright (C) 2008 Scott Peterson
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Gdk;
using Gtk;
using Hyena.Gui;
using Hyena.Gui.Theatrics;
namespace Hyena.Widgets
{
internal enum AnimationState
{
Coming,
Idle,
IntendingToGo,
Going
}
internal class AnimatedWidget : Container
{
public event EventHandler WidgetDestroyed;
public Widget Widget;
public Easing Easing;
public Blocking Blocking;
public AnimationState AnimationState;
public uint Duration;
public double Bias = 1.0;
public int Width;
public int Height;
public int StartPadding;
public int EndPadding;
public LinkedListNode <AnimatedWidget> Node;
private readonly bool horizontal;
private double percent;
private Rectangle widget_alloc;
private Cairo.Surface surface;
public AnimatedWidget (Widget widget, uint duration, Easing easing, Blocking blocking, bool horizontal)
{
this.horizontal = horizontal;
Widget = widget;
Duration = duration;
Easing = easing;
Blocking = blocking;
AnimationState = AnimationState.Coming;
Widget.Parent = this;
Widget.Destroyed += OnWidgetDestroyed;
ShowAll ();
}
protected AnimatedWidget (IntPtr raw) : base (raw)
{
}
public double Percent {
get { return percent; }
set {
percent = value * Bias;
QueueResizeNoRedraw ();
}
}
private void OnWidgetDestroyed (object sender, EventArgs args)
{
if (!IsRealized) {
return;
}
// Copy the widget's pixels to surface, we'll use it to draw the animation
surface = Window.CreateSimilarSurface (Cairo.Content.ColorAlpha, widget_alloc.Width, widget_alloc.Height);
using (var cr = new Cairo.Context (surface)) {
Gdk.CairoHelper.SetSourceWindow (cr, Window, widget_alloc.X, widget_alloc.Y);
cr.Rectangle (0, 0, widget_alloc.Width, widget_alloc.Height);
cr.Fill ();
if (AnimationState != AnimationState.Going) {
WidgetDestroyed (this, args);
}
}
}
#region Overrides
protected override void OnRemoved (Widget widget)
{
if (widget == Widget) {
widget.Unparent ();
Widget = null;
}
}
protected override void OnRealized ()
{
IsRealized = true;
Gdk.WindowAttr attributes = new Gdk.WindowAttr ();
attributes.WindowType = Gdk.WindowType.Child;
attributes.Wclass = Gdk.WindowWindowClass.InputOutput;
attributes.EventMask = (int)Gdk.EventMask.ExposureMask;
Window = new Gdk.Window (Parent.Window, attributes, 0);
Window.UserData = Handle;
Window.BackgroundRgba = StyleContext.GetBackgroundColor (StateFlags);
}
protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height)
{
base.OnGetPreferredHeight (out minimum_height, out natural_height);
var requisition = SizeRequested ();
minimum_height = natural_height = requisition.Height;
}
protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width)
{
base.OnGetPreferredWidth (out minimum_width, out natural_width);
var requisition = SizeRequested ();
minimum_width = natural_width = requisition.Width;
}
protected Requisition SizeRequested ()
{
var requisition = new Requisition ();
if (Widget != null) {
Requisition req, nat;
Widget.GetPreferredSize (out req, out nat);
widget_alloc.Width = req.Width;
widget_alloc.Height = req.Height;
}
if (horizontal) {
Width = Choreographer.PixelCompose (percent, widget_alloc.Width + StartPadding + EndPadding, Easing);
Height = widget_alloc.Height;
} else {
Width = widget_alloc.Width;
Height = Choreographer.PixelCompose (percent, widget_alloc.Height + StartPadding + EndPadding, Easing);
}
requisition.Width = Width;
requisition.Height = Height;
return requisition;
}
protected override void OnSizeAllocated (Rectangle allocation)
{
base.OnSizeAllocated (allocation);
if (Widget != null) {
if (horizontal) {
widget_alloc.Height = allocation.Height;
widget_alloc.X = StartPadding;
if (Blocking == Blocking.Downstage) {
widget_alloc.X += allocation.Width - widget_alloc.Width;
}
} else {
widget_alloc.Width = allocation.Width;
widget_alloc.Y = StartPadding;
if (Blocking == Blocking.Downstage) {
widget_alloc.Y = allocation.Height - widget_alloc.Height;
}
}
if (widget_alloc.Height > 0 && widget_alloc.Width > 0) {
Widget.SizeAllocate (widget_alloc);
}
}
}
protected override bool OnDrawn (Cairo.Context cr)
{
if (surface != null) {
cr.Save ();
Gtk.CairoHelper.TransformToWindow (cr, this, Window);
cr.SetSource (surface);
cr.Rectangle (widget_alloc.X, widget_alloc.Y, widget_alloc.Width, widget_alloc.Height);
cr.Fill ();
cr.Restore ();
return true;
} else {
return base.OnDrawn (cr);
}
}
protected override void ForAll (bool include_internals, Callback callback)
{
if (Widget != null) {
callback (Widget);
}
}
#endregion
}
}
| |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
using System.Text;
namespace Lucene.Net.Analysis.CommonGrams
{
/*
* 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.
*/
/*
* TODO: Consider implementing https://issues.apache.org/jira/browse/LUCENE-1688 changes to stop list and associated constructors
*/
/// <summary>
/// Construct bigrams for frequently occurring terms while indexing. Single terms
/// are still indexed too, with bigrams overlaid. This is achieved through the
/// use of <see cref="PositionIncrementAttribute.PositionIncrement"/>. Bigrams have a type
/// of <see cref="GRAM_TYPE"/> Example:
/// <list type="bullet">
/// <item><description>input:"the quick brown fox"</description></item>
/// <item><description>output:|"the","the-quick"|"brown"|"fox"|</description></item>
/// <item><description>"the-quick" has a position increment of 0 so it is in the same position
/// as "the" "the-quick" has a term.type() of "gram"</description></item>
/// </list>
/// </summary>
/*
* Constructors and makeCommonSet based on similar code in StopFilter
*/
public sealed class CommonGramsFilter : TokenFilter
{
public const string GRAM_TYPE = "gram";
private const char SEPARATOR = '_';
private readonly CharArraySet commonWords;
private readonly StringBuilder buffer = new StringBuilder();
private readonly ICharTermAttribute termAttribute;
private readonly IOffsetAttribute offsetAttribute;
private readonly ITypeAttribute typeAttribute;
private readonly IPositionIncrementAttribute posIncAttribute;
private readonly IPositionLengthAttribute posLenAttribute;
private int lastStartOffset;
private bool lastWasCommon;
private State savedState;
/// <summary>
/// Construct a token stream filtering the given input using a Set of common
/// words to create bigrams. Outputs both unigrams with position increment and
/// bigrams with position increment 0 type=gram where one or both of the words
/// in a potential bigram are in the set of common words .
/// </summary>
/// <param name="matchVersion"> lucene compatibility version </param>
/// <param name="input"> <see cref="TokenStream"/> input in filter chain </param>
/// <param name="commonWords"> The set of common words. </param>
public CommonGramsFilter(LuceneVersion matchVersion, TokenStream input, CharArraySet commonWords)
: base(input)
{
termAttribute = AddAttribute<ICharTermAttribute>();
offsetAttribute = AddAttribute<IOffsetAttribute>();
typeAttribute = AddAttribute<ITypeAttribute>();
posIncAttribute = AddAttribute<IPositionIncrementAttribute>();
posLenAttribute = AddAttribute<IPositionLengthAttribute>();
this.commonWords = commonWords;
}
/// <summary>
/// Inserts bigrams for common words into a token stream. For each input token,
/// output the token. If the token and/or the following token are in the list
/// of common words also output a bigram with position increment 0 and
/// type="gram"
/// <para/>
/// TODO:Consider adding an option to not emit unigram stopwords
/// as in CDL XTF BigramStopFilter, <see cref="CommonGramsQueryFilter"/> would need to be
/// changed to work with this.
/// <para/>
/// TODO: Consider optimizing for the case of three
/// commongrams i.e "man of the year" normally produces 3 bigrams: "man-of",
/// "of-the", "the-year" but with proper management of positions we could
/// eliminate the middle bigram "of-the"and save a disk seek and a whole set of
/// position lookups.
/// </summary>
public override bool IncrementToken()
{
// get the next piece of input
if (savedState != null)
{
RestoreState(savedState);
savedState = null;
SaveTermBuffer();
return true;
}
else if (!m_input.IncrementToken())
{
return false;
}
/* We build n-grams before and after stopwords.
* When valid, the buffer always contains at least the separator.
* If its empty, there is nothing before this stopword.
*/
if (lastWasCommon || (IsCommon && buffer.Length > 0))
{
savedState = CaptureState();
GramToken();
return true;
}
SaveTermBuffer();
return true;
}
/// <summary>
/// This method is called by a consumer before it begins consumption using
/// <see cref="IncrementToken()"/>.
/// <para/>
/// Resets this stream to a clean state. Stateful implementations must implement
/// this method so that they can be reused, just as if they had been created fresh.
/// <para/>
/// If you override this method, always call <c>base.Reset()</c>, otherwise
/// some internal state will not be correctly reset (e.g., <see cref="Tokenizer"/> will
/// throw <see cref="InvalidOperationException"/> on further usage).
/// </summary>
/// <remarks>
/// <b>NOTE:</b>
/// The default implementation chains the call to the input <see cref="TokenStream"/>, so
/// be sure to call <c>base.Reset()</c> when overriding this method.
/// </remarks>
public override void Reset()
{
base.Reset();
lastWasCommon = false;
savedState = null;
buffer.Length = 0;
}
// ================================================= Helper Methods ================================================
/// <summary>
/// Determines if the current token is a common term
/// </summary>
/// <returns> <c>true</c> if the current token is a common term, <c>false</c> otherwise </returns>
private bool IsCommon => commonWords != null && commonWords.Contains(termAttribute.Buffer, 0, termAttribute.Length);
/// <summary>
/// Saves this information to form the left part of a gram
/// </summary>
private void SaveTermBuffer()
{
buffer.Length = 0;
buffer.Append(termAttribute.Buffer, 0, termAttribute.Length);
buffer.Append(SEPARATOR);
lastStartOffset = offsetAttribute.StartOffset;
lastWasCommon = IsCommon;
}
/// <summary>
/// Constructs a compound token.
/// </summary>
private void GramToken()
{
buffer.Append(termAttribute.Buffer, 0, termAttribute.Length);
int endOffset = offsetAttribute.EndOffset;
ClearAttributes();
var length = buffer.Length;
var termText = termAttribute.Buffer;
if (length > termText.Length)
{
termText = termAttribute.ResizeBuffer(length);
}
buffer.CopyTo(0, termText, 0, length);
termAttribute.Length = length;
posIncAttribute.PositionIncrement = 0;
posLenAttribute.PositionLength = 2; // bigram
offsetAttribute.SetOffset(lastStartOffset, endOffset);
typeAttribute.Type = GRAM_TYPE;
buffer.Length = 0;
}
}
}
| |
//------------------------------------------------------------------------------
// Piece Manipulation Device (c) 2010 Robert MacGregor (AKA Dark Dragon DX)
// Version: 3.0b
// Comment: This file has went through much organization and it still isn't
// very neat!
//
// ----------------------------- Description -----------------------------------
// The Piece Manipulation Device is a special pack that enables
// you to create special effects on your creations by directly modifying
// any pieces found upon its list. When the device gains power, it scans
// a list of its pieces and takes the appropiate action for each one.
//
// Supported Actions:
//
// 1. Cloaking
// 2. Fading
// 3. Hiding (Just like fade, except the object cannot by collided with)
// 4. Scaling
// 5. Naming
// 6. Rotation (A special tool will be added to handle this)
//
// All of the above performance options are performed when the device gains
// power. The action taken will be undone when the device loses power.
//
// ------------------------------- Agreement -----------------------------------
//
// You may use this pack as a part of any other mod as long as
// you agree to the following terms:
//
// 1. You MAY NOT strip my name (Dark Dragon DX, Robert MacGregor)
// from any part of the script. This includes the header you are reading now.
//
// 2. You must directly state that I, Dark Dragon DX created this pack in a
// clearly seen place in Tribes 2. This may include the debriefGui,
// loadingGui or bottom & center print texts.
//
// 3. You MAY NOT modify any of the functioning code without my explicit
// permission. You can however, modify the settings that are GLOBAL VARIABLES.
//
// If you cannot abide by those terms, then don't edit this file at all.
//------------------------------------------------------------------------------
// Settings
$Editor::MaxScale["X"] = 20;
$Editor::MaxScale["Y"] = 20;
$Editor::MaxScale["Z"] = 20;
$Editor::MinScale["X"] = -20;
$Editor::MinScale["Y"] = -20;
$Editor::MinScale["Z"] = -20;
// Hidden Debris Option
$Editor::Debris::Enabled = false;
$Editor::Debris::MinMS = 100;
$Editor::Debris::Max = 5;
$Editor::Debris::Count = 0;
// Datablocks (From here on out, you cannot modify)
datablock StaticShapeData(DeployedEditorPack) : StaticShapeDamageProfile
{
className = "EditorPack";
shapeFile = "stackable2s.dts";
maxDamage = 2.0;
destroyedLevel = 2.0;
disabledLevel = 2.0;
mass = 1.2;
elasticity = 0.1;
friction = 0.9;
collideable = 1;
pickupRadius = 1;
sticky = false;
explosion = HandGrenadeExplosion;
expDmgRadius = 1.0;
expDamage = 0.1;
expImpulse = 200.0;
dynamicType = $TypeMasks::StaticShapeObjectType;
deployedObject = true;
cmdCategory = "DSupport";
cmdIcon = CMDSensorIcon;
cmdMiniIconName = "commander/MiniIcons/com_deploymotionsensor";
targetNameTag = 'Piece Manipulation';
targetTypeTag = 'Device';
deployAmbientThread = true;
debrisShapeName = "debris_generic_small.dts";
debris = DeployableDebris;
heatSignature = 0;
needsPower = true;
};
datablock ShapeBaseImageData(EditorPackDeployableImage)
{
mass = 10;
emap = true;
shapeFile = "stackable1s.dts";
item = EditorPackDeployable;
mountPoint = 1;
offset = "0 0 0";
deployed = DeployedEditorPack;
heatSignature = 0;
collideable = 1;
stateName[0] = "Idle";
stateTransitionOnTriggerDown[0] = "Activate";
stateName[1] = "Activate";
stateScript[1] = "onActivate";
stateTransitionOnTriggerUp[1] = "Idle";
isLarge = true;
maxDepSlope = 360;
deploySound = ItemPickupSound;
minDeployDis = 0.5;
maxDeployDis = 5.0;
};
datablock ItemData(EditorPackDeployable)
{
className = Pack;
catagory = "Deployables";
shapeFile = "stackable1s.dts";
mass = 5.0;
elasticity = 0.2;
friction = 0.6;
pickupRadius = 1;
rotate = true;
image = "EditorPackDeployableImage";
pickUpName = "a Piece Manipulation Device, by Dark Dragon DX";
heatSignature = 0;
emap = true;
};
// Code
function EditorPackDeployableImage::onDeploy(%item, %plyr, %slot)
{
%className = "StaticShape";
%playerVector = vectorNormalize(getWord(%plyr.getEyeVector(),1) SPC -1 * getWord(%plyr.getEyeVector(),0) SPC "0");
%item.surfaceNrm2 = %playerVector;
if (vAbs(floorVec(%item.surfaceNrm,100)) $= "0 0 1")
%item.surfaceNrm2 = %playerVector;
else
%item.surfaceNrm2 = vectorNormalize(vectorCross(%item.surfaceNrm,"0 0 -1"));
%rot = fullRot(%item.surfaceNrm,%item.surfaceNrm2);
%deplObj = new (%className)()
{
dataBlock = %item.deployed;
scale = "1 1 1";
};
// set orientation
%deplObj.setTransform(%item.surfacePt SPC %rot);
%deplObj.deploy();
// set team, owner, and handle
%deplObj.team = %plyr.client.Team;
%deplObj.setOwner(%plyr);
%deplObj.paded=1;
//Msg Client
messageclient(%plyr.client, 'MsgClient', "\c2Type /editor CMDs for a list of device CMD's.");
// set the sensor group if it needs one
if (%deplObj.getTarget() != -1)
setTargetSensorGroup(%deplObj.getTarget(), %plyr.client.team);
// place the deployable in the MissionCleanup/Deployables group (AI reasons)
addToDeployGroup(%deplObj);
//Set the power frequency
%deplObj.powerFreq = %plyr.powerFreq;
checkPowerObject(%deplObj);
//let the AI know as well...
AIDeployObject(%plyr.client, %deplObj);
// play the deploy sound
serverPlay3D(%item.deploySound, %deplObj.getTransform());
// increment the team count for this deployed object
$TeamDeployedCount[%plyr.team, %item.item]++;
addDSurface(%item.surface,%deplObj);
%deplObj.playThread($PowerThread,"Power");
%deplObj.playThread($AmbientThread,"ambient");
// take the deployable off the player's back and out of inventory
%plyr.unmountImage(%slot);
%plyr.decInventory(%item.item, 1);
//Set the slot count
%deplobj.slotcount = 1; //For /editor addobj
//Set the type
%type = addTaggedString("Device ("@%plyr.powerFreq@")");
setTargetType(%deplObj.target,%type);
return %deplObj;
}
function EditorPack::onCollision(%data,%obj,%col)
{
// created to prevent console errors
}
function EditorPackDeployable::onPickup(%this, %obj, %shape, %amount)
{
// created to prevent console errors
}
function EditorPackDeployableImage::onMount(%data, %obj, %node)
{
displayPowerFreq(%obj);
}
function EditorPackDeployableImage::onUnmount(%data, %obj, %node) {
// created to prevent console errors
}
function DeployedEditorPack::gainPower(%data, %obj)
{
if (%obj.IsPowered) //A source was turned off when multiple ones exist
return;
EditorPerform(%obj);
}
function DeployedEditorPack::losePower(%data, %obj)
{
if (!%obj.IsPowered) //Already off.
return;
%obj.RevertPieces(false);
}
function DeployedEditorPack::onDestroyed(%this, %obj, %prevState)
{
%obj.RevertPieces(true);
if (%obj.isRemoved)
return;
%obj.isRemoved = true;
Parent::onDestroyed(%this, %obj, %prevState);
$TeamDeployedCount[%obj.team, bogypackDeployable]--;
remDSurface(%obj);
%obj.schedule(500, "delete");
fireBallExplode(%obj,1);
}
function DeployedEditorPack::Disassemble(%data,%plyr,%obj)
{
%obj.RevertPieces(true);
Parent::Disassemble(%data,%plyr,%obj);
}
//*********************************************\\
// Command Code *\\
//*********************************************\\
function ccEditor(%sender,%args)
{
%f = getWord(%args,0);
%f = strLwr(%f); //Convert To LowerCase
%f = stripChars(%f," "); //Strip spaces.
%pos = %sender.player.getMuzzlePoint($WeaponSlot);
%vec = %sender.player.getMuzzleVector($WeaponSlot);
%targetpos = vectoradd(%pos,vectorscale(%vec,100));
%obj = containerraycast(%pos,%targetpos,$typemasks::staticshapeobjecttype,%sender.player);
%obj = getword(%obj,0);
if (%f $="")
{
messageclient(%sender,'msgclient',"\c2No command specified, please type '/Editor Help' for a list of commands.");
return 1;
}
else if (!EvaluateFunction(%f))
{
messageclient(%sender,'msgclient','\c2Unknown command: %1.', %f);
return 1;
}
else if (%f $="help" || %f $="cmds")
{
messageclient(%sender,'msgclient',"\c2/Editor Select - Selects the device you're looking at.");
messageclient(%sender,'msgclient',"\c2/Editor DelObj - Removes the object you're looking at from your currently selected device.");
messageclient(%sender,'msgclient',"\c2/Editor List - If you own the device you're looking at, this command will list all pieces assigned to it.");
messageclient(%sender,'msgclient',"\c2/Editor Cloak - Adds the object you're looking at to your device's currently selected cloak list.");
messageclient(%sender,'msgclient',"\c2/Editor Fade - Adds the object you're looking at to your device's currently selected fade list.");
messageclient(%sender,'msgclient',"\c2/Editor Name <New Name> - Adds the object you're looking at to your currently selected device's fade list.");
messageclient(%sender,'msgclient',"\c2/Editor Scale <New Scale> - Adds the object you're looking at to your currently selected device's scale list.");
messageclient(%sender,'msgclient',"\c2/Editor Hide - Adds the object you're looking at to your currently selected device's fade list.");
messageclient(%sender,'msgclient',"\c2/Editor Rotate <Rotation> - Adds the object you're looking at to your currently selected device's rotation list.");
if ($Editor::Debris::Enabled)
messageclient(%sender,'msgclient',"\c2/Editor Debris <Human-Bioderm> <TimeMS> - Adds the object you're looking at to your currently selected device's debris list.");
return 1;
}
else if (!%obj)
{
messageclient(%sender,'msgclient',"\c2Unable to find an object.");
return 1;
}
else if (IsObject(%obj) && IsValidClass(%obj.getclassname()))
{
messageclient(%sender,'msgclient','\c2Invalid object. Error: Invalid Class - %1.', %obj.getclassname());
return 1;
}
else if (%f $="delobj")
{
ProcessDelObj(%sender,%obj,%args);
return 1;
}
else if (%f $="list")
{
ProcessList(%sender,%obj);
return 1;
}
else if (%f $="size")
{
ProcessSize(%sender,%obj);
return 1;
}
else if (%f $="addobj")
{
ProcessAddObj(%sender,%obj);
return 1;
}
else if (%f $="debris")
{
ProcessDebris(%sender,%obj,%args);
return 1;
}
else if (%f $="fade")
{
ProcessFade(%sender,%obj,%args);
return 1;
}
else if (%f $="cloak")
{
ProcessCloak(%sender,%obj,%args);
return 1;
}
else if (%f $="scale")
{
ProcessScale(%sender,%obj,%args);
return 1;
}
else if (%f $="rotate")
{
ProcessRotate(%sender,%obj,%args);
return 1;
}
else if (%f $="name")
{
ProcessName(%sender,%obj,%args);
return 1;
}
else if (%f $="hide")
{
ProcessHide(%sender,%obj,%args);
return 1;
}
else
{
ProcessEditorRequest(%sender,%obj,%f);
return 1;
}
messageclient(%sender,'msgclient',"\c2Piece Editor: An unknown error has occurred. Code: 1"); //Shouldn't see this
return 1;
}
function ProcessList(%sender,%obj)
{
if (IsObject(%obj))
{
%count = %obj.slotcount;
%count = %count - 1;
if (%count > 1)
{
for (%i = 0; %i < %count; %i++)
{
%slotobj = %obj.slot[%i];
if (IsObject(%slotobj))
{
messageclient(%sender,'msgclient','\c2%1: %2 - %3', %i, %slotobj, %slotobj.getclassname());
}
else
{
messageclient(%sender,'msgclient','\c2%1: %2 - Does not exist. You should not see this error. Code: 2.', %i, %slotobj);
}
}
}
else
{
messageclient(%sender,'msgclient','\c2This device has an invalid slot count: %1. You should not see this error. Code: 3.', %count);
return;
}
}
else
{
messageclient(%sender,'msgclient','\c2Object %1 does not exist. You should not see this error. Code: 4', %obj);
return;
}
}
function ProcessEditorRequest(%sender,%obj,%f)
{
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2This editor pack is not yours!");
return;
}
if (%obj.getdatablock().getname() !$="DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to edit devices!");
return;
}
if (%f $="select" || %f $="selecteditor" || %f = "seledit")
{
%sender.currentedit = %obj;
%obj.cloakAnim(500);
messageclient(%sender,'msgclient',"\c2Current device set.");
return;
}
}
function ProcessAddObj(%sender,%obj)
{
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2This object is not yours!");
return;
}
if (!IsObject(%Sender.CurrentEdit))
{
messageclient(%sender,'msgclient',"\c2No device selected! You can use '/Editor Select' while pointing at a device to select it.");
return;
}
if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to edit Piece Manipulating Devices!");
return;
}
%Slots = %sender.currentedit.slotcount;
%edit = %sender.currentedit;
for (%i=0;%i<%slots;%i++)
{
if (%edit.slot[%i] $="")
{
%edit.slot[%i] = %obj;
%edit.slotcount++;
messageclient(%sender,'msgclient','\c2Object has been added to your current device. (%1)', %i);
%obj.slot = %i;
%obj.editor = true;
%obj.cloakAnim(500);
return;
}
}
}
function ProcessDelObj(%sender,%obj,%args)
{
%edit = %sender.currentedit;
if (!IsObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2Not your object!");
return;
}
if (!%obj.editor)
{
messageclient(%sender,'msgclient',"\c2This object is not bound to a device!");
return;
}
messageclient(%sender,'msgclient','\c2Object deleted from your currently selected device. (%1)', %edit.slot[%obj.slot]);
%edit.slot[%obj.slot] = "";
%obj.slot = "";
%obj.editor = false;
Revert(%obj,"all");
%obj.cloakAnim(500);
if (%edit.slotcount > 1)
%edit.slotcount--;
}
function ProcessRotate(%sender,%obj,%args)
{
%edit = %sender.currentedit;
%args = GetWords(%args, 1);
if (!IsObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2Not your object!");
return;
}
if (%obj.istrotate)
{
Revert(%obj,"rotation");
messageclient(%sender,'msgclient','\c2Object has been removed from your current device\'s rotation list.');
%obj.cloakAnim(500);
}
else
{
if (%args $= "")
{
messageclient(%sender,'msgclient','\c2No rotation angle set.');
return 1;
}
else if (%args $= "L")
{
return 1;
}
else
{
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.istrotate = true;
%obj.erotation = %args;
%obj.oldrotation = %obj.getRotation();
%obj.iserotated = false;
%obj.cloakAnim(500);
messageclient(%sender,'msgclient','\c2Object will be rotated with the following angles: %1.', %args);
}
}
}
function ProcessScale(%sender,%obj,%args)
{
%scale = getwords(%args,1);
%edit = %sender.currentedit;
if (!IsObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
else if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2Not your object!");
return;
}
else if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to scale devices!");
return;
}
else if (%scale $="" && %obj.istscale == false)
{
messageclient(%sender,'msgclient',"\c2No scale specified.");
return;
}
else if (getword(%scale,0) > $Editor::MaxScale["X"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The X axis is too big. Max: %2', %scale, $Editor::MaxScale["X"]);
return;
}
else if (getword(%scale,1) > $Editor::MaxScale["Y"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Y axis is too big. Max: %2', %scale, $Editor::MaxScale["Y"]);
return;
}
else if (getword(%scale,2) > $Editor::MaxScale["Z"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Z axis is too big. Max: %2', %scale,$Editor::MaxScale["Z"]);
return;
}
else if (getword(%scale,0) < $Editor::MinScale["X"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The X axis is too small. Min: %2', %scale, $Editor::MinScale["X"]);
return;
}
else if (getword(%scale,1) < $Editor::MinScale["Y"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The scale %1 is invalid. The Y axis is too small. Min:', %scale, $Editor::MinScale["Y"]);
return;
}
else if (getword(%scale,2) < $Editor::MinScale["Z"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The scale %1is invalid. The Z axis is too small. Min:', %scale, $Editor::MinScale["Z"]);
return;
}
else
{
%scale = CheckScale(%scale);
if (!%obj.istscale)
{
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.istscale = true;
%obj.isescaled = false;
messageclient(%sender,'msgclient','\c2Object has been added to your currently selected device\'s scale list. This object will be scaled to %1.', %scale);
%obj.escale = %scale;
%obj.oldscale = %obj.getscale();
%obj.cloakAnim(500);
return;
}
else
{
Revert(%obj,"scale");
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's scale list. Original scale restored.");
%obj.setscale(%obj.oldscale);
%obj.cloakAnim(500);
}
}
}
function ProcessSize(%sender,%obj,%args)
{
%scale = getwords(%args,1);
%edit = %sender.currentedit;
if (!IsObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
else if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2Not your object!");
return;
}
else if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to size devices!");
return;
}
else if (%scale $="" && %obj.istscale == false)
{
messageclient(%sender,'msgclient',"\c2No size specified.");
return;
}
else if (getword(%scale,0) > $Editor::MaxScale["X"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The size %1 is invalid. The X axis is too big. Max: %2', %scale, $Editor::MaxScale["X"]);
return;
}
else if (getword(%scale,1) > $Editor::MaxScale["Y"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The size %1 is invalid. The Y axis is too big. Max: %2', %scale, $Editor::MaxScale["Y"]);
return;
}
else if (getword(%scale,2) > $Editor::MaxScale["Z"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The size %1 is invalid. The Z axis is too big. Max: %2', %scale,$Editor::MaxScale["Z"]);
return;
}
else if (getword(%scale,0) < $Editor::MinScale["X"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The size %1 is invalid. The X axis is too small. Min: %2', %scale, $Editor::MinScale["X"]);
return;
}
else if (getword(%scale,1) < $Editor::MinScale["Y"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The size %1 is invalid. The Y axis is too small. Min:', %scale, $Editor::MinScale["Y"]);
return;
}
else if (getword(%scale,2) < $Editor::MinScale["Z"] && %obj.istscale == false)
{
messageclient(%sender,'msgclient','\c2The size %1is invalid. The Z axis is too small. Min:', %scale, $Editor::MinScale["Z"]);
return;
}
else
{
%scale = CheckScale(%scale);
if (!%obj.istsize)
{
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.istsize = true;
%obj.isesized = false;
messageclient(%sender,'msgclient','\c2Object has been added to your currently selected device\'s size list. This object will be scaled to %1.', %scale);
%obj.esize = %scale;
%obj.oldsize = %obj.getrealsize();
%obj.cloakAnim(500);
return;
}
else
{
Revert(%obj,"scale");
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's size list. Original scale restored.");
%obj.setscale(%obj.oldsize);
%obj.cloakAnim(500);
}
}
}
function ProcessFade(%sender,%obj,%args)
{
%edit = %sender.currentedit;
if (!isObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2This object is not yours!");
return;
}
if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to fade Piece Manipulating Devices!");
return;
}
if (!%obj.istfade)
{
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.istfade = true;
%obj.isefaded = false;
%obj.setcloaked(true);
%obj.cloakAnim(500);
return;
}
else
{
Revert(%obj,"fade");
%obj.cloakAnim(500);
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's fade list.");
}
}
function ProcessDebris(%sender,%obj,%args)
{
%edit = %sender.currentedit;
%deb = GetWord(%args, 0);
%debris = GetWord(%args, 1);
%timems = GetWord(%args, 2);
if (!$Editor::Debris::Enabled)
{
messageclient(%sender,'msgclient','\c2Unknown command: %1.', %deb);
return 1;
}
if (!isObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2This object is not yours!");
return;
}
if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to edit Piece Manipulating Devices!");
return;
}
if (%obj.istdebris)
{
Revert(%obj,"debris");
$Editor::Debris::Count--;
%obj.cloakAnim(500);
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's debris list.");
return 1;
}
if (%debris $= "Human" || %debris $= "Bioderm")
{
if (!%obj.istdebris)
{
if ($Editor::Debris::Count > $Editor::Debris::Max)
{
messageclient(%sender,'msgclient','\c2Unable to create debtis emitter, reached max. Max: %1', $Editor::Debris::Max);
return 1;
}
if (%timeMS $= "")
{
messageclient(%sender,'msgclient',"\c2No time in milliseconds specified.");
return 1;
}
if (%timeMS < $Editor::Debris::MinMS)
{
messageclient(%sender,'msgclient',"\c2Invalid time in milliseconds, too low: "@%timeMS@". Minimum is 100.");
return 1;
}
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.istdebris = true;
%obj.isedebris = false;
%obj.debristime = %timems;
%obj.isedebris = false;
%obj.debris = %debris;
%obj.cloakAnim(500);
$Editor::Debris::Count++;
messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's debris list. Type: "@%debris@".");
return;
}
}
else
{
messageclient(%sender,'msgclient',"\c2Invalid debris type: "@%debris@". Available are: Human and Bioderm.");
}
}
function ProcessHide(%sender,%obj,%args)
{
%edit = %sender.currentedit;
if (!isObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2This object is not yours!");
return;
}
if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to fade devices!");
return;
}
if (!%obj.isthide)
{
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.isthide = true;
%obj.isehidden = false;
messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's hide list.");
%obj.cloakAnim(500);
return;
}
else
{
Revert(%obj,"hide");
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's hide list.");
%obj.cloakAnim(500);
}
}
function ProcessCloak(%sender,%obj,%args)
{
%edit = %sender.currentedit;
if (!isObject(%edit))
{
messageclient(%sender,'msgclient',"\c2No device selected!");
return;
}
if (%obj.owner!=%sender && %obj.owner !$=""){
messageclient(%sender,'msgclient',"\c2This object is not yours!");
return;
}
if (%obj.getdatablock().getname() $= "DeployedEditorPack")
{
messageclient(%sender,'msgclient',"\c2Unable to cloak devices!");
return;
}
if (!%obj.istcloak)
{
if (!%obj.editor)
ProcessAddObj(%Sender,%obj);
%obj.istcloak = true;
%obj.isecloaked = false;
messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's cloak list.");
%obj.cloakAnim(500);
return;
}
else
{
Revert(%obj,"cloak");
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's cloak list.");
%obj.cloakAnim(500);
}
}
function ProcessName(%sender,%obj,%args)
{
%edit = %sender.currentedit;
%name = getwords(%args,1);
if (!isObject(%edit)) {
messageclient(%sender,'msgclient',"\c2No device selected!");
return 1;
}
else if (%obj.owner!=%sender && %obj.owner !$="") {
messageclient(%sender,'msgclient',"\c2This object is not yours!");
return 1;
}
else if (%obj.getdatablock().getname() $= "DeployedEditorPack") {
messageclient(%sender,'msgclient',"\c2Unable to name devices!");
return 1;
}
else if (!%obj.istname) {
if (!%obj.editor) {
ProcessAddObj(%Sender,%obj);
}
%obj.istname = true;
%obj.isenamed = false;
//<--Must Be defined-->\\
%db = %obj.GetDataBlock();
if (%obj.nametag !$= "")
%obj.oldname = %obj.nametag;
else if (%db.targetNameTag !$= "" && %db.targetTypeTag !$= "")
%obj.oldname = GetTaggedString(%obj.getdatablock().targetNameTag SPC %obj.getdatablock().targetTypeTag);
else //Gotta fall back on the target name
%obj.oldname = GetTaggedString(GetTargetName(%obj.target));
%obj.ename = %name;
messageclient(%sender,'msgclient',"\c2Object has been added to your currently selected device's name list. This object will be named to: "@%name@"");
%obj.cloakAnim(500);
return 1;
}
else if (%obj.istname) {
Revert(%obj,"name");
messageclient(%sender,'msgclient',"\c2Object has been removed from your currently selected device's cloak list. Old name restored.");
%obj.cloakAnim(500);
return 1;
}
else {
messageclient(%sender,'msgclient',"\c2An unknown error has occured. Code 5:");
return 1;
}
}
//*********************************************\\
// PERFORMANCE CODE *\\
//*********************************************\\
function EditorPerform(%obj)
{
PerformCloak(%obj);
PerformFade(%obj);
PerformScale(%obj);
PerformHide(%obj);
PerformName(%obj);
PerformRotate(%obj);
PerformSize(%obj);
PerformDebris(%obj);
}
function PerformCloak(%obj)
{
if (!IsObject(%obj))
return;
%c = %obj.slotcount;
%c++;
for (%i=0;%i<%c;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (!%object.istcloak) //IsTFade = Is To Fade
%object.isecloaked = true; //To Make The System Think It's Already Cloaked
if (%object.isecloaked)
{
%object.setcloaked(false);
%object.isecloaked = false;
}
else
{
schedule(510,0,"SetCloaked",%object,true); //Somehow Fixed The Cloaking Problem
%object.isecloaked = true;
}
}
}
function PerformFade(%obj)
{
if (!IsObject(%obj))
return;
%c = %obj.slotcount;
%c = %c++;
for (%i=0;%i<%c;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (!%object.istfade) //IsTFade = Is To Fade
%object.isefaded = true; //To Make The System Think It's Already Faded
if (%object.isefaded)
{
%object.startfade(1,0,0);
%object.isefaded= false;
}
else
{
%object.cloakAnim(500);
schedule(510,0,"fade",%object);
%object.isefaded = true;
}
}
}
function PerformHide(%obj)
{
if (!IsObject(%obj))
return;
for (%i=0;%i<%obj.slotcount;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (!%object.isthide) //IsTFade = Is To Fade
%object.isehidden = true; //To Make The System Think It's Already Hidden
if (%object.isehidden)
{
%object.hide(0);
%object.isehidden= false;
}
else
{
%object.cloakAnim(500);
schedule(510,0,"Hide",%object);
%object.isehidden = true;
}
}
}
function PerformDebris(%obj)
{
if (!$Editor::Debris::Enabled)
return;
if (!IsObject(%obj))
return;
for (%i=0;%i<%obj.slotcount;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (%object.istdebris)
{
if (%object.isedebris)
{
%object.isedebris= false;
%object.debrisemitter.delete();
}
else
{
%object.isedebris = true;
PerformDebrisLoop(%object);
}
}
}
}
function PerformDebrisLoop(%obj)
{
cancel(%obj.debrisloop);
if (!%obj.isedebris || !$Editor::Debris::Enabled)
{
if (IsObject(%obj.debrisemitter))
%obj.debrisemitter.delete();
%obj.debrisemitter = "";
if (!$Editor::Debris::Enabled)
{
$Editor::Debris::Count--;
%obj.istdebris = false;
%obj.isedebris = false;
%obj.debristime = "";
%obj.isedebris = false;
%obj.debris = "";
}
return;
}
if (!IsObject(%obj.debrisemitter))
{
if (%obj.debris $= "Human")
%obj.debrisemitter = new player(){
position = %obj.gettransform();
Datablock = "LightMaleHumanArmor";
Scale = "0 0 0";
Obj = %obj;
};
else
%obj.debrisemitter = new player(){
position = %obj.gettransform();
Datablock = "LightMaleBiodermArmor";
Scale = "0 0 0";
Obj = %obj;
};
%obj.debrisemitter.startfade(1,0,1);
%obj.debrisemitter.setmovestate(true);
}
%obj.debrisemitter.blowup();
%obj.debrisloop = schedule(%obj.debristime,0,"PerformDebrisLoop",%obj);
}
function PerformScale(%obj)
{
if (!IsObject(%obj))
return;
%c = %obj.slotcount;
%c = %c++;
for (%i=0;%i<%c;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (!%object.istscale){ //IsTFade = Is To Fade
%object.isescaled = true; //To Make The System Think It's Already Scaled
%object.oldscale = %object.getscale();
}
if (%object.isescaled)
{
%object.setscale(%object.oldscale);
%object.cloakAnim(500);
%object.isescaled= false;
}
else
{
%object.setscale(%object.escale);
%object.cloakAnim(500);
%object.isescaled = true;
}
}
}
function PerformSize(%obj)
{
if (!IsObject(%obj))
return;
%c = %obj.slotcount;
%c = %c++;
for (%i=0;%i<%c;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (!%object.istsize){ //IsTFade = Is To Fade
%object.isesized = true; //To Make The System Think It's Already Scaled
%object.oldsize = %object.getrealsize();
}
if (%object.isesized)
{
%object.setrealsize(%object.oldsize);
%object.cloakAnim(500);
%object.isescaled= false;
}
else
{
%object.setrealsize(%object.escale);
%object.cloakAnim(500);
%object.isesized = true;
}
}
}
function PerformRotate(%obj)
{
if (!IsObject(%obj))
return;
%c = %obj.slotcount;
%c = %c++;
for (%i=0;%i<%c;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (%object.istrotate)
{
%object.cloakAnim(500);
if (%object.iserotated)
{
%object.iserotated = false;
%object.setrotation(%object.oldrotation);
}
else
{
%object.iserotated = true;
%object.setrotation(%object.erotation);
}
}
}
}
function PerformName(%obj)
{
if (!IsObject(%obj))
return;
if (!%obj.isTName) //Idiotic Console Error Fix
return;
%c = %obj.slotcount;
%c = %c++;
for (%i=0;%i<%c;%i++)
{
%object = %obj.slot[%i];
if (!IsObject(%Object))
return;
if (!%object.istname){ //IsTFade = Is To Fade
%object.isenamed = true; //To Make The System Think It's Already Scaled
if (%object.nametag !$="")
%object.oldname = %object.nametag;
else
%object.oldname = %object.getdatablock().targetNameTag;
}
if (%object.isenamed)
{
%object.nametag = %obj.oldname;
setTargetName(%object.target,addTaggedString("\c6"@%object.oldname@""));
%object.isenamed = false;
}
else
{
%object.nametag = %object.ename;
setTargetName(%object.target,addTaggedString("\c6"@%object.ename@""));
%object.isenamed = true;
}
}
}
//*********************************************\\
// MISC. CODE *\\
//*********************************************\\
function Hide(%obj)
{
%obj.hide(1);
}
function fade(%obj)
{
%obj.startfade(1,0,1);
}
function EvaluateFunction(%f) //To Eval The Command
{
if (%f $="addobj" || %f $= "selecteditor" || %f $="select" || %f $="delobj" || %f $="help" || %f $="cmds" || %f $="fade" || %f $="cloak" || %f $="scale" || %f $="hide" || %f $="name" || %f $="list" || %f $="rotate" || %f $="debris" || %f $="size")
return true;
else
return false;
}
function IsMatch(%string1,%string2)
{
%string1 = StrLwr(%string1);
%string2 = StrLwr(%string2);
if (%string1 $=%string2)
return true;
else
return false;
}
function CheckScale(%scale) //Evals The Scale For Any Missing Args, If So, Puts A 1 In The Blank Slot
{
if (getword(%scale,0) $="")
%scale = "1" SPC getWord(%scale,1) SPC getWord(%scale,2);
if (getword(%scale,1) $="")
%scale = getWord(%scale,0) SPC "1" SPC getWord(%scale,2);
if (getword(%scale,2) $="")
%scale = getWord(%scale,0) SPC getWord(%scale,1) SPC "1";
return %scale;
}
function IsValidClass(%class)
{
if (%class $="Spine" || %class $="Generator" || %class $="Switch" || %class $="WWall" || %class $="Wall" || %class $="MSpine" || %class $="Station" || %class $="Sensor" || %class $="DeployedTurret" || %class $="LogoProjector" || %class $="DeployedLightBase" || %class $="Tripwire" || %class $="Teleport" || %class $="Jumpad" || %class $="Tree" || %class $="Crate" || %class $="GravityField")
return true;
else
return false;
}
function StaticShape::RevertPieces(%obj,%reset){ return RevertPieces(%obj,%reset); }
function RevertPieces(%obj)
{
if (!%obj.getDataBlock().getName() $="DeployedEditorPack")
return;
%count = %obj.slotcount;
%count = %count - 1;
for (%i = 0; %i < %count; %i++)
{
%slotobj = %obj.slot[%i];
if (%reset)
{
%slotObj.slot = "";
%slotObj.editor = false;
%obj.slot[%i] = ""; //Nada..
}
if (%slotobj.istrotate)
{
%slotobj.erotation = "";
%slotobj.setrotation(%slotobj.oldrotation);
if (%reset)
%slotObj.isTRotate = false;
}
else if (%slotobj.istscale)
{
%slotobj.isescaled = false;
%slotobj.escale = "";
%slotobj.setscale(%slotobj.oldscale);
if (%reset)
%slotObj.isTScale = false;
}
else if (%slotobj.istsize)
{
%slotobj.isesized = false;
%slotobj.setscale(%slotobj.oldsize);
if (%reset)
%slotObj.isTSize = false;
}
else if (%slotobj.istfade)
{
%slotobj.isefaded = false;
%slotobj.startfade(0,0,0);
if (%reset)
%slotObj.isTFade = false;
}
else if (%slotobj.istdebris)
{
%slotobj.isedebris = false;
$Editor::Debris::Count--;
if (%reset)
%slotObj.isDebris = false;
}
else if (%slotobj.isthide)
{
%slotobj.isehidden = false;
%slotobj.hide(0);
if (%reset)
%slotObj.isTHide = false;
}
else if (%slotobj.istcloak)
{
%slotobj.isecloaked = false;
%slotobj.setcloaked(0);
if (%reset)
%slotObj.isTCloak = false;
}
%slotObj.cloakAnim(500);
}
return %obj;
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSLF.Record
{
using System;
using System.IO;
using NPOI.Util;
using System.Text;
/**
* An atom record that specifies the animation information for a shape.
*
* @author Yegor Kozlov
*/
public class AnimationInfoAtom : RecordAtom
{
/**
* whether the animation plays in the reverse direction
*/
public static int Reverse = 1;
/**
* whether the animation starts automatically
*/
public static int Automatic = 4;
/**
* whether the animation has an associated sound
*/
public static int Sound = 16;
/**
* whether all playing sounds are stopped when this animation begins
*/
public static int StopSound = 64;
/**
* whether an associated sound, media or action verb is activated when the shape is clicked.
*/
public static int Play = 256;
/**
* specifies that the animation, while playing, stops other slide show actions.
*/
public static int Synchronous = 1024;
/**
* whether the shape is hidden while the animation is not playing
*/
public static int Hide = 4096;
/**
* whether the background of the shape is animated
*/
public static int AnimateBg = 16384;
/**
* Record header.
*/
private byte[] _header;
/**
* record data
*/
private byte[] _recdata;
/**
* Constructs a brand new link related atom record.
*/
public AnimationInfoAtom()
{
_recdata = new byte[28];
_header = new byte[8];
LittleEndian.PutShort(_header, 0, (short)0x01);
LittleEndian.PutShort(_header, 2, (short)RecordType);
LittleEndian.PutInt(_header, 4, _recdata.Length);
}
/**
* Constructs the link related atom record from its
* source data.
*
* @param source the source data as a byte array.
* @param start the start offset into the byte array.
* @param len the length of the slice in the byte array.
*/
public AnimationInfoAtom(byte[] source, int start, int len)
{
// Get the header
_header = new byte[8];
Array.Copy(source, start, _header, 0, 8);
// Grab the record data
_recdata = new byte[len - 8];
Array.Copy(source, start + 8, _recdata, 0, len - 8);
}
/**
* Gets the record type.
* @return the record type.
*/
public override long RecordType
{
get
{
return RecordTypes.AnimationInfoAtom.typeID;
}
}
/**
* Write the contents of the record back, so it can be written
* to disk
*
* @param out the output stream to write to.
* @throws java.io.IOException if an error occurs.
*/
public override void WriteOut(Stream out1)
{
out1.Write(_header,(int)out1.Position,_header.Length);
out1.Write(_recdata, (int)out1.Position, _recdata.Length);
}
/**
* A rgb structure that specifies a color for the dim effect after the animation is complete.
*
* @return color for the dim effect after the animation is complete
*/
public int DimColor
{
get
{
return LittleEndian.GetInt(_recdata, 0);
}
set
{
LittleEndian.PutInt(_recdata, 0, value);
}
}
/**
* A bit mask specifying options for displaying headers and footers
*
* @return A bit mask specifying options for displaying headers and footers
*/
public int Mask
{
get
{
return LittleEndian.GetInt(_recdata, 4);
}
set
{
LittleEndian.PutInt(_recdata, 4,value);
}
}
/**
* @param bit the bit to check
* @return whether the specified flag is set
*/
public bool GetFlag(int bit)
{
return (Mask & bit) != 0;
}
/**
* @param bit the bit to set
* @param value whether the specified bit is set
*/
public void SetFlag(int bit, bool value)
{
int mask = Mask;
if (value) mask |= bit;
else mask &= ~bit;
Mask = (mask);
}
/**
* A 4-byte unsigned integer that specifies a reference to a sound
* in the SoundCollectionContainer record to locate the embedded audio
*
* @return reference to a sound
*/
public int SoundIdRef
{
get
{
return LittleEndian.GetInt(_recdata, 8);
}
set
{
LittleEndian.PutInt(_recdata, 8, value);
}
}
/**
* A signed integer that specifies the delay time, in milliseconds, before the animation starts to play.
* If {@link #Automatic} is 0x1, this value MUST be greater than or equal to 0; otherwise, this field MUST be ignored.
*/
public int DelayTime
{
get
{
return LittleEndian.GetInt(_recdata, 12);
}
set
{
LittleEndian.PutInt(_recdata, 12, value);
}
}
/**
* A signed integer that specifies the order of the animation in the slide.
* It MUST be greater than or equal to -2. The value -2 specifies that this animation follows the order of
* the corresponding placeholder shape on the main master slide or title master slide.
* The value -1 SHOULD NOT <105> be used.
*/
public int OrderID
{
get
{
return LittleEndian.GetInt(_recdata, 16);
}
set
{
LittleEndian.PutInt(_recdata, 16, value);
}
}
/**
* An unsigned integer that specifies the number of slides that this animation continues playing.
* This field is utilized only in conjunction with media.
* The value 0xFFFFFFFF specifies that the animation plays for one slide.
*/
public int SlideCount
{
get
{
return LittleEndian.GetInt(_recdata, 18);
}
set
{
LittleEndian.PutInt(_recdata, 18, value);
}
}
public override String ToString()
{
StringBuilder buf = new StringBuilder();
buf.Append("AnimationInfoAtom\n");
buf.Append("\tDimColor: " + DimColor + "\n");
int mask = Mask;
buf.Append("\tMask: " + mask + ", 0x" + StringUtil.ToHexString(mask) + "\n");
buf.Append("\t Reverse: " + GetFlag(Reverse) + "\n");
buf.Append("\t Automatic: " + GetFlag(Automatic) + "\n");
buf.Append("\t Sound: " + GetFlag(Sound) + "\n");
buf.Append("\t StopSound: " + GetFlag(StopSound) + "\n");
buf.Append("\t Play: " + GetFlag(Play) + "\n");
buf.Append("\t Synchronous: " + GetFlag(Synchronous) + "\n");
buf.Append("\t Hide: " + GetFlag(Hide) + "\n");
buf.Append("\t AnimateBg: " + GetFlag(AnimateBg) + "\n");
buf.Append("\tSoundIdRef: " + SoundIdRef + "\n");
buf.Append("\tDelayTime: " + DelayTime + "\n");
buf.Append("\tOrderID: " + OrderID + "\n");
buf.Append("\tSlideCount: " + SlideCount + "\n");
return buf.ToString();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace RestClient.TestAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace ERY.EMath
{
[Serializable]
public class FunctionProcessor
{
private double mTolerance = 1e-10;
private int mMaxIterations = 100;
public delegate double FunctionOneVar(double x);
public delegate Complex FunctionComplexOneVar(double x);
public double Tolerance
{
get { return mTolerance; }
set { mTolerance = Math.Abs(value); }
}
public int MaxIterations
{
get { return mMaxIterations; }
set
{
if (value < 1)
throw new Exception("Error: MaxIterations must be positive!");
mMaxIterations = value;
}
}
#region --- Finding the point with a specified value ---
/// <summary>
/// Finds the root of the given function using the bisection algorithm.
/// </summary>
/// <param name="f">The function whose root we are supposed to find.</param>
/// <param name="low">The lower end of the range within to look for a root.</param>
/// <param name="high">The upper end of the range within to look for a root.</param>
/// <returns></returns>
public double RootByBisection(FunctionOneVar f, double low, double high)
{
return s_RootByBisection(f, low, high, mTolerance, mMaxIterations);
}
/// <summary>
/// Finds the point at which given function is at the given value, using the bisection algorithm.
/// </summary>
/// <param name="f">The function whose root we are supposed to find.</param>
/// <param name="low">The lower end of the range within to look for a root.</param>
/// <param name="high">The upper end of the range within to look for a root.</param>
/// <param name="value">The value to look for.</param>
/// <returns></returns>
public double ValueByBisection(FunctionOneVar f, double low, double high, double value)
{
mFunctionToCall = f;
mFunctionValue = value;
double retval = s_RootByBisection(pValueFunction, low, high, mTolerance, mMaxIterations);
mFunctionToCall = null;
mFunctionValue = 0;
return retval;
}
#region --- Temporary variables for ValueByBisection call ---
[NonSerialized] private FunctionOneVar mFunctionToCall;
[NonSerialized] private double mFunctionValue;
private double pValueFunction(double x)
{
return mFunctionToCall(x) - mFunctionValue;
}
#endregion
/// <summary>
/// Finds the root of a passed function. Returns the value of x for which f(x) = 0.
/// </summary>
/// <param name="f">The function whose root we are supposed to find.</param>
/// <param name="low">The lower end of the range within to look for a root.</param>
/// <param name="high">The upper end of the range within to look for a root.</param>
/// <param name="maxIterations">The maximum number of iterations in which to look.</param>
/// <param name="tolerance">The level of tolerance at which the result should differ from the
/// correct value. The actual value used is (tolerance * (f(high) - f(low) / 2)). </param>
/// <returns></returns>
public static double s_RootByBisection(FunctionOneVar f, double low, double high, double tolerance, int maxIterations)
{
double x = (low + high) / 2.0;
double f_val = f(x);
double f_low = f(low);
while (double.IsNaN(f_low))
{
low += (high - low) / 1000.0;
f_low = f(low);
}
double f_high = f(high);
while (double.IsNaN(f_high))
{
high -= (high - low) / 1000.0;
f_high = f(high);
}
double tol = Math.Abs(tolerance * (f_high - f_low) / 2);
if (f_low * f_high >= 0)
throw new Exception("Error: Range given is not guaranteed to bracket a zero.");
int nIterations = 0;
do
{
f_val = f(x);
if (f_val * f_low < 0)
{
high = x;
f_high = f_val;
}
else if (f_val * f_high < 0)
{
low = x;
f_low = f_val;
}
x = (low + high) / 2.0;
nIterations++;
} while (nIterations < maxIterations && Math.Abs(f_val) > tol) ;
return x;
}
#endregion
#region --- Finding the maximum or minimum ---
public double MinimumByBisection(FunctionOneVar f, double low, double high)
{
return s_MinimumByBisection(f, low, high, Tolerance, MaxIterations);
}
public static double s_MinimumByBisection(FunctionOneVar f, double x_low, double x_high, double tolerance, int maxIterations)
{
double x_center = (x_low + x_high) / 2.0;
double f_center = f(x_center);
double f_low = f(x_low);
double f_high = f(x_high);
double tol = tolerance * (f_high - f_low) / 2;
int nIterations = 0;
// check to see if we've failed to bracket a minimum.
while (nIterations < maxIterations && f_center > f_low)
{
x_high = x_center;
f_high = f_center;
x_center = (x_low + x_high) / 2.0;
f_center = f(x_center);
nIterations++;
}
while (nIterations < maxIterations && f_center > f_high)
{
x_low = x_center;
f_low = f_center;
x_center = (x_low + x_high) / 2.0;
f_center = f(x_center);
nIterations++;
}
do
{
// examine right bracket
double x = (x_high + x_center) / 2;
double f_val = f(x);
if (f_center < f_val)
{
x_high = x;
f_high = f_val;
}
else
{
x_low = x_center;
x_center = x;
f_low = f_center;
f_center = f_val;
}
// examine left bracket
x = (x_low + x_center) / 2;
f_val = f(x);
if (f_center < f_val)
{
x_low = x;
f_low = f_val;
}
else
{
x_high = x_center;
x_center = x;
f_high = f_center;
f_center = f_val;
}
nIterations++;
} while (nIterations < maxIterations && Math.Abs(f_high - f_low) > tol);
return x_center;
}
#endregion
#region --- Interpolation ---
public double Interpolate(double[] x, double[] y, double newx)
{
return s_Interpolate(x, y, newx);
}
public static double s_Interpolate(double[] x, double[] y, double newx)
{
if (x.Length != y.Length)
throw new ArgumentException("Error: The two arrays must be the same length!");
if (x.Length == 0)
throw new ArgumentException("Error: The arrays must have something in them!");
// make sure x values are monotonic
int sign = 0;
for (int i = 0; i < x.Length - 1; i++)
{
if (x[i] < x[i + 1])
{
if (sign == 0)
sign = 1;
else if (sign == -1)
throw new ArgumentException("Error: The x values must be monotonic!");
}
else if (x[i] > x[i + 1])
{
if (sign == 0)
sign = -1;
else if (sign == 1)
throw new ArgumentException("Error: The x values must be monotonic!");
}
}
if (sign == -1)
{
List<double> newxList = new List<double>();
List<double> newyList = new List<double>();
for (int i = x.Length - 1; i >= 0; i--)
{
newxList.Add(x[i]);
newyList.Add(y[i]);
}
return s_Interpolate(newxList.ToArray(), newyList.ToArray(), newx);
}
// bracket the value in n, using bisection.
int left = 0;
int right = x.Length;
int current = x.Length / 2;
do
{
double current_x = x[current];
if (current_x > newx)
{
right = current;
}
else if (current_x < newx)
{
left = current;
}
else
break;
current = (left + right) / 2;
if (current == 0)
break;
else if (current == x.Length - 1)
break;
// this condition should read
// until current_n is below n and current+1_n is above n.
} while (!(x[current] <= newx && x[current + 1] >= newx));
if (x[current] == newx)
{
return y[current];
}
else if (x[current + 1] == newx)
return y[current + 1];
// now we need to linearly interpolate, because neither one is the exact value we want.
double left_x = x[current];
double right_x = x[current + 1];
double left_y = y[current];
double right_y = y[current + 1];
if (double.IsNaN(left_y) || double.IsInfinity(left_y))
return right_y;
else if (double.IsNaN(right_y) || double.IsInfinity(right_y))
return left_y;
double result = s_TwoPointInterpolate(newx, left_x, left_y, right_x, right_y);
if (newx > left_x && newx < right_x)
{
// make sure the result is between the two endpoints.
System.Diagnostics.Debug.Assert(Math.Min(left_y, right_y) <= result && result <= Math.Max(left_y, right_y));
}
return result;
}
public static double s_TwoPointInterpolate(double newx, double left_x, double left_y, double right_x, double right_y)
{
double rightFactor = (newx - left_x) / (right_x - left_x);
return left_y + rightFactor * (right_y - left_y);
}
#endregion
#region --- Calculus ---
public static double Derivative(FunctionOneVar f, double x, double step)
{
double val = f(x);
if (double.IsNaN(val) || double.IsInfinity(val))
return double.NaN;
double valRight = f(x + step);
double valLeft = f(x - step);
// if they're both NaN, we can't do anything.
if (double.IsNaN(valRight) && double.IsNaN(valLeft))
return double.NaN;
// if only one is NaN, we can still do a first order derivative.
else if (double.IsNaN(valLeft) || double.IsInfinity(valLeft))
{
valLeft = val;
return (valRight - valLeft) / step;
}
else if (double.IsNaN(valRight) || double.IsInfinity(valRight))
{
valRight = val;
return (valRight - valLeft) / step;
}
// wel, everything seems good here:
else
return (valRight - valLeft) / (2 * step);
}
public static double Integrate(FunctionOneVar f, double low, double high, int steps)
{
return IntegrateSimpsonsRule(f, low, high, steps);
//return IntegrateTrapezoidRule(f, low, high, steps);
}
private static double IntegrateSimpsonsRule(FunctionOneVar f, double low, double high, int steps)
{
double retval = 0;
double stepSize = (high - low) / (double)steps;
double leftVal = 0;
double midVal = 0;
double rightVal = 0;
leftVal = f(low);
if (steps % 2 == 1)
steps++;
for (int i = 2; i <= steps; i += 2)
{
double xmid = low + (i - 1) * stepSize;
double xright = low + i * stepSize;
midVal = f(xmid);
rightVal = f(xright);
retval += (leftVal + 4 * midVal + rightVal) * stepSize / 3.0;
leftVal = rightVal;
}
return retval;
}
private static double IntegrateTrapezoidRule(FunctionOneVar f, double low, double high, int steps)
{
double retval = 0;
double stepSize = (high - low) / (double)steps;
double leftVal = 0;
double rightVal = 0;
leftVal = f(low);
for (int i = 1; i <= steps; i++)
{
double x = low + i * stepSize;
rightVal = f(x);
retval += 0.5 * (rightVal + leftVal) * stepSize;
leftVal = rightVal;
}
return retval;
}
public static Complex IntegrateComplex(FunctionComplexOneVar f, double low, double high, int steps)
{
return IntegrateSimpsonsRule(f, low, high, steps);
//return IntegrateTrapezoidRule(f, low, high, steps);
}
private static Complex IntegrateSimpsonsRule(FunctionComplexOneVar f, double low, double high, int steps)
{
Complex retval = 0;
double stepSize = (high - low) / (double)steps;
Complex leftVal = 0;
Complex midVal = 0;
Complex rightVal = 0;
leftVal = f(low);
if (steps % 2 == 1)
steps++;
for (int i = 2; i <= steps; i += 2)
{
double xmid = low + (i - 1) * stepSize;
double xright = low + i * stepSize;
midVal = f(xmid);
rightVal = f(xright);
retval += (leftVal + 4 * midVal + rightVal) * stepSize / 3.0;
leftVal = rightVal;
}
return retval;
}
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Cci;
using System.Diagnostics;
using System.IO;
using System.Diagnostics.Contracts;
namespace CRASanitizer
{
class Program
{
static int Main(string[] args)
{
if (args.Length != 2)
{
Usage();
}
var contractAssembly = args[0];
var originalAssembly = args[1];
var checker = new Checker(Console.Out);
int result = checker.CheckSurface(contractAssembly, originalAssembly);
if (result != 0)
{
Console.WriteLine("{0} has {1} errors", contractAssembly, result);
}
return result;
}
private static void Usage()
{
Contract.Ensures(false);
Console.WriteLine("Usage: contract-assembly original-assembly");
Environment.Exit(-1);
}
}
public class Checker {
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.errorCount >= 0);
}
readonly SanitizerHostEnvironment host1;
readonly SanitizerHostEnvironment host2;
readonly NameTable nt;
readonly TextWriter tw;
int errorCount;
public Checker(TextWriter tw)
{
this.tw = tw;
this.nt = new NameTable();
this.host1 = new SanitizerHostEnvironment(nt);
this.host2 = new SanitizerHostEnvironment(nt);
}
public int CheckSurface(string contractAssemblyName, string originalAssemblyName)
{
Contract.Requires(originalAssemblyName != null);
Contract.Requires(contractAssemblyName != null);
IAssembly/*?*/ contractAssembly = host1.LoadUnitFrom(contractAssemblyName) as IAssembly;
if (contractAssembly == null || contractAssembly == Dummy.Assembly)
{
Error("{0} is not a PE file containing a CLR assembly, or an error occurred when loading it.", contractAssemblyName);
return Errors;
}
IAssembly/*?*/ originalAssembly = host2.LoadUnitFrom(originalAssemblyName) as IAssembly;
if (originalAssembly == null || originalAssembly == Dummy.Assembly)
{
Error("{0} is not a PE file containing a CLR assembly, or an error occurred when loading it.", originalAssemblyName);
return Errors;
}
if (Errors == 0)
{
CheckSurface(contractAssembly, originalAssembly);
}
return Errors;
}
void CheckSurface(IAssembly contractAssembly, IAssembly originalAssembly)
{
Contract.Requires(contractAssembly != null);
// Check each type in contract Assembly
foreach (var type in contractAssembly.GetAllTypes())
{
if (type is INestedTypeDefinition) continue; // visited during parent type
CheckSurface(type, originalAssembly);
}
}
static bool ExcludeTypeFromComparison(INamedTypeDefinition type, string name)
{
if (name == "<Module>") return true;
if (name.StartsWith("System.Diagnostics.Contracts")) return true;
if (IsContractClass(type.Attributes)) return true;
return false;
}
private static bool IsContractClass(IEnumerable<ICustomAttribute> attrs)
{
Contract.Requires(attrs != null);
return attrs.Any(attr => TypeHelper.GetTypeName(attr.Type) == "System.Diagnostics.Contracts.ContractClassForAttribute");
}
private static bool IsModel(IEnumerable<ICustomAttribute> attrs) {
Contract.Requires(attrs != null);
return attrs.Any(attr => TypeHelper.GetTypeName(attr.Type) == "System.Diagnostics.Contracts.ContractModelAttribute");
}
private static bool IsCompilerGeneratedType(IEnumerable<ICustomAttribute> attrs) {
Contract.Requires(attrs != null);
return attrs.Any(attr => TypeHelper.GetTypeName(attr.Type) == "System.Runtime.CompilerServices.CompilerGeneratedAttribute");
}
private void CheckSurface(INamedTypeDefinition type, IAssembly originalAssembly)
{
var typeName = TypeHelper.GetTypeName(type, NameFormattingOptions.UseGenericTypeNameSuffix);
if (ExcludeTypeFromComparison(type, typeName)) return;
var original = originalAssembly.GetCorresponding(type);
if (original != null)
{
CheckTypeSurface(type, original);
}
else
{
if (type.IsInterface && !TypeHelper.IsVisibleOutsideAssembly(type))
{
// Allow internal interfaces to be in our contract reference assemblies in order to get right virtual bits on some members.
Warning("Interface {0} only exists in contract reference assembly, but it is internal only, so allowed.", TypeHelper.GetTypeName(type));
}
else
{
Error("Type {0} is in contract assembly but not in original assembly", typeName);
}
}
}
void CheckTypeSurface(ITypeDefinition type, INamedTypeDefinition original)
{
Contract.Requires(type != null);
Contract.Requires(original != null);
var baseClassCount = IteratorHelper.EnumerableCount(type.BaseClasses);
var originalBaseClassCount = IteratorHelper.EnumerableCount(original.BaseClasses);
if (baseClassCount != originalBaseClassCount) {
Error("{0} has a different number of base classes in contract reference assembly.",
TypeHelper.GetTypeName(type));
} else if (0 < baseClassCount) {
var baseType = IteratorHelper.First(type.BaseClasses);
Contract.Assume(baseType != null);
var baseTypeName = TypeHelper.GetTypeName(baseType, NameFormattingOptions.UseGenericTypeNameSuffix);
var originalBaseType = IteratorHelper.First(original.BaseClasses);
Contract.Assume(originalBaseType != null);
var originalName = TypeHelper.GetTypeName(originalBaseType, NameFormattingOptions.UseGenericTypeNameSuffix);
if (!baseTypeName.Equals(originalName)) {
// Warning instead of Error because existing contract assemblies have lots of violations and it
// is a pain to chase each and every one down. Causes lots of new files/classes to be added for
// each base class.
this.Warning("{0} has a different base class in contract reference assembly. Should be {1} instead of {2}.",
TypeHelper.GetTypeName(type), originalName, baseTypeName);
}
}
foreach (var member in type.Members)
{
CheckSurface(member, original);
}
}
private void CheckSurface(ITypeDefinitionMember member, INamedTypeDefinition original)
{
Contract.Requires(original != null);
// find member in original
if (member is IFieldDefinition) {
var field = (IFieldDefinition)member;
if (!IsCompilerGeneratedType(field.Attributes)) {
// compiler generated types are closure implementations
// they are not going to match up.
CheckSurface(field, original.GetMembersNamed(field.Name, false));
}
}
else if (member is IMethodDefinition) {
var method = (IMethodDefinition)member;
if (!(IsCompilerGeneratedType(method.Attributes))){
// compiler generated types are closure implementations
// they are not going to match up.
CheckSurface(method, GetMethod(original, method));
}
}
else if (member is INestedTypeDefinition) {
var nested = (INestedTypeDefinition)member;
if (!IsCompilerGeneratedType(nested.Attributes)) {
// compiler generated types are closure implementations
// they are not going to match up.
CheckSurface(nested, original.NestedTypes);
}
}
else if (member is IPropertyDefinition) {
var nested = (IPropertyDefinition)member;
CheckSurface(nested, original.GetMembersNamed(nested.Name, false));
}
else if (member is IEventDefinition) {
var nested = (IEventDefinition)member;
CheckSurface(nested, original.GetMembersNamed(nested.Name, false));
}
// ignore other members?
}
private void CheckSurface(INestedTypeDefinition nested, IEnumerable<INestedTypeDefinition> nestedTypes)
{
Contract.Requires(nested != null);
Contract.Requires(nestedTypes != null);
foreach (INamedTypeDefinition candidate in nestedTypes)
{
if (candidate.Name.UniqueKey == nested.Name.UniqueKey)
{
CheckTypeSurface(nested, candidate);
return;
}
}
if (nested.IsInterface && !TypeHelper.IsVisibleOutsideAssembly(nested))
{
// Allow internal interfaces to be in our contract reference assemblies in order to get right virtual bits on some members.
Warning("Nested interface {0} only exists in contract reference assembly, but it is internal only, so allowed.", TypeHelper.GetTypeName(nested));
}
else
{
Error("Nested type {0} only exists in contract reference assembly", TypeHelper.GetTypeName(nested));
}
}
private void CheckSurface(IFieldDefinition field, IEnumerable<ITypeDefinitionMember> fields)
{
Contract.Requires(field != null);
foreach (var c in fields)
{
IFieldDefinition candidate = c as IFieldDefinition;
if (candidate == null) continue;
// What should we check?
if (candidate.Visibility != field.Visibility)
{
Error("Field {0} has different visibility: contract: {1}, original: {2}", MemberHelper.GetMemberSignature(field, NameFormattingOptions.None),
field.Visibility, candidate.Visibility);
}
if (candidate.IsStatic != field.IsStatic)
{
Error("Field {0} has different static bit: contract: {1}, original: {2}", MemberHelper.GetMemberSignature(field, NameFormattingOptions.None),
field.IsStatic, candidate.IsStatic);
}
if (candidate.IsCompileTimeConstant != field.IsCompileTimeConstant)
{
Error("Field {0} has different const bit: contract: {1}, original: {2} (compile-time constant has value: {3})",
MemberHelper.GetMemberSignature(field, NameFormattingOptions.None),
field.IsCompileTimeConstant,
candidate.IsCompileTimeConstant,
(candidate.IsCompileTimeConstant ? candidate.CompileTimeValue.Value.ToString() : field.CompileTimeValue.Value.ToString())
);
}
else if (candidate.IsCompileTimeConstant) // then both are
{
if (!candidate.CompileTimeValue.Value.Equals(field.CompileTimeValue.Value))
{
Warning("Field {0} has different values for const bit: contract: {1}, original: {2}",
MemberHelper.GetMemberSignature(field, NameFormattingOptions.None),
field.CompileTimeValue.Value.ToString(),
candidate.CompileTimeValue.Value.ToString()
);
}
}
return; // found
}
if (IsModel(field.Attributes)) return;
Error("Field {0} only appears in contract reference assembly", MemberHelper.GetMemberSignature(field, NameFormattingOptions.None));
}
private void CheckSurface(IPropertyDefinition property, IEnumerable<ITypeDefinitionMember> properties) {
Contract.Requires(property != null);
Contract.Requires(properties != null);
foreach (var c in properties) {
var candidate = c as IPropertyDefinition;
if (candidate == null) continue;
// What should we check?
if (candidate.Visibility != property.Visibility) {
Error("Property {0} has different visibility: contract: {1}, original: {2}", MemberHelper.GetMemberSignature(property, NameFormattingOptions.None),
property.Visibility, candidate.Visibility);
}
return; // found
}
if (IsModel(property.Attributes)) return;
if (property.Getter != null && IsImplementingInvisibleInterface(property.Getter.ResolvedMethod) ||
property.Setter != null && IsImplementingInvisibleInterface(property.Setter.ResolvedMethod))
{
Warning("Property {0} only appears in contract reference assembly, but is invisible, so okay", MemberHelper.GetMemberSignature(property, NameFormattingOptions.None));
}
else
{
Error("Property {0} only appears in contract reference assembly", MemberHelper.GetMemberSignature(property, NameFormattingOptions.None));
}
}
private bool IsImplementingInvisibleInterface(IMethodDefinition method)
{
if (MemberHelper.IsVisibleOutsideAssembly(method)) return false;
foreach (var bm in MemberHelper.GetExplicitlyOverriddenMethods(method))
{
var containing = bm.ContainingType;
var unitref = TypeHelper.GetDefiningUnitReference(containing);
if (UnitHelper.UnitsAreEquivalent(unitref, TypeHelper.GetDefiningUnitReference(method.ContainingType)))
{
var instance = containing as IGenericTypeInstanceReference;
if (instance != null) { containing = instance.GenericType; }
var spec = containing as ISpecializedNestedTypeReference;
if (spec != null) { containing = spec.UnspecializedVersion; }
var resolved = containing.ResolvedType;
if (resolved.IsInterface && !TypeHelper.IsVisibleOutsideAssembly(resolved))
{
return true;
}
}
}
return false;
}
private void CheckSurface(IEventDefinition Event, IEnumerable<ITypeDefinitionMember> events) {
Contract.Requires(Event != null);
Contract.Requires(events != null);
foreach (var c in events) {
var candidate = c as IEventDefinition;
if (candidate == null) continue;
// What should we check?
if (candidate.Visibility != Event.Visibility) {
Error("Event {0} has different visibility: contract: {1}, original: {2}", MemberHelper.GetMemberSignature(Event, NameFormattingOptions.None),
Event.Visibility, candidate.Visibility);
}
return; // found
}
if (Event.Adder != null && (IsImplementingInvisibleInterface(Event.Adder.ResolvedMethod) || Event.Adder.ResolvedMethod.Visibility == TypeMemberVisibility.Private) ||
Event.Remover != null && (IsImplementingInvisibleInterface(Event.Remover.ResolvedMethod) || Event.Adder.ResolvedMethod.Visibility == TypeMemberVisibility.Private))
{
Warning("Event {0} only appears in contract reference assembly, but is invisible, so okay", MemberHelper.GetMemberSignature(Event, NameFormattingOptions.None));
}
else
{
Error("Event {0} only appears in contract reference assembly", MemberHelper.GetMemberSignature(Event, NameFormattingOptions.None));
}
}
private static IMethodDefinition GetMethod(INamedTypeDefinition original, IMethodDefinition method)
{
foreach (var candidate in original.GetMembersNamed(method.Name, false))
{
IMethodDefinition candidateMethod = candidate as IMethodDefinition;
if (candidateMethod == null) continue;
if (candidateMethod.GenericParameterCount != method.GenericParameterCount) continue;
if (candidateMethod.ParameterCount != method.ParameterCount) continue;
if (!ParameterTypesMatch(candidateMethod.Parameters, method.Parameters)) continue;
if (!TypesMatchSyntactically(candidateMethod.Type, method.Type)) continue;
return candidateMethod;
}
return null;
}
private static bool ParameterTypesMatch(IEnumerable<IParameterDefinition> pars1, IEnumerable<IParameterDefinition> pars2)
{
var pars2it = pars2.GetEnumerator();
foreach (var p1 in pars1)
{
pars2it.MoveNext(); // must succeed (same count);
var p2 = pars2it.Current;
if (p1.IsByReference != p2.IsByReference) return false;
if (!TypesMatchSyntactically(p1.Type, p2.Type)) return false;
}
return true;
}
private static bool TypesMatchSyntactically(ITypeReference tref1, ITypeReference tref2)
{
return (TypeHelper.GetTypeName(tref1) == TypeHelper.GetTypeName(tref2));
}
private void CheckSurface(IMethodDefinition method, IMethodDefinition original)
{
Contract.Requires(method != null);
if (original == null || original == Dummy.Method)
{
// special case for generated default constructors.
if (method.IsConstructor && method.ParameterCount == 0)
{
return;
}
if (IsModel(method)) return;
if (IsImplementingInvisibleInterface(method))
{
Warning("Method {0} exists only in contract reference assembly, but is hidden, so okay", MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature));
}
else
{
Error("Method {0} exists only in contract reference assembly", MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature));
}
return;
}
// check that both are virtual or not
if (method.IsVirtual != original.IsVirtual)
{
Error("Found method {0} which differs in virtual bit: contract: {1}, original: {2}", MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature), method.IsVirtual, original.IsVirtual);
}
if (method.Visibility != original.Visibility)
{
if (method.IsConstructor && method.ParameterCount == 0 && (method.Visibility == TypeMemberVisibility.Assembly || method.Visibility == TypeMemberVisibility.Family))
{
// skip. It's hard to match reference assemblies constructor visibility.
}
else if (original.Visibility == TypeMemberVisibility.FamilyOrAssembly && method.Visibility == TypeMemberVisibility.Family)
{
// skip, removing the internal is fine and sometimes necessary
}
else
{
Error("Found method {0} which differ in visibility: contract: {1}, original: {2}", MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature | NameFormattingOptions.UseGenericTypeNameSuffix), method.Visibility, original.Visibility);
}
}
if (method.IsStatic != original.IsStatic)
{
Error("Found method {0} which differ in static bit: contract: {1}, original: {2}", MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature), method.IsStatic, original.IsStatic);
}
//if (!TypesMatchSyntactically(method.Type, original.Type)) {
// Error("Found method {0} which have different return types: contract: {1}, original: {2}", MemberHelper.GetMethodSignature(method, NameFormattingOptions.Signature), method.Type, original.Type);
//}
// TODO more
}
private bool IsModel(IMethodDefinition method) {
Contract.Requires(method != null);
if (IsModel(method.Attributes)) return true;
IPropertyDefinition prop;
if (IsPropertyGetter(method, out prop)) {
if (IsModel(prop.Attributes)) return true;
}
return false;
}
public bool IsPropertyGetter(IMethodDefinition method, out IPropertyDefinition prop) {
Contract.Requires(method != null);
ITypeDefinition declaringType = method.ContainingTypeDefinition;
foreach (var p in declaringType.Properties) {
if (p.Getter != null && p.Getter.InternedKey == method.InternedKey) {
prop = p;
return true;
}
}
prop = null;
return false;
}
public int Errors { get { return this.errorCount; } }
private void Error(string format, params object[] args)
{
Contract.Ensures(this.errorCount == Contract.OldValue(this.errorCount) +1);
this.errorCount++;
this.tw.Write("Error: ");
this.tw.WriteLine(format, args);
}
private void Warning(string format, params object[] args)
{
#if EMIT_WARNINGS
this.tw.Write("Warning: ");
this.tw.WriteLine(format, args);
#endif
}
}
internal class SanitizerHostEnvironment : MetadataReaderHost
{
readonly PeReader peReader;
internal SanitizerHostEnvironment(NameTable nameTable)
: base(nameTable, new InternFactory(), 4, null, true)
{
this.peReader = new PeReader(this);
}
public override IUnit LoadUnitFrom(string location)
{
IUnit result = this.peReader.OpenModule(BinaryDocument.GetBinaryDocumentForFile(location, this));
this.RegisterAsLatest(result);
return result;
}
protected override IPlatformType GetPlatformType()
{
return SanitizerPlatformType;
}
SanitizerPlatformType _myPlatformType = null;
public SanitizerPlatformType SanitizerPlatformType
{
get
{
if (_myPlatformType == null)
_myPlatformType = new SanitizerPlatformType(this);
return _myPlatformType;
}
}
}
internal class SanitizerPlatformType : Microsoft.Cci.Immutable.PlatformType
{
public SanitizerPlatformType(IMetadataHost host) : base(host) { }
/// <summary>
/// Returns a reference to the type System.ArgumentException from the core assembly
/// </summary>
public INamespaceTypeReference SystemArgumentException
{
[DebuggerNonUserCode]
get
{
if (this.systemArgumentException == null)
{
this.systemArgumentException = this.CreateReference(this.CoreAssemblyRef, "System", "ArgumentException");
}
return this.systemArgumentException;
}
}
INamespaceTypeReference/*?*/ systemArgumentException;
}
static class CCI2UnitHelper
{
public static INamedTypeDefinition GetCorresponding(this IUnit unit, ITypeDefinition type)
{
INamespaceTypeDefinition nstd = type as INamespaceTypeDefinition;
if (nstd != null) return unit.GetCorresponding(nstd);
INestedTypeDefinition nested = type as INestedTypeDefinition;
if (nested != null) return unit.GetCorresponding(nested);
return null;
}
public static INamespaceTypeDefinition GetCorresponding(this IUnit unit, INamespaceTypeDefinition type)
{
INamespaceDefinition ns = unit.GetCorresponding(type.ContainingNamespace);
if (ns == null) return null;
foreach (var mem in ns.GetMembersNamed(type.Name, true)) {
INamespaceTypeDefinition candidate = mem as INamespaceTypeDefinition;
if (candidate == null) continue;
if (candidate.GenericParameterCount == type.GenericParameterCount) return candidate;
}
return null;
}
private static INamespaceDefinition GetCorresponding(this IUnit unit, INamespaceDefinition nsd)
{
INestedUnitNamespace nested = nsd as INestedUnitNamespace;
if (nested != null)
{
var parent = unit.GetCorresponding(nested.ContainingNamespace);
if (parent == null) return null;
foreach (var candidate in parent.GetMembersNamed(nested.Name, false)) {
INamespaceDefinition result = candidate as INamespaceDefinition;
if (result != null) return result;
}
return null;
}
// must be the root
return unit.UnitNamespaceRoot;
}
public static INestedTypeDefinition GetCorresponding(this IUnit unit, INestedTypeDefinition type)
{
var parent = unit.GetCorresponding(type.ContainingTypeDefinition);
if (parent == null) return null;
foreach (var candidate in parent.GetMembersNamed(type.Name, false))
{
INestedTypeDefinition result = candidate as INestedTypeDefinition;
if (result == null) continue;
if (result.GenericParameterCount == type.GenericParameterCount) return result;
}
return null;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using Lucene.Net.Util;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using FileInfo = System.IO.FileInfo;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using BinaryDocValuesField = Lucene.Net.Document.BinaryDocValuesField;
using Document = Lucene.Net.Document.Document;
using DoubleDocValuesField = Lucene.Net.Document.DoubleDocValuesField;
using Field = Lucene.Net.Document.Field;
using FieldType = Lucene.Net.Document.FieldType;
using FloatDocValuesField = Lucene.Net.Document.FloatDocValuesField;
using IntField = Lucene.Net.Document.IntField;
using LongField = Lucene.Net.Document.LongField;
using NumericDocValuesField = Lucene.Net.Document.NumericDocValuesField;
using SortedDocValuesField = Lucene.Net.Document.SortedDocValuesField;
using StringField = Lucene.Net.Document.StringField;
using TextField = Lucene.Net.Document.TextField;
using IndexOptions = Lucene.Net.Index.FieldInfo.IndexOptions_e;
using OpenMode_e = Lucene.Net.Index.IndexWriterConfig.OpenMode_e;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using FieldCache_Fields = Lucene.Net.Search.FieldCache_Fields;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using NumericRangeQuery = Lucene.Net.Search.NumericRangeQuery;
using PhraseQuery = Lucene.Net.Search.PhraseQuery;
using ScoreDoc = Lucene.Net.Search.ScoreDoc;
using TermQuery = Lucene.Net.Search.TermQuery;
using TopDocs = Lucene.Net.Search.TopDocs;
using BaseDirectoryWrapper = Lucene.Net.Store.BaseDirectoryWrapper;
using Directory = Lucene.Net.Store.Directory;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using Bits = Lucene.Net.Util.Bits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Constants = Lucene.Net.Util.Constants;
using StringHelper = Lucene.Net.Util.StringHelper;
using SuppressCodecs = Lucene.Net.Util.LuceneTestCase.SuppressCodecs;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using TestUtil = Lucene.Net.Util.TestUtil;
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
using Lucene.Net.Support;
/*
Verify we can read the pre-4.0 file format, do searches
against it, and add documents to it.
*/
// don't use 3.x codec, its unrealistic since it means
// we won't even be running the actual code, only the impostor
// Sep codec cannot yet handle the offsets we add when changing indexes!
[TestFixture]
public class TestBackwardsCompatibility3x : LuceneTestCase
{
// Uncomment these cases & run them on an older Lucene
// version, to generate an index to test backwards
// compatibility. Then, cd to build/test/index.cfs and
// run "zip index.<VERSION>.cfs.zip *"; cd to
// build/test/index.nocfs and run "zip
// index.<VERSION>.nocfs.zip *". Then move those 2 zip
// files to your trunk checkout and add them to the
// oldNames array.
/*
public void testCreateCFS() throws IOException {
createIndex("index.cfs", true, false);
}
public void testCreateNoCFS() throws IOException {
createIndex("index.nocfs", false, false);
}
*/
/*
// These are only needed for the special upgrade test to verify
// that also single-segment indexes are correctly upgraded by IndexUpgrader.
// You don't need them to be build for non-3.1 (the test is happy with just one
// "old" segment format, version is unimportant:
public void testCreateSingleSegmentCFS() throws IOException {
createIndex("index.singlesegment.cfs", true, true);
}
public void testCreateSingleSegmentNoCFS() throws IOException {
createIndex("index.singlesegment.nocfs", false, true);
}
*/
internal static readonly string[] OldNames = new string[] { "30.cfs", "30.nocfs", "31.cfs", "31.nocfs", "32.cfs", "32.nocfs", "34.cfs", "34.nocfs" };
internal readonly string[] UnsupportedNames = new string[] { "19.cfs", "19.nocfs", "20.cfs", "20.nocfs", "21.cfs", "21.nocfs", "22.cfs", "22.nocfs", "23.cfs", "23.nocfs", "24.cfs", "24.nocfs", "29.cfs", "29.nocfs" };
internal static readonly string[] OldSingleSegmentNames = new string[] { "31.optimized.cfs", "31.optimized.nocfs" };
internal static IDictionary<string, Directory> OldIndexDirs;
[TestFixtureSetUp]
public static void BeforeClass()
{
Assert.IsFalse(LuceneTestCase.OLD_FORMAT_IMPERSONATION_IS_ACTIVE, "test infra is broken!");
IList<string> names = new List<string>(OldNames.Length + OldSingleSegmentNames.Length);
names.AddRange(Arrays.AsList(OldNames));
names.AddRange(Arrays.AsList(OldSingleSegmentNames));
OldIndexDirs = new Dictionary<string, Directory>();
foreach (string name in names)
{
DirectoryInfo dir = CreateTempDir(name);
FileInfo dataFile = new FileInfo(typeof(TestBackwardsCompatibility3x).getResource("index." + name + ".zip").toURI());
TestUtil.Unzip(dataFile, dir);
OldIndexDirs[name] = NewFSDirectory(dir);
}
}
[TestFixtureTearDown]
public static void AfterClass()
{
foreach (Directory d in OldIndexDirs.Values)
{
d.Dispose();
}
OldIndexDirs = null;
}
/// <summary>
/// this test checks that *only* IndexFormatTooOldExceptions are thrown when you open and operate on too old indexes! </summary>
[Test]
public virtual void TestUnsupportedOldIndexes()
{
for (int i = 0; i < UnsupportedNames.Length; i++)
{
if (VERBOSE)
{
Console.WriteLine("TEST: index " + UnsupportedNames[i]);
}
DirectoryInfo oldIndexDir = CreateTempDir(UnsupportedNames[i]);
TestUtil.Unzip(GetDataFile("unsupported." + UnsupportedNames[i] + ".zip"), oldIndexDir);
BaseDirectoryWrapper dir = NewFSDirectory(oldIndexDir);
// don't checkindex, these are intentionally not supported
dir.CheckIndexOnClose = false;
IndexReader reader = null;
IndexWriter writer = null;
try
{
reader = DirectoryReader.Open(dir);
Assert.Fail("DirectoryReader.open should not pass for " + UnsupportedNames[i]);
}
catch (IndexFormatTooOldException e)
{
// pass
}
finally
{
if (reader != null)
{
reader.Dispose();
}
reader = null;
}
try
{
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
Assert.Fail("IndexWriter creation should not pass for " + UnsupportedNames[i]);
}
catch (IndexFormatTooOldException e)
{
// pass
if (VERBOSE)
{
Console.WriteLine("TEST: got expected exc:");
Console.WriteLine(e.StackTrace);
}
// Make sure exc message includes a path=
Assert.IsTrue(e.Message.IndexOf("path=\"") != -1, "got exc message: " + e.Message);
}
finally
{
// we should fail to open IW, and so it should be null when we get here.
// However, if the test fails (i.e., IW did not fail on open), we need
// to close IW. However, if merges are run, IW may throw
// IndexFormatTooOldException, and we don't want to mask the Assert.Fail()
// above, so close without waiting for merges.
if (writer != null)
{
writer.Dispose(false);
}
writer = null;
}
MemoryStream bos = new MemoryStream(1024);
CheckIndex checker = new CheckIndex(dir);
checker.InfoStream = new StreamWriter(bos.ToString(), false, IOUtils.CHARSET_UTF_8);
CheckIndex.Status indexStatus = checker.DoCheckIndex();
Assert.IsFalse(indexStatus.Clean);
Assert.IsTrue(bos.ToString().Contains(typeof(IndexFormatTooOldException).Name));
dir.Dispose();
}
}
[Test]
public virtual void TestFullyMergeOldIndex()
{
foreach (string name in OldNames)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: index=" + name);
}
Directory dir = NewDirectory(OldIndexDirs[name]);
IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
w.ForceMerge(1);
w.Dispose();
dir.Dispose();
}
}
[Test]
public virtual void TestAddOldIndexes()
{
foreach (string name in OldNames)
{
if (VERBOSE)
{
Console.WriteLine("\nTEST: old index " + name);
}
Directory targetDir = NewDirectory();
IndexWriter w = new IndexWriter(targetDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
w.AddIndexes(OldIndexDirs[name]);
if (VERBOSE)
{
Console.WriteLine("\nTEST: done adding indices; now close");
}
w.Dispose();
targetDir.Dispose();
}
}
[Test]
public virtual void TestAddOldIndexesReader()
{
foreach (string name in OldNames)
{
IndexReader reader = DirectoryReader.Open(OldIndexDirs[name]);
Directory targetDir = NewDirectory();
IndexWriter w = new IndexWriter(targetDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
w.AddIndexes(reader);
w.Dispose();
reader.Dispose();
targetDir.Dispose();
}
}
[Test]
public virtual void TestSearchOldIndex()
{
foreach (string name in OldNames)
{
SearchIndex(OldIndexDirs[name], name);
}
}
[Test]
public virtual void TestIndexOldIndexNoAdds()
{
foreach (string name in OldNames)
{
Directory dir = NewDirectory(OldIndexDirs[name]);
ChangeIndexNoAdds(Random(), dir);
dir.Dispose();
}
}
[Test]
public virtual void TestIndexOldIndex()
{
foreach (string name in OldNames)
{
if (VERBOSE)
{
Console.WriteLine("TEST: oldName=" + name);
}
Directory dir = NewDirectory(OldIndexDirs[name]);
ChangeIndexWithAdds(Random(), dir, name);
dir.Dispose();
}
}
/// @deprecated 3.x transition mechanism
[Obsolete("3.x transition mechanism")]
[Test]
public virtual void TestDeleteOldIndex()
{
foreach (string name in OldNames)
{
if (VERBOSE)
{
Console.WriteLine("TEST: oldName=" + name);
}
// Try one delete:
Directory dir = NewDirectory(OldIndexDirs[name]);
IndexReader ir = DirectoryReader.Open(dir);
Assert.AreEqual(35, ir.NumDocs());
ir.Dispose();
IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
iw.DeleteDocuments(new Term("id", "3"));
iw.Dispose();
ir = DirectoryReader.Open(dir);
Assert.AreEqual(34, ir.NumDocs());
ir.Dispose();
// Delete all but 1 document:
iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
for (int i = 0; i < 35; i++)
{
iw.DeleteDocuments(new Term("id", "" + i));
}
// Verify NRT reader takes:
ir = DirectoryReader.Open(iw, true);
iw.Dispose();
Assert.AreEqual(1, ir.NumDocs(), "index " + name);
ir.Dispose();
// Verify non-NRT reader takes:
ir = DirectoryReader.Open(dir);
Assert.AreEqual(1, ir.NumDocs(), "index " + name);
ir.Dispose();
dir.Dispose();
}
}
private void DoTestHits(ScoreDoc[] hits, int expectedCount, IndexReader reader)
{
int hitCount = hits.Length;
Assert.AreEqual(expectedCount, hitCount, "wrong number of hits");
for (int i = 0; i < hitCount; i++)
{
reader.Document(hits[i].Doc);
reader.GetTermVectors(hits[i].Doc);
}
}
public virtual void SearchIndex(Directory dir, string oldName)
{
//QueryParser parser = new QueryParser("contents", new MockAnalyzer(random));
//Query query = parser.parse("handle:1");
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
TestUtil.CheckIndex(dir);
// true if this is a 4.0+ index
bool is40Index = MultiFields.GetMergedFieldInfos(reader).FieldInfo("content5") != null;
Bits liveDocs = MultiFields.GetLiveDocs(reader);
for (int i = 0; i < 35; i++)
{
if (liveDocs.Get(i))
{
Document d = reader.Document(i);
IList<IndexableField> fields = d.Fields;
bool isProxDoc = d.GetField("content3") == null;
if (isProxDoc)
{
int numFields = is40Index ? 7 : 5;
Assert.AreEqual(numFields, fields.Count);
IndexableField f = d.GetField("id");
Assert.AreEqual("" + i, f.StringValue);
f = d.GetField("utf8");
Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.StringValue);
f = d.GetField("autf8");
Assert.AreEqual("Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", f.StringValue);
f = d.GetField("content2");
Assert.AreEqual("here is more content with aaa aaa aaa", f.StringValue);
f = d.GetField("fie\u2C77ld");
Assert.AreEqual("field with non-ascii name", f.StringValue);
}
Fields tfvFields = reader.GetTermVectors(i);
Assert.IsNotNull(tfvFields, "i=" + i);
Terms tfv = tfvFields.Terms("utf8");
Assert.IsNotNull(tfv, "docID=" + i + " index=" + oldName);
}
else
{
// Only ID 7 is deleted
Assert.AreEqual(7, i);
}
}
if (is40Index)
{
// check docvalues fields
NumericDocValues dvByte = MultiDocValues.GetNumericValues(reader, "dvByte");
BinaryDocValues dvBytesDerefFixed = MultiDocValues.GetBinaryValues(reader, "dvBytesDerefFixed");
BinaryDocValues dvBytesDerefVar = MultiDocValues.GetBinaryValues(reader, "dvBytesDerefVar");
SortedDocValues dvBytesSortedFixed = MultiDocValues.GetSortedValues(reader, "dvBytesSortedFixed");
SortedDocValues dvBytesSortedVar = MultiDocValues.GetSortedValues(reader, "dvBytesSortedVar");
BinaryDocValues dvBytesStraightFixed = MultiDocValues.GetBinaryValues(reader, "dvBytesStraightFixed");
BinaryDocValues dvBytesStraightVar = MultiDocValues.GetBinaryValues(reader, "dvBytesStraightVar");
NumericDocValues dvDouble = MultiDocValues.GetNumericValues(reader, "dvDouble");
NumericDocValues dvFloat = MultiDocValues.GetNumericValues(reader, "dvFloat");
NumericDocValues dvInt = MultiDocValues.GetNumericValues(reader, "dvInt");
NumericDocValues dvLong = MultiDocValues.GetNumericValues(reader, "dvLong");
NumericDocValues dvPacked = MultiDocValues.GetNumericValues(reader, "dvPacked");
NumericDocValues dvShort = MultiDocValues.GetNumericValues(reader, "dvShort");
for (int i = 0; i < 35; i++)
{
int id = Convert.ToInt32(reader.Document(i).Get("id"));
Assert.AreEqual(id, dvByte.Get(i));
sbyte[] bytes = new sbyte[] { (sbyte)((int)((uint)id >> 24)), (sbyte)((int)((uint)id >> 16)), (sbyte)((int)((uint)id >> 8)), (sbyte)id };
BytesRef expectedRef = new BytesRef(bytes);
BytesRef scratch = new BytesRef();
dvBytesDerefFixed.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesDerefVar.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesSortedFixed.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesSortedVar.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesStraightFixed.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
dvBytesStraightVar.Get(i, scratch);
Assert.AreEqual(expectedRef, scratch);
Assert.AreEqual((double)id, BitConverter.Int64BitsToDouble(dvDouble.Get(i)), 0D);
Assert.AreEqual((float)id, Number.IntBitsToFloat((int)dvFloat.Get(i)), 0F);
Assert.AreEqual(id, dvInt.Get(i));
Assert.AreEqual(id, dvLong.Get(i));
Assert.AreEqual(id, dvPacked.Get(i));
Assert.AreEqual(id, dvShort.Get(i));
}
}
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
// First document should be #21 since it's norm was
// increased:
Document d_ = searcher.IndexReader.Document(hits[0].Doc);
Assert.AreEqual("didn't get the right document first", "21", d_.Get("id"));
DoTestHits(hits, 34, searcher.IndexReader);
if (is40Index)
{
hits = searcher.Search(new TermQuery(new Term("content5", "aaa")), null, 1000).ScoreDocs;
DoTestHits(hits, 34, searcher.IndexReader);
hits = searcher.Search(new TermQuery(new Term("content6", "aaa")), null, 1000).ScoreDocs;
DoTestHits(hits, 34, searcher.IndexReader);
}
hits = searcher.Search(new TermQuery(new Term("utf8", "\u0000")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
hits = searcher.Search(new TermQuery(new Term("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
hits = searcher.Search(new TermQuery(new Term("utf8", "ab\ud917\udc17cd")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length);
reader.Dispose();
}
private int Compare(string name, string v)
{
int v0 = Convert.ToInt32(name.Substring(0, 2));
int v1 = Convert.ToInt32(v);
return v0 - v1;
}
public virtual void ChangeIndexWithAdds(Random random, Directory dir, string origOldName)
{
// open writer
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode_e.APPEND));
// add 10 docs
for (int i = 0; i < 10; i++)
{
AddDoc(writer, 35 + i);
}
// make sure writer sees right total -- writer seems not to know about deletes in .del?
int expected;
if (Compare(origOldName, "24") < 0)
{
expected = 44;
}
else
{
expected = 45;
}
Assert.AreEqual(expected, writer.NumDocs(), "wrong doc count");
writer.Dispose();
// make sure searching sees right # hits
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Document d = searcher.IndexReader.Document(hits[0].Doc);
Assert.AreEqual("wrong first document", "21", d.Get("id"));
DoTestHits(hits, 44, searcher.IndexReader);
reader.Dispose();
// fully merge
writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode_e.APPEND));
writer.ForceMerge(1);
writer.Dispose();
reader = DirectoryReader.Open(dir);
searcher = new IndexSearcher(reader);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(44, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
DoTestHits(hits, 44, searcher.IndexReader);
Assert.AreEqual("wrong first document", "21", d.Get("id"));
reader.Dispose();
}
public virtual void ChangeIndexNoAdds(Random random, Directory dir)
{
// make sure searching sees right # hits
DirectoryReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
ScoreDoc[] hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length, "wrong number of hits");
Document d = searcher.Doc(hits[0].Doc);
Assert.AreEqual("wrong first document", "21", d.Get("id"));
reader.Dispose();
// fully merge
IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetOpenMode(OpenMode_e.APPEND));
writer.ForceMerge(1);
writer.Dispose();
reader = DirectoryReader.Open(dir);
searcher = new IndexSearcher(reader);
hits = searcher.Search(new TermQuery(new Term("content", "aaa")), null, 1000).ScoreDocs;
Assert.AreEqual(34, hits.Length, "wrong number of hits");
DoTestHits(hits, 34, searcher.IndexReader);
reader.Dispose();
}
public virtual DirectoryInfo CreateIndex(string dirName, bool doCFS, bool fullyMerged)
{
// we use a real directory name that is not cleaned up, because this method is only used to create backwards indexes:
DirectoryInfo indexDir = new DirectoryInfo(Path.Combine("/tmp/4x/", dirName));
TestUtil.Rm(indexDir);
Directory dir = NewFSDirectory(indexDir);
LogByteSizeMergePolicy mp = new LogByteSizeMergePolicy();
mp.NoCFSRatio = doCFS ? 1.0 : 0.0;
mp.MaxCFSSegmentSizeMB = double.PositiveInfinity;
// TODO: remove randomness
IndexWriterConfig conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetMaxBufferedDocs(10).SetMergePolicy(mp).SetUseCompoundFile(doCFS);
IndexWriter writer = new IndexWriter(dir, conf);
for (int i = 0; i < 35; i++)
{
AddDoc(writer, i);
}
Assert.AreEqual(35, writer.MaxDoc(), "wrong doc count");
if (fullyMerged)
{
writer.ForceMerge(1);
}
writer.Dispose();
if (!fullyMerged)
{
// open fresh writer so we get no prx file in the added segment
mp = new LogByteSizeMergePolicy();
mp.NoCFSRatio = doCFS ? 1.0 : 0.0;
// TODO: remove randomness
conf = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetMaxBufferedDocs(10).SetMergePolicy(mp).SetUseCompoundFile(doCFS);
writer = new IndexWriter(dir, conf);
AddNoProxDoc(writer);
writer.Dispose();
writer = new IndexWriter(dir, conf.SetMergePolicy(doCFS ? NoMergePolicy.COMPOUND_FILES : NoMergePolicy.NO_COMPOUND_FILES));
Term searchTerm = new Term("id", "7");
writer.DeleteDocuments(searchTerm);
writer.Dispose();
}
dir.Dispose();
return indexDir;
}
private void AddDoc(IndexWriter writer, int id)
{
Document doc = new Document();
doc.Add(new TextField("content", "aaa", Field.Store.NO));
doc.Add(new StringField("id", Convert.ToString(id), Field.Store.YES));
FieldType customType2 = new FieldType(TextField.TYPE_STORED);
customType2.StoreTermVectors = true;
customType2.StoreTermVectorPositions = true;
customType2.StoreTermVectorOffsets = true;
doc.Add(new Field("autf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", customType2));
doc.Add(new Field("utf8", "Lu\uD834\uDD1Ece\uD834\uDD60ne \u0000 \u2620 ab\ud917\udc17cd", customType2));
doc.Add(new Field("content2", "here is more content with aaa aaa aaa", customType2));
doc.Add(new Field("fie\u2C77ld", "field with non-ascii name", customType2));
// add numeric fields, to test if flex preserves encoding
doc.Add(new IntField("trieInt", id, Field.Store.NO));
doc.Add(new LongField("trieLong", (long)id, Field.Store.NO));
// add docvalues fields
doc.Add(new NumericDocValuesField("dvByte", (sbyte)id));
sbyte[] bytes = new sbyte[] { (sbyte)((int)((uint)id >> 24)), (sbyte)((int)((uint)id >> 16)), (sbyte)((int)((uint)id >> 8)), (sbyte)id };
BytesRef @ref = new BytesRef(bytes);
doc.Add(new BinaryDocValuesField("dvBytesDerefFixed", @ref));
doc.Add(new BinaryDocValuesField("dvBytesDerefVar", @ref));
doc.Add(new SortedDocValuesField("dvBytesSortedFixed", @ref));
doc.Add(new SortedDocValuesField("dvBytesSortedVar", @ref));
doc.Add(new BinaryDocValuesField("dvBytesStraightFixed", @ref));
doc.Add(new BinaryDocValuesField("dvBytesStraightVar", @ref));
doc.Add(new DoubleDocValuesField("dvDouble", (double)id));
doc.Add(new FloatDocValuesField("dvFloat", (float)id));
doc.Add(new NumericDocValuesField("dvInt", id));
doc.Add(new NumericDocValuesField("dvLong", id));
doc.Add(new NumericDocValuesField("dvPacked", id));
doc.Add(new NumericDocValuesField("dvShort", (short)id));
// a field with both offsets and term vectors for a cross-check
FieldType customType3 = new FieldType(TextField.TYPE_STORED);
customType3.StoreTermVectors = true;
customType3.StoreTermVectorPositions = true;
customType3.StoreTermVectorOffsets = true;
customType3.IndexOptionsValue = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
doc.Add(new Field("content5", "here is more content with aaa aaa aaa", customType3));
// a field that omits only positions
FieldType customType4 = new FieldType(TextField.TYPE_STORED);
customType4.StoreTermVectors = true;
customType4.StoreTermVectorPositions = false;
customType4.StoreTermVectorOffsets = true;
customType4.IndexOptionsValue = IndexOptions.DOCS_AND_FREQS;
doc.Add(new Field("content6", "here is more content with aaa aaa aaa", customType4));
// TODO:
// index different norms types via similarity (we use a random one currently?!)
// remove any analyzer randomness, explicitly add payloads for certain fields.
writer.AddDocument(doc);
}
private void AddNoProxDoc(IndexWriter writer)
{
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.IndexOptionsValue = IndexOptions.DOCS_ONLY;
Field f = new Field("content3", "aaa", customType);
doc.Add(f);
FieldType customType2 = new FieldType();
customType2.Stored = true;
customType2.IndexOptionsValue = IndexOptions.DOCS_ONLY;
f = new Field("content4", "aaa", customType2);
doc.Add(f);
writer.AddDocument(doc);
}
private int CountDocs(DocsEnum docs)
{
int count = 0;
while ((docs.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
{
count++;
}
return count;
}
// flex: test basics of TermsEnum api on non-flex index
[Test]
public virtual void TestNextIntoWrongField()
{
foreach (string name in OldNames)
{
Directory dir = OldIndexDirs[name];
IndexReader r = DirectoryReader.Open(dir);
TermsEnum terms = MultiFields.GetFields(r).Terms("content").Iterator(null);
BytesRef t = terms.Next();
Assert.IsNotNull(t);
// content field only has term aaa:
Assert.AreEqual("aaa", t.Utf8ToString());
Assert.IsNull(terms.Next());
BytesRef aaaTerm = new BytesRef("aaa");
// should be found exactly
Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(aaaTerm));
Assert.AreEqual(35, CountDocs(TestUtil.Docs(Random(), terms, null, null, 0)));
Assert.IsNull(terms.Next());
// should hit end of field
Assert.AreEqual(TermsEnum.SeekStatus.END, terms.SeekCeil(new BytesRef("bbb")));
Assert.IsNull(terms.Next());
// should seek to aaa
Assert.AreEqual(TermsEnum.SeekStatus.NOT_FOUND, terms.SeekCeil(new BytesRef("a")));
Assert.IsTrue(terms.Term().BytesEquals(aaaTerm));
Assert.AreEqual(35, CountDocs(TestUtil.Docs(Random(), terms, null, null, 0)));
Assert.IsNull(terms.Next());
Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(aaaTerm));
Assert.AreEqual(35, CountDocs(TestUtil.Docs(Random(), terms, null, null, 0)));
Assert.IsNull(terms.Next());
r.Dispose();
}
}
/// <summary>
/// Test that we didn't forget to bump the current Constants.LUCENE_MAIN_VERSION.
/// this is important so that we can determine which version of lucene wrote the segment.
/// </summary>
[Test]
public virtual void TestOldVersions()
{
// first create a little index with the current code and get the version
Directory currentDir = NewDirectory();
RandomIndexWriter riw = new RandomIndexWriter(Random(), currentDir);
riw.AddDocument(new Document());
riw.Dispose();
DirectoryReader ir = DirectoryReader.Open(currentDir);
SegmentReader air = (SegmentReader)ir.Leaves()[0].Reader();
string currentVersion = air.SegmentInfo.Info.Version;
Assert.IsNotNull(currentVersion); // only 3.0 segments can have a null version
ir.Dispose();
currentDir.Dispose();
IComparer<string> comparator = StringHelper.VersionComparator;
// now check all the old indexes, their version should be < the current version
foreach (string name in OldNames)
{
Directory dir = OldIndexDirs[name];
DirectoryReader r = DirectoryReader.Open(dir);
foreach (AtomicReaderContext context in r.Leaves())
{
air = (SegmentReader)context.Reader();
string oldVersion = air.SegmentInfo.Info.Version;
// TODO: does preflex codec actually set "3.0" here? this is safe to do I think.
// Assert.IsNotNull(oldVersion);
Assert.IsTrue(oldVersion == null || comparator.Compare(oldVersion, currentVersion) < 0, "current Constants.LUCENE_MAIN_VERSION is <= an old index: did you forget to bump it?!");
}
r.Dispose();
}
}
[Test]
public virtual void TestNumericFields()
{
foreach (string name in OldNames)
{
Directory dir = OldIndexDirs[name];
IndexReader reader = DirectoryReader.Open(dir);
IndexSearcher searcher = new IndexSearcher(reader);
for (int id = 10; id < 15; id++)
{
ScoreDoc[] hits = searcher.Search(NumericRangeQuery.NewIntRange("trieInt", 4, Convert.ToInt32(id), Convert.ToInt32(id), true, true), 100).ScoreDocs;
Assert.AreEqual(1, hits.Length, "wrong number of hits");
Document d = searcher.Doc(hits[0].Doc);
Assert.AreEqual(Convert.ToString(id), d.Get("id"));
hits = searcher.Search(NumericRangeQuery.NewLongRange("trieLong", 4, Convert.ToInt64(id), Convert.ToInt64(id), true, true), 100).ScoreDocs;
Assert.AreEqual(1, hits.Length, "wrong number of hits");
d = searcher.Doc(hits[0].Doc);
Assert.AreEqual(Convert.ToString(id), d.Get("id"));
}
// check that also lower-precision fields are ok
ScoreDoc[] hits_ = searcher.Search(NumericRangeQuery.NewIntRange("trieInt", 4, int.MinValue, int.MaxValue, false, false), 100).ScoreDocs;
Assert.AreEqual(34, hits_.Length, "wrong number of hits");
hits_ = searcher.Search(NumericRangeQuery.NewLongRange("trieLong", 4, long.MinValue, long.MaxValue, false, false), 100).ScoreDocs;
Assert.AreEqual(34, hits_.Length, "wrong number of hits");
// check decoding into field cache
FieldCache_Fields.Ints fci = FieldCache_Fields.DEFAULT.GetInts(SlowCompositeReaderWrapper.Wrap(searcher.IndexReader), "trieInt", false);
int maxDoc = searcher.IndexReader.MaxDoc();
for (int doc = 0; doc < maxDoc; doc++)
{
int val = fci.Get(doc);
Assert.IsTrue(val >= 0 && val < 35, "value in id bounds");
}
FieldCache_Fields.Longs fcl = FieldCache_Fields.DEFAULT.GetLongs(SlowCompositeReaderWrapper.Wrap(searcher.IndexReader), "trieLong", false);
for (int doc = 0; doc < maxDoc; doc++)
{
long val = fcl.Get(doc);
Assert.IsTrue(val >= 0L && val < 35L, "value in id bounds");
}
reader.Dispose();
}
}
private int CheckAllSegmentsUpgraded(Directory dir)
{
SegmentInfos infos = new SegmentInfos();
infos.Read(dir);
if (VERBOSE)
{
Console.WriteLine("checkAllSegmentsUpgraded: " + infos);
}
foreach (SegmentCommitInfo si in infos.Segments)
{
Assert.AreEqual(Constants.LUCENE_MAIN_VERSION, si.Info.Version);
}
return infos.Size();
}
private int GetNumberOfSegments(Directory dir)
{
SegmentInfos infos = new SegmentInfos();
infos.Read(dir);
return infos.Size();
}
[Test]
public virtual void TestUpgradeOldIndex()
{
IList<string> names = new List<string>(OldNames.Length + OldSingleSegmentNames.Length);
names.AddRange(Arrays.AsList(OldNames));
names.AddRange(Arrays.AsList(OldSingleSegmentNames));
foreach (string name in names)
{
if (VERBOSE)
{
Console.WriteLine("testUpgradeOldIndex: index=" + name);
}
Directory dir = NewDirectory(OldIndexDirs[name]);
(new IndexUpgrader(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false)).Upgrade();
CheckAllSegmentsUpgraded(dir);
dir.Dispose();
}
}
[Test]
public virtual void TestUpgradeOldSingleSegmentIndexWithAdditions()
{
foreach (string name in OldSingleSegmentNames)
{
if (VERBOSE)
{
Console.WriteLine("testUpgradeOldSingleSegmentIndexWithAdditions: index=" + name);
}
Directory dir = NewDirectory(OldIndexDirs[name]);
Assert.AreEqual(1, GetNumberOfSegments(dir), "Original index must be single segment");
// create a bunch of dummy segments
int id = 40;
RAMDirectory ramDir = new RAMDirectory();
for (int i = 0; i < 3; i++)
{
// only use Log- or TieredMergePolicy, to make document addition predictable and not suddenly merge:
MergePolicy mp = Random().NextBoolean() ? (MergePolicy)NewLogMergePolicy() : NewTieredMergePolicy();
IndexWriterConfig iwc = (new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))).SetMergePolicy(mp);
IndexWriter w = new IndexWriter(ramDir, iwc);
// add few more docs:
for (int j = 0; j < RANDOM_MULTIPLIER * Random().Next(30); j++)
{
AddDoc(w, id++);
}
w.Dispose(false);
}
// add dummy segments (which are all in current
// version) to single segment index
MergePolicy mp_ = Random().NextBoolean() ? (MergePolicy)NewLogMergePolicy() : NewTieredMergePolicy();
IndexWriterConfig iwc_ = (new IndexWriterConfig(TEST_VERSION_CURRENT, null)).SetMergePolicy(mp_);
IndexWriter w_ = new IndexWriter(dir, iwc_);
w_.AddIndexes(ramDir);
w_.Dispose(false);
// determine count of segments in modified index
int origSegCount = GetNumberOfSegments(dir);
(new IndexUpgrader(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, null), false)).Upgrade();
int segCount = CheckAllSegmentsUpgraded(dir);
Assert.AreEqual(origSegCount, segCount, "Index must still contain the same number of segments, as only one segment was upgraded and nothing else merged");
dir.Dispose();
}
}
public const string SurrogatesIndexName = "index.36.surrogates.zip";
[Test]
public virtual void TestSurrogates()
{
DirectoryInfo oldIndexDir = CreateTempDir("surrogates");
TestUtil.Unzip(GetDataFile(SurrogatesIndexName), oldIndexDir);
Directory dir = NewFSDirectory(oldIndexDir);
// TODO: more tests
TestUtil.CheckIndex(dir);
dir.Dispose();
}
/*
* Index with negative positions (LUCENE-1542)
* Created with this code, using a 2.4.0 jar, then upgraded with 3.6 upgrader:
*
* public class CreateBogusIndexes {
* public static void main(String args[]) throws Exception {
* Directory d = FSDirectory.getDirectory("/tmp/bogus24");
* IndexWriter iw = new IndexWriter(d, new StandardAnalyzer());
* Document doc = new Document();
* Token brokenToken = new Token("broken", 0, 3);
* brokenToken.setPositionIncrement(0);
* Token okToken = new Token("ok", 0, 2);
* doc.Add(new Field("field1", new CannedTokenStream(brokenToken), Field.TermVector.NO));
* doc.Add(new Field("field2", new CannedTokenStream(brokenToken), Field.TermVector.WITH_POSITIONS));
* doc.Add(new Field("field3", new CannedTokenStream(brokenToken, okToken), Field.TermVector.NO));
* doc.Add(new Field("field4", new CannedTokenStream(brokenToken, okToken), Field.TermVector.WITH_POSITIONS));
* iw.AddDocument(doc);
* doc = new Document();
* doc.Add(new Field("field1", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED));
* doc.Add(new Field("field2", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
* doc.Add(new Field("field3", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED));
* doc.Add(new Field("field4", "just more text, not broken", Field.Store.NO, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS));
* iw.AddDocument(doc);
* iw.Dispose();
* d.Dispose();
* }
*
* static class CannedTokenStream extends TokenStream {
* private final Token[] tokens;
* private int upto = 0;
*
* CannedTokenStream(Token... tokens) {
* this.tokens = tokens;
* }
*
* @Override
* public Token next() {
* if (upto < tokens.Length) {
* return tokens[upto++];
* } else {
* return null;
* }
* }
* }
* }
*/
public const string Bogus24IndexName = "bogus24.upgraded.to.36.zip";
[Test]
public virtual void TestNegativePositions()
{
DirectoryInfo oldIndexDir = CreateTempDir("negatives");
TestUtil.Unzip(GetDataFile(Bogus24IndexName), oldIndexDir);
Directory dir = NewFSDirectory(oldIndexDir);
DirectoryReader ir = DirectoryReader.Open(dir);
IndexSearcher @is = new IndexSearcher(ir);
PhraseQuery pq = new PhraseQuery();
pq.Add(new Term("field3", "more"));
pq.Add(new Term("field3", "text"));
TopDocs td = @is.Search(pq, 10);
Assert.AreEqual(1, td.TotalHits);
AtomicReader wrapper = SlowCompositeReaderWrapper.Wrap(ir);
DocsAndPositionsEnum de = wrapper.TermPositionsEnum(new Term("field3", "broken"));
Debug.Assert(de != null);
Assert.AreEqual(0, de.NextDoc());
Assert.AreEqual(0, de.NextPosition());
ir.Dispose();
TestUtil.CheckIndex(dir);
dir.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
public class ArrayLastIndexOf1
{
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()
{
ArrayLastIndexOf1 ac = new ArrayLastIndexOf1();
TestLibrary.TestFramework.BeginTestCase("Array.LastInexOf(Array, object, int, int)");
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;
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()
{
bool retVal = true;
Array array;
int length;
int element;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest1: Array.LastInexOf(Array, object, int, int) where element is found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
element = TestLibrary.Generator.GetInt32(-55);
// fill the array
for (int i=0; i<array.Length; i++)
{
array.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (index > newIndex)
{
TestLibrary.TestFramework.LogError("000", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (element != (int)array.GetValue(newIndex))
{
TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + element + ") Actual(" + (int)array.GetValue(newIndex) + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
Array array;
int length;
string element;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest2: Array.LastInexOf(Array, object, int, int) non-primitive type");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(string), length);
element = TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN);
// fill the array
for (int i=0; i<array.Length; i++)
{
array.SetValue(TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), i);
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (index > newIndex)
{
TestLibrary.TestFramework.LogError("003", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (!element.Equals(array.GetValue(newIndex)))
{
TestLibrary.TestFramework.LogError("004", "Unexpected value: Expected(" + element + ") Actual(" + array.GetValue(newIndex) + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
Array array;
int length;
object element;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest3: Array.LastInexOf(Array, object, int, int) non-primitive type (with value == null)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(string), length);
element = null;
// fill the array
for (int i=0; i<array.Length; i++)
{
array.SetValue(TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), i);
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (index > newIndex)
{
TestLibrary.TestFramework.LogError("006", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (element != array.GetValue(newIndex))
{
TestLibrary.TestFramework.LogError("007", "Unexpected value: Expected(" + element + ") Actual(" + array.GetValue(newIndex) + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
Array array;
int length;
MyStruct element;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest4: Array.LastInexOf(Array, object, int, int) non-primitive type (not derived from object)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(MyStruct), length);
element = new MyStruct(TestLibrary.Generator.GetSingle(-55));
// fill the array
for (int i=0; i<array.Length; i++)
{
array.SetValue(new MyStruct(TestLibrary.Generator.GetSingle(-55)), i);
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (index > newIndex)
{
TestLibrary.TestFramework.LogError("009", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (element.f != ((MyStruct)array.GetValue(newIndex)).f)
{
TestLibrary.TestFramework.LogError("010", "Unexpected value: Expected(" + element.f + ") Actual(" + ((MyStruct)array.GetValue(newIndex)).f + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("011", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
Array array;
int length;
int element;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest1: Array.LastInexOf(Array, object, int, int) where element is not found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
element = TestLibrary.Generator.GetInt32(-55);
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue((object)TestLibrary.Generator.GetInt32(-55), i);
}
while (element == (int)array.GetValue(i));
}
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("012", "Unexpected index: Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("013", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
Array array;
int length;
int element;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest2: Array.LastInexOf(Array, object, int, int) array full of null's");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
element = TestLibrary.Generator.GetInt32(-55);
// fill the array
for (int i=0; i<array.Length; i++)
{
array.SetValue(null, i);
}
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("014", "Unexpected index: Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("015", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: Array.LastInexOf(Array, object, int, int) array is null");
try
{
Array.LastIndexOf(null, (object)1, 0, 0);
TestLibrary.TestFramework.LogError("016", "Should have thrown an expection");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("017", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
Array array;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest4: Array.LastInexOf(Array, object, int, int) array of length 0");
try
{
// creat the array
array = Array.CreateInstance(typeof(Int32), 0);
newIndex = Array.LastIndexOf(array, (object)null, array.Length-1, array.Length);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("018", "Unexpected index: Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("019", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest5: Array.LastInexOf(Array, object, int, int) start index less than lower bound");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.LastIndexOf(array, (object)null, -1, array.Length);
TestLibrary.TestFramework.LogError("020", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("021", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest6: Array.LastInexOf(Array, object, int, int) start index greater than upper bound");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.LastIndexOf(array, (object)null, array.Length, array.Length);
TestLibrary.TestFramework.LogError("022", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("023", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest7: Array.LastInexOf(Array, object, int, int) count less than 0");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.LastIndexOf(array, (object)null, array.Length-1, -1);
TestLibrary.TestFramework.LogError("024", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("025", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest8: Array.LastInexOf(Array, object, int, int) (count > startIndex - lb + 1)");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), length);
Array.LastIndexOf(array, (object)null, 0, array.Length);
TestLibrary.TestFramework.LogError("026", "Should have thrown an exception");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("027", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest9()
{
bool retVal = true;
Array array;
int length;
TestLibrary.TestFramework.BeginScenario("NegTest9: Array.LastInexOf(Array, object, int, int) multi dim array");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(Int32), new int[2] {length, length});
Array.LastIndexOf(array, (object)null, array.Length-1, array.Length);
TestLibrary.TestFramework.LogError("028", "Should have thrown an exception");
retVal = false;
}
catch (RankException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("029", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public struct MyStruct
{
public float f;
public MyStruct(float ff) { f = ff; }
}
public bool NegTest10()
{
bool retVal = true;
Array array;
int length;
MyStruct element;
int newIndex;
TestLibrary.TestFramework.BeginScenario("NegTest10: Array.LastInexOf(Array, object, int, int) non-primitive type (not derived from object) not found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = Array.CreateInstance(typeof(MyStruct), length);
element = new MyStruct(TestLibrary.Generator.GetSingle(-55));
// fill the array
for (int i=0; i<array.Length; i++)
{
do
{
array.SetValue(new MyStruct(TestLibrary.Generator.GetSingle(-55)), i);
}
while(element.Equals((MyStruct)array.GetValue(i)));
}
newIndex = Array.LastIndexOf(array, (object)element, array.Length-1, array.Length);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("030", "Unexpected index: Expected(-1) Actual(" + newIndex + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("031", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Cloud Runtime Configuration API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://cloud.google.com/deployment-manager/runtime-configurator/'>Google Cloud Runtime Configuration API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20170620 (901)
* <tr><th>API Docs
* <td><a href='https://cloud.google.com/deployment-manager/runtime-configurator/'>
* https://cloud.google.com/deployment-manager/runtime-configurator/</a>
* <tr><th>Discovery Name<td>runtimeconfig
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Cloud Runtime Configuration API can be found at
* <a href='https://cloud.google.com/deployment-manager/runtime-configurator/'>https://cloud.google.com/deployment-manager/runtime-configurator/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.CloudRuntimeConfig.v1
{
/// <summary>The CloudRuntimeConfig Service.</summary>
public class CloudRuntimeConfigService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudRuntimeConfigService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudRuntimeConfigService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
operations = new OperationsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "runtimeconfig"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://runtimeconfig.googleapis.com/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return ""; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://runtimeconfig.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Runtime Configuration API.</summary>
public class Scope
{
/// <summary>View and manage your data across Google Cloud Platform services</summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Manage your Google Cloud Platform services' runtime configuration</summary>
public static string Cloudruntimeconfig = "https://www.googleapis.com/auth/cloudruntimeconfig";
}
private readonly OperationsResource operations;
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations
{
get { return operations; }
}
}
///<summary>A base abstract class for CloudRuntimeConfig requests.</summary>
public abstract class CloudRuntimeConfigBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new CloudRuntimeConfigBaseServiceRequest instance.</summary>
protected CloudRuntimeConfigBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto,
}
/// <summary>OAuth bearer token.</summary>
[Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string BearerToken { get; set; }
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Pretty-print response.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> Pp { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudRuntimeConfig parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"bearer_token", new Google.Apis.Discovery.Parameter
{
Name = "bearer_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pp", new Google.Apis.Discovery.Parameter
{
Name = "pp",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to
/// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary>
public class CancelRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest body, string name)
: base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "cancel"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}:cancel"; }
}
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.+$",
});
}
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in
/// the operation result. It does not cancel the operation. If the server doesn't support this method, it
/// returns `google.rpc.Code.UNIMPLEMENTED`.</summary>
public class DeleteRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "delete"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "DELETE"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.+$",
});
}
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes,
/// such as `users/operations`. To override the binding, API services can add a binding such as
/// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default
/// name includes the operations collection id, however overriding users must ensure the name binding is the
/// parent resource, without the operations collection id.</summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this
/// method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes,
/// such as `users/operations`. To override the binding, API services can add a binding such as
/// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default
/// name includes the operations collection id, however overriding users must ensure the name binding is the
/// parent resource, without the operations collection id.</summary>
public class ListRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name)
: base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "v1/{+name}"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations$",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.CloudRuntimeConfig.v1.Data
{
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A
/// typical example is to use it as the request or the response type of an API method. For instance:
///
/// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// The JSON representation for `Empty` is empty JSON object `{}`.</summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>If the value is `false`, it means the operation is still in progress. If true, the operation is
/// completed, and either `error` or `response` is available.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>Service-specific metadata associated with the operation. It typically contains progress
/// information and common metadata such as create time. Some services might not provide such metadata. Any
/// method that returns a long-running operation should document the metadata type, if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; }
/// <summary>The server-assigned name, which is only unique within the same service that originally returns it.
/// If you use the default HTTP mapping, the `name` should have the format of
/// `operations/some/unique/name`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>The normal response of the operation in case of success. If the original method returns no data on
/// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name
/// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The `Status` type defines a logical error model that is suitable for different programming
/// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model
/// is designed to be:
///
/// - Simple to use and understand for most users - Flexible enough to meet unexpected needs
///
/// # Overview
///
/// The `Status` message contains three pieces of data: error code, error message, and error details. The error code
/// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error
/// message should be a developer-facing English message that helps developers *understand* and *resolve* the error.
/// If a localized user-facing error message is needed, put the localized message in the error details or localize
/// it in the client. The optional error details may contain arbitrary information about the error. There is a
/// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions.
///
/// # Language mapping
///
/// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire
/// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can
/// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped
/// to some error codes in C.
///
/// # Other uses
///
/// The error model and the `Status` message can be used in a variety of environments, either with or without APIs,
/// to provide a consistent developer experience across different environments.
///
/// Example uses of this error model include:
///
/// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the
/// normal response to indicate the partial errors.
///
/// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error
/// reporting.
///
/// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used
/// directly inside batch response, one for each error sub-response.
///
/// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of
/// those operations should be represented directly using the `Status` message.
///
/// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any
/// stripping needed for security/privacy reasons.</summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>A list of messages that carry the error details. There will be a common set of message types for
/// APIs to use.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; }
/// <summary>A developer-facing error message, which should be in English. Any user-facing error message should
/// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareScalarNotLessThanOrEqualDouble()
{
var test = new SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble testClass)
{
var result = Sse2.CompareScalarNotLessThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareScalarNotLessThanOrEqual(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarNotLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareScalarNotLessThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareScalarNotLessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarNotLessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareScalarNotLessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble();
var result = Sse2.CompareScalarNotLessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareScalarNotLessThanOrEqualDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareScalarNotLessThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareScalarNotLessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareScalarNotLessThanOrEqual(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] <= right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarNotLessThanOrEqual)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace Python.Runtime
{
[SuppressUnmanagedCodeSecurity]
internal static class NativeMethods
{
#if MONO_LINUX || MONO_OSX
private static int RTLD_NOW = 0x2;
private static int RTLD_SHARED = 0x20;
#if MONO_OSX
private static IntPtr RTLD_DEFAULT = new IntPtr(-2);
private const string NativeDll = "__Internal";
#elif MONO_LINUX
private static IntPtr RTLD_DEFAULT = IntPtr.Zero;
private const string NativeDll = "libdl.so";
#endif
public static IntPtr LoadLibrary(string fileName)
{
return dlopen(fileName, RTLD_NOW | RTLD_SHARED);
}
public static void FreeLibrary(IntPtr handle)
{
dlclose(handle);
}
public static IntPtr GetProcAddress(IntPtr dllHandle, string name)
{
// look in the exe if dllHandle is NULL
if (dllHandle == IntPtr.Zero)
{
dllHandle = RTLD_DEFAULT;
}
// clear previous errors if any
dlerror();
IntPtr res = dlsym(dllHandle, name);
IntPtr errPtr = dlerror();
if (errPtr != IntPtr.Zero)
{
throw new Exception("dlsym: " + Marshal.PtrToStringAnsi(errPtr));
}
return res;
}
[DllImport(NativeDll)]
private static extern IntPtr dlopen(String fileName, int flags);
[DllImport(NativeDll)]
private static extern IntPtr dlsym(IntPtr handle, String symbol);
[DllImport(NativeDll)]
private static extern int dlclose(IntPtr handle);
[DllImport(NativeDll)]
private static extern IntPtr dlerror();
#else // Windows
private const string NativeDll = "kernel32.dll";
[DllImport(NativeDll)]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport(NativeDll)]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport(NativeDll)]
public static extern bool FreeLibrary(IntPtr hModule);
#endif
}
/// <summary>
/// Encapsulates the low-level Python C API. Note that it is
/// the responsibility of the caller to have acquired the GIL
/// before calling any of these methods.
/// </summary>
public class Runtime
{
#if UCS4
public const int UCS = 4;
/// <summary>
/// EntryPoint to be used in DllImport to map to correct Unicode
/// methods prior to PEP393. Only used for PY27.
/// </summary>
private const string PyUnicodeEntryPoint = "PyUnicodeUCS4_";
#elif UCS2
public const int UCS = 2;
/// <summary>
/// EntryPoint to be used in DllImport to map to correct Unicode
/// methods prior to PEP393. Only used for PY27.
/// </summary>
private const string PyUnicodeEntryPoint = "PyUnicodeUCS2_";
#else
#error You must define either UCS2 or UCS4!
#endif
#if PYTHON27
public const string pyversion = "2.7";
public const string pyver = "27";
#elif PYTHON33
public const string pyversion = "3.3";
public const string pyver = "33";
#elif PYTHON34
public const string pyversion = "3.4";
public const string pyver = "34";
#elif PYTHON35
public const string pyversion = "3.5";
public const string pyver = "35";
#elif PYTHON36
public const string pyversion = "3.6";
public const string pyver = "36";
#elif PYTHON37 // TODO: Add `interop37.cs` after PY37 is released
public const string pyversion = "3.7";
public const string pyver = "37";
#else
#error You must define one of PYTHON33 to PYTHON37 or PYTHON27
#endif
#if MONO_LINUX || MONO_OSX // Linux/macOS use dotted version string
internal const string dllBase = "python" + pyversion;
#else // Windows
internal const string dllBase = "python" + pyver;
#endif
#if PYTHON_WITH_PYDEBUG
internal const string dllWithPyDebug = "d";
#else
internal const string dllWithPyDebug = "";
#endif
#if PYTHON_WITH_PYMALLOC
internal const string dllWithPyMalloc = "m";
#else
internal const string dllWithPyMalloc = "";
#endif
#if PYTHON_WITHOUT_ENABLE_SHARED
public const string PythonDll = "__Internal";
#else
public const string PythonDll = dllBase + dllWithPyDebug + dllWithPyMalloc;
#endif
public static readonly int pyversionnumber = Convert.ToInt32(pyver);
// set to true when python is finalizing
internal static object IsFinalizingLock = new object();
internal static bool IsFinalizing;
internal static bool Is32Bit = IntPtr.Size == 4;
internal static bool IsPython2 = pyversionnumber < 30;
internal static bool IsPython3 = pyversionnumber >= 30;
/// <summary>
/// Encoding to use to convert Unicode to/from Managed to Native
/// </summary>
internal static readonly Encoding PyEncoding = UCS == 2 ? Encoding.Unicode : Encoding.UTF32;
/// <summary>
/// Initialize the runtime...
/// </summary>
internal static void Initialize()
{
if (Py_IsInitialized() == 0)
{
Py_Initialize();
}
if (PyEval_ThreadsInitialized() == 0)
{
PyEval_InitThreads();
}
IntPtr op;
IntPtr dict;
if (IsPython3)
{
op = PyImport_ImportModule("builtins");
dict = PyObject_GetAttrString(op, "__dict__");
}
else // Python2
{
dict = PyImport_GetModuleDict();
op = PyDict_GetItemString(dict, "__builtin__");
}
PyNotImplemented = PyObject_GetAttrString(op, "NotImplemented");
PyBaseObjectType = PyObject_GetAttrString(op, "object");
PyModuleType = PyObject_Type(op);
PyNone = PyObject_GetAttrString(op, "None");
PyTrue = PyObject_GetAttrString(op, "True");
PyFalse = PyObject_GetAttrString(op, "False");
PyBoolType = PyObject_Type(PyTrue);
PyNoneType = PyObject_Type(PyNone);
PyTypeType = PyObject_Type(PyNoneType);
op = PyObject_GetAttrString(dict, "keys");
PyMethodType = PyObject_Type(op);
XDecref(op);
// For some arcane reason, builtins.__dict__.__setitem__ is *not*
// a wrapper_descriptor, even though dict.__setitem__ is.
//
// object.__init__ seems safe, though.
op = PyObject_GetAttrString(PyBaseObjectType, "__init__");
PyWrapperDescriptorType = PyObject_Type(op);
XDecref(op);
#if PYTHON3
XDecref(dict);
#endif
op = PyString_FromString("string");
PyStringType = PyObject_Type(op);
XDecref(op);
op = PyUnicode_FromString("unicode");
PyUnicodeType = PyObject_Type(op);
XDecref(op);
#if PYTHON3
op = PyBytes_FromString("bytes");
PyBytesType = PyObject_Type(op);
XDecref(op);
#endif
op = PyTuple_New(0);
PyTupleType = PyObject_Type(op);
XDecref(op);
op = PyList_New(0);
PyListType = PyObject_Type(op);
XDecref(op);
op = PyDict_New();
PyDictType = PyObject_Type(op);
XDecref(op);
op = PyInt_FromInt32(0);
PyIntType = PyObject_Type(op);
XDecref(op);
op = PyLong_FromLong(0);
PyLongType = PyObject_Type(op);
XDecref(op);
op = PyFloat_FromDouble(0);
PyFloatType = PyObject_Type(op);
XDecref(op);
#if PYTHON3
PyClassType = IntPtr.Zero;
PyInstanceType = IntPtr.Zero;
#elif PYTHON2
IntPtr s = PyString_FromString("_temp");
IntPtr d = PyDict_New();
IntPtr c = PyClass_New(IntPtr.Zero, d, s);
PyClassType = PyObject_Type(c);
IntPtr i = PyInstance_New(c, IntPtr.Zero, IntPtr.Zero);
PyInstanceType = PyObject_Type(i);
XDecref(s);
XDecref(i);
XDecref(c);
XDecref(d);
#endif
Error = new IntPtr(-1);
#if PYTHON3
IntPtr dllLocal = IntPtr.Zero;
if (PythonDll != "__Internal")
{
NativeMethods.LoadLibrary(PythonDll);
}
_PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dllLocal, "_PyObject_NextNotImplemented");
#if !(MONO_LINUX || MONO_OSX)
if (dllLocal != IntPtr.Zero)
{
NativeMethods.FreeLibrary(dllLocal);
}
#endif
#endif
// Initialize modules that depend on the runtime class.
AssemblyManager.Initialize();
PyCLRMetaType = MetaType.Initialize();
Exceptions.Initialize();
ImportHook.Initialize();
// Need to add the runtime directory to sys.path so that we
// can find built-in assemblies like System.Data, et. al.
string rtdir = RuntimeEnvironment.GetRuntimeDirectory();
IntPtr path = PySys_GetObject("path");
IntPtr item = PyString_FromString(rtdir);
PyList_Append(path, item);
XDecref(item);
AssemblyManager.UpdatePath();
}
internal static void Shutdown()
{
AssemblyManager.Shutdown();
Exceptions.Shutdown();
ImportHook.Shutdown();
Py_Finalize();
}
// called *without* the GIL acquired by clr._AtExit
internal static int AtExit()
{
lock (IsFinalizingLock)
{
IsFinalizing = true;
}
return 0;
}
internal static IntPtr Py_single_input = (IntPtr)256;
internal static IntPtr Py_file_input = (IntPtr)257;
internal static IntPtr Py_eval_input = (IntPtr)258;
internal static IntPtr PyBaseObjectType;
internal static IntPtr PyModuleType;
internal static IntPtr PyClassType;
internal static IntPtr PyInstanceType;
internal static IntPtr PyCLRMetaType;
internal static IntPtr PyMethodType;
internal static IntPtr PyWrapperDescriptorType;
internal static IntPtr PyUnicodeType;
internal static IntPtr PyStringType;
internal static IntPtr PyTupleType;
internal static IntPtr PyListType;
internal static IntPtr PyDictType;
internal static IntPtr PyIntType;
internal static IntPtr PyLongType;
internal static IntPtr PyFloatType;
internal static IntPtr PyBoolType;
internal static IntPtr PyNoneType;
internal static IntPtr PyTypeType;
#if PYTHON3
internal static IntPtr PyBytesType;
internal static IntPtr _PyObject_NextNotImplemented;
#endif
internal static IntPtr PyNotImplemented;
internal const int Py_LT = 0;
internal const int Py_LE = 1;
internal const int Py_EQ = 2;
internal const int Py_NE = 3;
internal const int Py_GT = 4;
internal const int Py_GE = 5;
internal static IntPtr PyTrue;
internal static IntPtr PyFalse;
internal static IntPtr PyNone;
internal static IntPtr Error;
/// <summary>
/// Check if any Python Exceptions occurred.
/// If any exist throw new PythonException.
/// </summary>
/// <remarks>
/// Can be used instead of `obj == IntPtr.Zero` for example.
/// </remarks>
internal static void CheckExceptionOccurred()
{
if (PyErr_Occurred() != 0)
{
throw new PythonException();
}
}
internal static IntPtr GetBoundArgTuple(IntPtr obj, IntPtr args)
{
if (PyObject_TYPE(args) != PyTupleType)
{
Exceptions.SetError(Exceptions.TypeError, "tuple expected");
return IntPtr.Zero;
}
int size = PyTuple_Size(args);
IntPtr items = PyTuple_New(size + 1);
PyTuple_SetItem(items, 0, obj);
XIncref(obj);
for (var i = 0; i < size; i++)
{
IntPtr item = PyTuple_GetItem(args, i);
XIncref(item);
PyTuple_SetItem(items, i + 1, item);
}
return items;
}
internal static IntPtr ExtendTuple(IntPtr t, params IntPtr[] args)
{
int size = PyTuple_Size(t);
int add = args.Length;
IntPtr item;
IntPtr items = PyTuple_New(size + add);
for (var i = 0; i < size; i++)
{
item = PyTuple_GetItem(t, i);
XIncref(item);
PyTuple_SetItem(items, i, item);
}
for (var n = 0; n < add; n++)
{
item = args[n];
XIncref(item);
PyTuple_SetItem(items, size + n, item);
}
return items;
}
internal static Type[] PythonArgsToTypeArray(IntPtr arg)
{
return PythonArgsToTypeArray(arg, false);
}
internal static Type[] PythonArgsToTypeArray(IntPtr arg, bool mangleObjects)
{
// Given a PyObject * that is either a single type object or a
// tuple of (managed or unmanaged) type objects, return a Type[]
// containing the CLR Type objects that map to those types.
IntPtr args = arg;
var free = false;
if (!PyTuple_Check(arg))
{
args = PyTuple_New(1);
XIncref(arg);
PyTuple_SetItem(args, 0, arg);
free = true;
}
int n = PyTuple_Size(args);
var types = new Type[n];
Type t = null;
for (var i = 0; i < n; i++)
{
IntPtr op = PyTuple_GetItem(args, i);
if (mangleObjects && (!PyType_Check(op)))
{
op = PyObject_TYPE(op);
}
ManagedType mt = ManagedType.GetManagedObject(op);
if (mt is ClassBase)
{
t = ((ClassBase)mt).type;
}
else if (mt is CLRObject)
{
object inst = ((CLRObject)mt).inst;
if (inst is Type)
{
t = inst as Type;
}
}
else
{
t = Converter.GetTypeByAlias(op);
}
if (t == null)
{
types = null;
break;
}
types[i] = t;
}
if (free)
{
XDecref(args);
}
return types;
}
/// <summary>
/// Managed exports of the Python C API. Where appropriate, we do
/// some optimization to avoid managed <--> unmanaged transitions
/// (mostly for heavily used methods).
/// </summary>
internal static unsafe void XIncref(IntPtr op)
{
#if PYTHON_WITH_PYDEBUG
Py_IncRef(op);
return;
#else
var p = (void*)op;
if ((void*)0 != p)
{
if (Is32Bit)
{
(*(int*)p)++;
}
else
{
(*(long*)p)++;
}
}
#endif
}
internal static unsafe void XDecref(IntPtr op)
{
#if PYTHON_WITH_PYDEBUG
Py_DecRef(op);
return;
#else
var p = (void*)op;
if ((void*)0 != p)
{
if (Is32Bit)
{
--(*(int*)p);
}
else
{
--(*(long*)p);
}
if ((*(int*)p) == 0)
{
// PyObject_HEAD: struct _typeobject *ob_type
void* t = Is32Bit
? (void*)(*((uint*)p + 1))
: (void*)(*((ulong*)p + 1));
// PyTypeObject: destructor tp_dealloc
void* f = Is32Bit
? (void*)(*((uint*)t + 6))
: (void*)(*((ulong*)t + 6));
if ((void*)0 == f)
{
return;
}
NativeCall.Impl.Void_Call_1(new IntPtr(f), op);
}
}
#endif
}
internal static unsafe long Refcount(IntPtr op)
{
var p = (void*)op;
if ((void*)0 == p)
{
return 0;
}
return Is32Bit ? (*(int*)p) : (*(long*)p);
}
/// <summary>
/// Export of Macro Py_XIncRef. Use XIncref instead.
/// Limit this function usage for Testing and Py_Debug builds
/// </summary>
/// <param name="ob">PyObject Ptr</param>
[DllImport(PythonDll)]
internal static extern void Py_IncRef(IntPtr ob);
/// <summary>
/// Export of Macro Py_XDecRef. Use XDecref instead.
/// Limit this function usage for Testing and Py_Debug builds
/// </summary>
/// <param name="ob">PyObject Ptr</param>
[DllImport(PythonDll)]
internal static extern void Py_DecRef(IntPtr ob);
[DllImport(PythonDll)]
internal static extern void Py_Initialize();
[DllImport(PythonDll)]
internal static extern int Py_IsInitialized();
[DllImport(PythonDll)]
internal static extern void Py_Finalize();
[DllImport(PythonDll)]
internal static extern IntPtr Py_NewInterpreter();
[DllImport(PythonDll)]
internal static extern void Py_EndInterpreter(IntPtr threadState);
[DllImport(PythonDll)]
internal static extern IntPtr PyThreadState_New(IntPtr istate);
[DllImport(PythonDll)]
internal static extern IntPtr PyThreadState_Get();
[DllImport(PythonDll)]
internal static extern IntPtr PyThread_get_key_value(IntPtr key);
[DllImport(PythonDll)]
internal static extern int PyThread_get_thread_ident();
[DllImport(PythonDll)]
internal static extern int PyThread_set_key_value(IntPtr key, IntPtr value);
[DllImport(PythonDll)]
internal static extern IntPtr PyThreadState_Swap(IntPtr key);
[DllImport(PythonDll)]
internal static extern IntPtr PyGILState_Ensure();
[DllImport(PythonDll)]
internal static extern void PyGILState_Release(IntPtr gs);
[DllImport(PythonDll)]
internal static extern IntPtr PyGILState_GetThisThreadState();
#if PYTHON3
[DllImport(PythonDll)]
public static extern int Py_Main(
int argc,
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv
);
#elif PYTHON2
[DllImport(PythonDll)]
public static extern int Py_Main(int argc, string[] argv);
#endif
[DllImport(PythonDll)]
internal static extern void PyEval_InitThreads();
[DllImport(PythonDll)]
internal static extern int PyEval_ThreadsInitialized();
[DllImport(PythonDll)]
internal static extern void PyEval_AcquireLock();
[DllImport(PythonDll)]
internal static extern void PyEval_ReleaseLock();
[DllImport(PythonDll)]
internal static extern void PyEval_AcquireThread(IntPtr tstate);
[DllImport(PythonDll)]
internal static extern void PyEval_ReleaseThread(IntPtr tstate);
[DllImport(PythonDll)]
internal static extern IntPtr PyEval_SaveThread();
[DllImport(PythonDll)]
internal static extern void PyEval_RestoreThread(IntPtr tstate);
[DllImport(PythonDll)]
internal static extern IntPtr PyEval_GetBuiltins();
[DllImport(PythonDll)]
internal static extern IntPtr PyEval_GetGlobals();
[DllImport(PythonDll)]
internal static extern IntPtr PyEval_GetLocals();
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetProgramName();
[DllImport(PythonDll)]
internal static extern void Py_SetProgramName(IntPtr name);
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetPythonHome();
[DllImport(PythonDll)]
internal static extern void Py_SetPythonHome(IntPtr home);
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetPath();
[DllImport(PythonDll)]
internal static extern void Py_SetPath(IntPtr home);
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetVersion();
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetPlatform();
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetCopyright();
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetCompiler();
[DllImport(PythonDll)]
internal static extern IntPtr Py_GetBuildInfo();
[DllImport(PythonDll)]
internal static extern int PyRun_SimpleString(string code);
[DllImport(PythonDll)]
internal static extern IntPtr PyRun_String(string code, IntPtr st, IntPtr globals, IntPtr locals);
[DllImport(PythonDll)]
internal static extern IntPtr Py_CompileString(string code, string file, IntPtr tok);
[DllImport(PythonDll)]
internal static extern IntPtr PyImport_ExecCodeModule(string name, IntPtr code);
[DllImport(PythonDll)]
internal static extern IntPtr PyCFunction_NewEx(IntPtr ml, IntPtr self, IntPtr mod);
[DllImport(PythonDll)]
internal static extern IntPtr PyCFunction_Call(IntPtr func, IntPtr args, IntPtr kw);
[DllImport(PythonDll)]
internal static extern IntPtr PyClass_New(IntPtr bases, IntPtr dict, IntPtr name);
[DllImport(PythonDll)]
internal static extern IntPtr PyInstance_New(IntPtr cls, IntPtr args, IntPtr kw);
[DllImport(PythonDll)]
internal static extern IntPtr PyInstance_NewRaw(IntPtr cls, IntPtr dict);
[DllImport(PythonDll)]
internal static extern IntPtr PyMethod_New(IntPtr func, IntPtr self, IntPtr cls);
//====================================================================
// Python abstract object API
//====================================================================
/// <summary>
/// A macro-like method to get the type of a Python object. This is
/// designed to be lean and mean in IL & avoid managed <-> unmanaged
/// transitions. Note that this does not incref the type object.
/// </summary>
internal static unsafe IntPtr PyObject_TYPE(IntPtr op)
{
var p = (void*)op;
if ((void*)0 == p)
{
return IntPtr.Zero;
}
#if PYTHON_WITH_PYDEBUG
var n = 3;
#else
var n = 1;
#endif
return Is32Bit
? new IntPtr((void*)(*((uint*)p + n)))
: new IntPtr((void*)(*((ulong*)p + n)));
}
/// <summary>
/// Managed version of the standard Python C API PyObject_Type call.
/// This version avoids a managed <-> unmanaged transition.
/// This one does incref the returned type object.
/// </summary>
internal static IntPtr PyObject_Type(IntPtr op)
{
IntPtr tp = PyObject_TYPE(op);
XIncref(tp);
return tp;
}
internal static string PyObject_GetTypeName(IntPtr op)
{
IntPtr pyType = Marshal.ReadIntPtr(op, ObjectOffset.ob_type);
IntPtr ppName = Marshal.ReadIntPtr(pyType, TypeOffset.tp_name);
return Marshal.PtrToStringAnsi(ppName);
}
[DllImport(PythonDll)]
internal static extern int PyObject_HasAttrString(IntPtr pointer, string name);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_GetAttrString(IntPtr pointer, string name);
[DllImport(PythonDll)]
internal static extern int PyObject_SetAttrString(IntPtr pointer, string name, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyObject_HasAttr(IntPtr pointer, IntPtr name);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_GetAttr(IntPtr pointer, IntPtr name);
[DllImport(PythonDll)]
internal static extern int PyObject_SetAttr(IntPtr pointer, IntPtr name, IntPtr value);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_GetItem(IntPtr pointer, IntPtr key);
[DllImport(PythonDll)]
internal static extern int PyObject_SetItem(IntPtr pointer, IntPtr key, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyObject_DelItem(IntPtr pointer, IntPtr key);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_GetIter(IntPtr op);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_Call(IntPtr pointer, IntPtr args, IntPtr kw);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_CallObject(IntPtr pointer, IntPtr args);
#if PYTHON3
[DllImport(PythonDll)]
internal static extern int PyObject_RichCompareBool(IntPtr value1, IntPtr value2, int opid);
internal static int PyObject_Compare(IntPtr value1, IntPtr value2)
{
int res;
res = PyObject_RichCompareBool(value1, value2, Py_LT);
if (-1 == res)
return -1;
else if (1 == res)
return -1;
res = PyObject_RichCompareBool(value1, value2, Py_EQ);
if (-1 == res)
return -1;
else if (1 == res)
return 0;
res = PyObject_RichCompareBool(value1, value2, Py_GT);
if (-1 == res)
return -1;
else if (1 == res)
return 1;
Exceptions.SetError(Exceptions.SystemError, "Error comparing objects");
return -1;
}
#elif PYTHON2
[DllImport(PythonDll)]
internal static extern int PyObject_Compare(IntPtr value1, IntPtr value2);
#endif
[DllImport(PythonDll)]
internal static extern int PyObject_IsInstance(IntPtr ob, IntPtr type);
[DllImport(PythonDll)]
internal static extern int PyObject_IsSubclass(IntPtr ob, IntPtr type);
[DllImport(PythonDll)]
internal static extern int PyCallable_Check(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PyObject_IsTrue(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PyObject_Not(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PyObject_Size(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_Hash(IntPtr op);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_Repr(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_Str(IntPtr pointer);
#if PYTHON3
[DllImport(PythonDll, EntryPoint = "PyObject_Str")]
internal static extern IntPtr PyObject_Unicode(IntPtr pointer);
#elif PYTHON2
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_Unicode(IntPtr pointer);
#endif
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_Dir(IntPtr pointer);
//====================================================================
// Python number API
//====================================================================
#if PYTHON3
[DllImport(PythonDll, EntryPoint = "PyNumber_Long")]
internal static extern IntPtr PyNumber_Int(IntPtr ob);
#elif PYTHON2
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Int(IntPtr ob);
#endif
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Long(IntPtr ob);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Float(IntPtr ob);
[DllImport(PythonDll)]
internal static extern bool PyNumber_Check(IntPtr ob);
internal static bool PyInt_Check(IntPtr ob)
{
return PyObject_TypeCheck(ob, PyIntType);
}
internal static bool PyBool_Check(IntPtr ob)
{
return PyObject_TypeCheck(ob, PyBoolType);
}
internal static IntPtr PyInt_FromInt32(int value)
{
var v = new IntPtr(value);
return PyInt_FromLong(v);
}
internal static IntPtr PyInt_FromInt64(long value)
{
var v = new IntPtr(value);
return PyInt_FromLong(v);
}
#if PYTHON3
[DllImport(PythonDll, EntryPoint = "PyLong_FromLong")]
private static extern IntPtr PyInt_FromLong(IntPtr value);
[DllImport(PythonDll, EntryPoint = "PyLong_AsLong")]
internal static extern int PyInt_AsLong(IntPtr value);
[DllImport(PythonDll, EntryPoint = "PyLong_FromString")]
internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix);
[DllImport(PythonDll, EntryPoint = "PyLong_GetMax")]
internal static extern int PyInt_GetMax();
#elif PYTHON2
[DllImport(PythonDll)]
private static extern IntPtr PyInt_FromLong(IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyInt_AsLong(IntPtr value);
[DllImport(PythonDll)]
internal static extern IntPtr PyInt_FromString(string value, IntPtr end, int radix);
[DllImport(PythonDll)]
internal static extern int PyInt_GetMax();
#endif
internal static bool PyLong_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyLongType;
}
[DllImport(PythonDll)]
internal static extern IntPtr PyLong_FromLong(long value);
[DllImport(PythonDll)]
internal static extern IntPtr PyLong_FromUnsignedLong(uint value);
[DllImport(PythonDll)]
internal static extern IntPtr PyLong_FromDouble(double value);
[DllImport(PythonDll)]
internal static extern IntPtr PyLong_FromLongLong(long value);
[DllImport(PythonDll)]
internal static extern IntPtr PyLong_FromUnsignedLongLong(ulong value);
[DllImport(PythonDll)]
internal static extern IntPtr PyLong_FromString(string value, IntPtr end, int radix);
[DllImport(PythonDll)]
internal static extern int PyLong_AsLong(IntPtr value);
[DllImport(PythonDll)]
internal static extern uint PyLong_AsUnsignedLong(IntPtr value);
[DllImport(PythonDll)]
internal static extern long PyLong_AsLongLong(IntPtr value);
[DllImport(PythonDll)]
internal static extern ulong PyLong_AsUnsignedLongLong(IntPtr value);
internal static bool PyFloat_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyFloatType;
}
[DllImport(PythonDll)]
internal static extern IntPtr PyFloat_FromDouble(double value);
[DllImport(PythonDll)]
internal static extern IntPtr PyFloat_FromString(IntPtr value, IntPtr junk);
[DllImport(PythonDll)]
internal static extern double PyFloat_AsDouble(IntPtr ob);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Add(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Subtract(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Multiply(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Divide(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_And(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Xor(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Or(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Lshift(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Rshift(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Power(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Remainder(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceAdd(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceSubtract(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceMultiply(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceDivide(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceAnd(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceXor(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceOr(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceLshift(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceRshift(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlacePower(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_InPlaceRemainder(IntPtr o1, IntPtr o2);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Negative(IntPtr o1);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Positive(IntPtr o1);
[DllImport(PythonDll)]
internal static extern IntPtr PyNumber_Invert(IntPtr o1);
//====================================================================
// Python sequence API
//====================================================================
[DllImport(PythonDll)]
internal static extern bool PySequence_Check(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PySequence_GetItem(IntPtr pointer, int index);
[DllImport(PythonDll)]
internal static extern int PySequence_SetItem(IntPtr pointer, int index, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PySequence_DelItem(IntPtr pointer, int index);
[DllImport(PythonDll)]
internal static extern IntPtr PySequence_GetSlice(IntPtr pointer, int i1, int i2);
[DllImport(PythonDll)]
internal static extern int PySequence_SetSlice(IntPtr pointer, int i1, int i2, IntPtr v);
[DllImport(PythonDll)]
internal static extern int PySequence_DelSlice(IntPtr pointer, int i1, int i2);
[DllImport(PythonDll)]
internal static extern int PySequence_Size(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PySequence_Contains(IntPtr pointer, IntPtr item);
[DllImport(PythonDll)]
internal static extern IntPtr PySequence_Concat(IntPtr pointer, IntPtr other);
[DllImport(PythonDll)]
internal static extern IntPtr PySequence_Repeat(IntPtr pointer, int count);
[DllImport(PythonDll)]
internal static extern int PySequence_Index(IntPtr pointer, IntPtr item);
[DllImport(PythonDll)]
internal static extern int PySequence_Count(IntPtr pointer, IntPtr value);
[DllImport(PythonDll)]
internal static extern IntPtr PySequence_Tuple(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PySequence_List(IntPtr pointer);
//====================================================================
// Python string API
//====================================================================
internal static bool IsStringType(IntPtr op)
{
IntPtr t = PyObject_TYPE(op);
return (t == PyStringType) || (t == PyUnicodeType);
}
internal static bool PyString_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyStringType;
}
internal static IntPtr PyString_FromString(string value)
{
return PyString_FromStringAndSize(value, value.Length);
}
#if PYTHON3
[DllImport(PythonDll)]
internal static extern IntPtr PyBytes_FromString(string op);
[DllImport(PythonDll)]
internal static extern int PyBytes_Size(IntPtr op);
internal static IntPtr PyBytes_AS_STRING(IntPtr ob)
{
return ob + BytesOffset.ob_sval;
}
[DllImport(PythonDll, EntryPoint = "PyUnicode_FromStringAndSize")]
internal static extern IntPtr PyString_FromStringAndSize(
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8Marshaler))] string value,
int size
);
[DllImport(PythonDll)]
internal static extern IntPtr PyUnicode_FromStringAndSize(IntPtr value, int size);
#elif PYTHON2
[DllImport(PythonDll)]
internal static extern IntPtr PyString_FromStringAndSize(string value, int size);
[DllImport(PythonDll)]
internal static extern IntPtr PyString_AsString(IntPtr op);
[DllImport(PythonDll)]
internal static extern int PyString_Size(IntPtr pointer);
#endif
internal static bool PyUnicode_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyUnicodeType;
}
#if PYTHON3
[DllImport(PythonDll)]
internal static extern IntPtr PyUnicode_FromObject(IntPtr ob);
[DllImport(PythonDll)]
internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err);
[DllImport(PythonDll)]
internal static extern IntPtr PyUnicode_FromKindAndData(
int kind,
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s,
int size
);
internal static IntPtr PyUnicode_FromUnicode(string s, int size)
{
return PyUnicode_FromKindAndData(UCS, s, size);
}
[DllImport(PythonDll)]
internal static extern int PyUnicode_GetSize(IntPtr ob);
[DllImport(PythonDll)]
internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob);
[DllImport(PythonDll)]
internal static extern IntPtr PyUnicode_FromOrdinal(int c);
#elif PYTHON2
[DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromObject")]
internal static extern IntPtr PyUnicode_FromObject(IntPtr ob);
[DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromEncodedObject")]
internal static extern IntPtr PyUnicode_FromEncodedObject(IntPtr ob, IntPtr enc, IntPtr err);
[DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromUnicode")]
internal static extern IntPtr PyUnicode_FromUnicode(
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(UcsMarshaler))] string s,
int size
);
[DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "GetSize")]
internal static extern int PyUnicode_GetSize(IntPtr ob);
[DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "AsUnicode")]
internal static extern IntPtr PyUnicode_AsUnicode(IntPtr ob);
[DllImport(PythonDll, EntryPoint = PyUnicodeEntryPoint + "FromOrdinal")]
internal static extern IntPtr PyUnicode_FromOrdinal(int c);
#endif
internal static IntPtr PyUnicode_FromString(string s)
{
return PyUnicode_FromUnicode(s, s.Length);
}
/// <summary>
/// Function to access the internal PyUnicode/PyString object and
/// convert it to a managed string with the correct encoding.
/// </summary>
/// <remarks>
/// We can't easily do this through through the CustomMarshaler's on
/// the returns because will have access to the IntPtr but not size.
/// <para />
/// For PyUnicodeType, we can't convert with Marshal.PtrToStringUni
/// since it only works for UCS2.
/// </remarks>
/// <param name="op">PyStringType or PyUnicodeType object to convert</param>
/// <returns>Managed String</returns>
internal static string GetManagedString(IntPtr op)
{
IntPtr type = PyObject_TYPE(op);
#if PYTHON2 // Python 3 strings are all Unicode
if (type == PyStringType)
{
return Marshal.PtrToStringAnsi(PyString_AsString(op), PyString_Size(op));
}
#endif
if (type == PyUnicodeType)
{
IntPtr p = PyUnicode_AsUnicode(op);
int length = PyUnicode_GetSize(op);
int size = length * UCS;
var buffer = new byte[size];
Marshal.Copy(p, buffer, 0, size);
return PyEncoding.GetString(buffer, 0, size);
}
return null;
}
//====================================================================
// Python dictionary API
//====================================================================
internal static bool PyDict_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyDictType;
}
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_New();
[DllImport(PythonDll)]
internal static extern IntPtr PyDictProxy_New(IntPtr dict);
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_GetItem(IntPtr pointer, IntPtr key);
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_GetItemString(IntPtr pointer, string key);
[DllImport(PythonDll)]
internal static extern int PyDict_SetItem(IntPtr pointer, IntPtr key, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyDict_SetItemString(IntPtr pointer, string key, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyDict_DelItem(IntPtr pointer, IntPtr key);
[DllImport(PythonDll)]
internal static extern int PyDict_DelItemString(IntPtr pointer, string key);
[DllImport(PythonDll)]
internal static extern int PyMapping_HasKey(IntPtr pointer, IntPtr key);
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_Keys(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_Values(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_Items(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyDict_Copy(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PyDict_Update(IntPtr pointer, IntPtr other);
[DllImport(PythonDll)]
internal static extern void PyDict_Clear(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PyDict_Size(IntPtr pointer);
//====================================================================
// Python list API
//====================================================================
internal static bool PyList_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyListType;
}
[DllImport(PythonDll)]
internal static extern IntPtr PyList_New(int size);
[DllImport(PythonDll)]
internal static extern IntPtr PyList_AsTuple(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyList_GetItem(IntPtr pointer, int index);
[DllImport(PythonDll)]
internal static extern int PyList_SetItem(IntPtr pointer, int index, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyList_Insert(IntPtr pointer, int index, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyList_Append(IntPtr pointer, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyList_Reverse(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern int PyList_Sort(IntPtr pointer);
[DllImport(PythonDll)]
internal static extern IntPtr PyList_GetSlice(IntPtr pointer, int start, int end);
[DllImport(PythonDll)]
internal static extern int PyList_SetSlice(IntPtr pointer, int start, int end, IntPtr value);
[DllImport(PythonDll)]
internal static extern int PyList_Size(IntPtr pointer);
//====================================================================
// Python tuple API
//====================================================================
internal static bool PyTuple_Check(IntPtr ob)
{
return PyObject_TYPE(ob) == PyTupleType;
}
[DllImport(PythonDll)]
internal static extern IntPtr PyTuple_New(int size);
[DllImport(PythonDll)]
internal static extern IntPtr PyTuple_GetItem(IntPtr pointer, int index);
[DllImport(PythonDll)]
internal static extern int PyTuple_SetItem(IntPtr pointer, int index, IntPtr value);
[DllImport(PythonDll)]
internal static extern IntPtr PyTuple_GetSlice(IntPtr pointer, int start, int end);
[DllImport(PythonDll)]
internal static extern int PyTuple_Size(IntPtr pointer);
//====================================================================
// Python iterator API
//====================================================================
#if PYTHON2
[DllImport(PythonDll)]
internal static extern bool PyIter_Check(IntPtr pointer);
#elif PYTHON3
internal static bool PyIter_Check(IntPtr pointer)
{
var ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr));
IntPtr tp_iternext = ob_type + TypeOffset.tp_iternext;
return tp_iternext != null && tp_iternext != _PyObject_NextNotImplemented;
}
#endif
[DllImport(PythonDll)]
internal static extern IntPtr PyIter_Next(IntPtr pointer);
//====================================================================
// Python module API
//====================================================================
[DllImport(PythonDll)]
internal static extern IntPtr PyModule_New(string name);
[DllImport(PythonDll)]
internal static extern string PyModule_GetName(IntPtr module);
[DllImport(PythonDll)]
internal static extern IntPtr PyModule_GetDict(IntPtr module);
[DllImport(PythonDll)]
internal static extern string PyModule_GetFilename(IntPtr module);
#if PYTHON3
[DllImport(PythonDll)]
internal static extern IntPtr PyModule_Create2(IntPtr module, int apiver);
#endif
[DllImport(PythonDll)]
internal static extern IntPtr PyImport_Import(IntPtr name);
[DllImport(PythonDll)]
internal static extern IntPtr PyImport_ImportModule(string name);
[DllImport(PythonDll)]
internal static extern IntPtr PyImport_ReloadModule(IntPtr module);
[DllImport(PythonDll)]
internal static extern IntPtr PyImport_AddModule(string name);
[DllImport(PythonDll)]
internal static extern IntPtr PyImport_GetModuleDict();
#if PYTHON3
[DllImport(PythonDll)]
internal static extern void PySys_SetArgvEx(
int argc,
[MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(StrArrayMarshaler))] string[] argv,
int updatepath
);
#elif PYTHON2
[DllImport(PythonDll)]
internal static extern void PySys_SetArgvEx(
int argc,
string[] argv,
int updatepath
);
#endif
[DllImport(PythonDll)]
internal static extern IntPtr PySys_GetObject(string name);
[DllImport(PythonDll)]
internal static extern int PySys_SetObject(string name, IntPtr ob);
//====================================================================
// Python type object API
//====================================================================
internal static bool PyType_Check(IntPtr ob)
{
return PyObject_TypeCheck(ob, PyTypeType);
}
[DllImport(PythonDll)]
internal static extern void PyType_Modified(IntPtr type);
[DllImport(PythonDll)]
internal static extern bool PyType_IsSubtype(IntPtr t1, IntPtr t2);
internal static bool PyObject_TypeCheck(IntPtr ob, IntPtr tp)
{
IntPtr t = PyObject_TYPE(ob);
return (t == tp) || PyType_IsSubtype(t, tp);
}
[DllImport(PythonDll)]
internal static extern IntPtr PyType_GenericNew(IntPtr type, IntPtr args, IntPtr kw);
[DllImport(PythonDll)]
internal static extern IntPtr PyType_GenericAlloc(IntPtr type, int n);
[DllImport(PythonDll)]
internal static extern int PyType_Ready(IntPtr type);
[DllImport(PythonDll)]
internal static extern IntPtr _PyType_Lookup(IntPtr type, IntPtr name);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_GenericGetAttr(IntPtr obj, IntPtr name);
[DllImport(PythonDll)]
internal static extern int PyObject_GenericSetAttr(IntPtr obj, IntPtr name, IntPtr value);
[DllImport(PythonDll)]
internal static extern IntPtr _PyObject_GetDictPtr(IntPtr obj);
[DllImport(PythonDll)]
internal static extern IntPtr PyObject_GC_New(IntPtr tp);
[DllImport(PythonDll)]
internal static extern void PyObject_GC_Del(IntPtr tp);
[DllImport(PythonDll)]
internal static extern void PyObject_GC_Track(IntPtr tp);
[DllImport(PythonDll)]
internal static extern void PyObject_GC_UnTrack(IntPtr tp);
//====================================================================
// Python memory API
//====================================================================
[DllImport(PythonDll)]
internal static extern IntPtr PyMem_Malloc(int size);
[DllImport(PythonDll)]
internal static extern IntPtr PyMem_Realloc(IntPtr ptr, int size);
[DllImport(PythonDll)]
internal static extern void PyMem_Free(IntPtr ptr);
//====================================================================
// Python exception API
//====================================================================
[DllImport(PythonDll)]
internal static extern void PyErr_SetString(IntPtr ob, string message);
[DllImport(PythonDll)]
internal static extern void PyErr_SetObject(IntPtr ob, IntPtr message);
[DllImport(PythonDll)]
internal static extern IntPtr PyErr_SetFromErrno(IntPtr ob);
[DllImport(PythonDll)]
internal static extern void PyErr_SetNone(IntPtr ob);
[DllImport(PythonDll)]
internal static extern int PyErr_ExceptionMatches(IntPtr exception);
[DllImport(PythonDll)]
internal static extern int PyErr_GivenExceptionMatches(IntPtr ob, IntPtr val);
[DllImport(PythonDll)]
internal static extern void PyErr_NormalizeException(IntPtr ob, IntPtr val, IntPtr tb);
[DllImport(PythonDll)]
internal static extern int PyErr_Occurred();
[DllImport(PythonDll)]
internal static extern void PyErr_Fetch(ref IntPtr ob, ref IntPtr val, ref IntPtr tb);
[DllImport(PythonDll)]
internal static extern void PyErr_Restore(IntPtr ob, IntPtr val, IntPtr tb);
[DllImport(PythonDll)]
internal static extern void PyErr_Clear();
[DllImport(PythonDll)]
internal static extern void PyErr_Print();
//====================================================================
// Miscellaneous
//====================================================================
[DllImport(PythonDll)]
internal static extern IntPtr PyMethod_Self(IntPtr ob);
[DllImport(PythonDll)]
internal static extern IntPtr PyMethod_Function(IntPtr ob);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Serialization;
using Orleans.Serialization.Invocation;
namespace Orleans.Runtime
{
[GenerateSerializer]
[WellKnownId(101)]
internal sealed class Message
{
public const int LENGTH_HEADER_SIZE = 8;
public const int LENGTH_META_HEADER = 4;
[NonSerialized]
private string _targetHistory;
[NonSerialized]
private DateTime? _queuedTime;
[NonSerialized]
private int _retryCount;
public string TargetHistory
{
get { return _targetHistory; }
set { _targetHistory = value; }
}
public DateTime? QueuedTime
{
get { return _queuedTime; }
set { _queuedTime = value; }
}
public int RetryCount
{
get { return _retryCount; }
set { _retryCount = value; }
}
// Cache values of TargetAddess and SendingAddress as they are used very frequently
[Id(0)]
private ActivationAddress targetAddress;
[Id(1)]
private ActivationAddress sendingAddress;
static Message()
{
}
[GenerateSerializer]
public enum Categories
{
Ping,
System,
Application,
}
[GenerateSerializer]
public enum Directions
{
Request,
Response,
OneWay
}
[GenerateSerializer]
public enum ResponseTypes
{
Success,
Error,
Rejection,
Status
}
[GenerateSerializer]
public enum RejectionTypes
{
Transient,
Overloaded,
DuplicateRequest,
Unrecoverable,
GatewayTooBusy,
CacheInvalidation
}
[Id(2)]
internal HeadersContainer Headers { get; set; } = new HeadersContainer();
public Categories Category
{
get { return Headers.Category; }
set { Headers.Category = value; }
}
public Directions Direction
{
get { return Headers.Direction ?? default(Directions); }
set { Headers.Direction = value; }
}
public bool HasDirection => Headers.Direction.HasValue;
public bool IsReadOnly
{
get { return Headers.IsReadOnly; }
set { Headers.IsReadOnly = value; }
}
public bool IsAlwaysInterleave
{
get { return Headers.IsAlwaysInterleave; }
set { Headers.IsAlwaysInterleave = value; }
}
public bool IsUnordered
{
get { return Headers.IsUnordered; }
set { Headers.IsUnordered = value; }
}
public CorrelationId Id
{
get { return Headers.Id; }
set { Headers.Id = value; }
}
public int ForwardCount
{
get { return Headers.ForwardCount; }
set { Headers.ForwardCount = value; }
}
public SiloAddress TargetSilo
{
get { return Headers.TargetSilo; }
set
{
Headers.TargetSilo = value;
targetAddress = null;
}
}
public GrainId TargetGrain
{
get { return Headers.TargetGrain; }
set
{
Headers.TargetGrain = value;
targetAddress = null;
}
}
public ActivationId TargetActivation
{
get { return Headers.TargetActivation; }
set
{
Headers.TargetActivation = value;
targetAddress = null;
}
}
public bool IsFullyAddressed => TargetSilo is object && !TargetGrain.IsDefault && TargetActivation is object;
public ActivationAddress TargetAddress
{
get
{
if (targetAddress is object) return targetAddress;
if (!TargetGrain.IsDefault)
{
return targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation);
}
return null;
}
set
{
TargetGrain = value.Grain;
TargetActivation = value.Activation;
TargetSilo = value.Silo;
targetAddress = value;
}
}
public SiloAddress SendingSilo
{
get { return Headers.SendingSilo; }
set
{
Headers.SendingSilo = value;
sendingAddress = null;
}
}
public GrainId SendingGrain
{
get { return Headers.SendingGrain; }
set
{
Headers.SendingGrain = value;
sendingAddress = null;
}
}
public ActivationId SendingActivation
{
get { return Headers.SendingActivation; }
set
{
Headers.SendingActivation = value;
sendingAddress = null;
}
}
public CorrelationId CallChainId
{
get { return Headers.CallChainId; }
set { Headers.CallChainId = value; }
}
public ActivationAddress SendingAddress
{
get { return sendingAddress ?? (sendingAddress = ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation)); }
set
{
SendingGrain = value.Grain;
SendingActivation = value.Activation;
SendingSilo = value.Silo;
sendingAddress = value;
}
}
public bool IsNewPlacement
{
get { return Headers.IsNewPlacement; }
set
{
Headers.IsNewPlacement = value;
}
}
public ushort InterfaceVersion
{
get { return Headers.InterfaceVersion; }
set
{
Headers.InterfaceVersion = value;
}
}
public GrainInterfaceType InterfaceType
{
get { return Headers.InterfaceType; }
set
{
Headers.InterfaceType = value;
}
}
public ResponseTypes Result
{
get { return Headers.Result; }
set { Headers.Result = value; }
}
public TimeSpan? TimeToLive
{
get { return Headers.TimeToLive; }
set { Headers.TimeToLive = value; }
}
public bool IsExpired
{
get
{
if (!TimeToLive.HasValue)
return false;
return TimeToLive <= TimeSpan.Zero;
}
}
public bool IsExpirableMessage(bool dropExpiredMessages)
{
if (!dropExpiredMessages) return false;
GrainId id = TargetGrain;
if (id.IsDefault) return false;
// don't set expiration for one way, system target and system grain messages.
return Direction != Directions.OneWay && !id.IsSystemTarget();
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return Headers.CacheInvalidationHeader; }
set { Headers.CacheInvalidationHeader = value; }
}
public bool HasCacheInvalidationHeader => this.CacheInvalidationHeader != null
&& this.CacheInvalidationHeader.Count > 0;
internal void AddToCacheInvalidationHeader(ActivationAddress address)
{
var list = new List<ActivationAddress>();
if (CacheInvalidationHeader != null)
{
list.AddRange(CacheInvalidationHeader);
}
list.Add(address);
CacheInvalidationHeader = list;
}
public RejectionTypes RejectionType
{
get { return Headers.RejectionType; }
set { Headers.RejectionType = value; }
}
public string RejectionInfo
{
get { return GetNotNullString(Headers.RejectionInfo); }
set { Headers.RejectionInfo = value; }
}
public Dictionary<string, object> RequestContextData
{
get { return Headers.RequestContextData; }
set { Headers.RequestContextData = value; }
}
[Id(3)]
public object BodyObject { get; set; }
public void ClearTargetAddress()
{
targetAddress = null;
}
private static string GetNotNullString(string s)
{
return s ?? string.Empty;
}
/// <summary>
/// Tell whether two messages are duplicates of one another
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool IsDuplicate(Message other)
{
return Equals(SendingSilo, other.SendingSilo) && Equals(Id, other.Id);
}
// For testing and logging/tracing
public string ToLongString()
{
var sb = new StringBuilder();
AppendIfExists(HeadersContainer.Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader);
AppendIfExists(HeadersContainer.Headers.CATEGORY, sb, (m) => m.Category);
AppendIfExists(HeadersContainer.Headers.DIRECTION, sb, (m) => m.Direction);
AppendIfExists(HeadersContainer.Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive);
AppendIfExists(HeadersContainer.Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount);
AppendIfExists(HeadersContainer.Headers.CORRELATION_ID, sb, (m) => m.Id);
AppendIfExists(HeadersContainer.Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave);
AppendIfExists(HeadersContainer.Headers.IS_NEW_PLACEMENT, sb, (m) => m.IsNewPlacement);
AppendIfExists(HeadersContainer.Headers.READ_ONLY, sb, (m) => m.IsReadOnly);
AppendIfExists(HeadersContainer.Headers.IS_UNORDERED, sb, (m) => m.IsUnordered);
AppendIfExists(HeadersContainer.Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo);
AppendIfExists(HeadersContainer.Headers.REJECTION_TYPE, sb, (m) => m.RejectionType);
AppendIfExists(HeadersContainer.Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData);
AppendIfExists(HeadersContainer.Headers.RESULT, sb, (m) => m.Result);
AppendIfExists(HeadersContainer.Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation);
AppendIfExists(HeadersContainer.Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain);
AppendIfExists(HeadersContainer.Headers.SENDING_SILO, sb, (m) => m.SendingSilo);
AppendIfExists(HeadersContainer.Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation);
AppendIfExists(HeadersContainer.Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain);
AppendIfExists(HeadersContainer.Headers.CALL_CHAIN_ID, sb, (m) => m.CallChainId);
AppendIfExists(HeadersContainer.Headers.TARGET_SILO, sb, (m) => m.TargetSilo);
return sb.ToString();
}
private void AppendIfExists(HeadersContainer.Headers header, StringBuilder sb, Func<Message, object> valueProvider)
{
// used only under log3 level
if ((Headers.GetHeadersMask() & header) != HeadersContainer.Headers.NONE)
{
sb.AppendFormat("{0}={1};", header, valueProvider(this));
sb.AppendLine();
}
}
public override string ToString()
{
string response = String.Empty;
if (Direction == Directions.Response)
{
switch (Result)
{
case ResponseTypes.Error:
response = "Error ";
break;
case ResponseTypes.Rejection:
response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo);
break;
case ResponseTypes.Status:
response = "Status ";
break;
default:
break;
}
}
return String.Format("{0}{1}{2}{3}{4} {5}->{6}{7} #{8}{9}",
IsReadOnly ? "ReadOnly " : "", //0
IsAlwaysInterleave ? "IsAlwaysInterleave " : "", //1
IsNewPlacement ? "NewPlacement " : "", // 2
response, //3
Direction, //4
$"[{SendingSilo} {SendingGrain} {SendingActivation}]", //5
$"[{TargetSilo} {TargetGrain} {TargetActivation}]", //6
BodyObject is { } request ? $" {request}" : string.Empty, // 7
Id, //8
ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : ""); //9
}
public string GetTargetHistory()
{
var history = new StringBuilder();
history.Append("<");
if (TargetSilo != null)
{
history.Append(TargetSilo).Append(":");
}
if (!TargetGrain.IsDefault)
{
history.Append(TargetGrain).Append(":");
}
if (TargetActivation is object)
{
history.Append(TargetActivation);
}
history.Append(">");
if (!string.IsNullOrEmpty(TargetHistory))
{
history.Append(" ").Append(TargetHistory);
}
return history.ToString();
}
// For statistical measuring of time spent in queues.
[Id(4)]
private ITimeInterval timeInterval;
public void Start()
{
timeInterval = TimeIntervalFactory.CreateTimeInterval(true);
timeInterval.Start();
}
public void Stop()
{
timeInterval.Stop();
}
public void Restart()
{
timeInterval.Restart();
}
public TimeSpan Elapsed => timeInterval == null ? TimeSpan.Zero : timeInterval.Elapsed;
public static Message CreatePromptExceptionResponse(Message request, Exception exception)
{
return new Message
{
Category = request.Category,
Direction = Message.Directions.Response,
Result = Message.ResponseTypes.Error,
BodyObject = Response.FromException(exception)
};
}
[Serializable]
public class HeadersContainer
{
[Flags]
public enum Headers
{
NONE = 0,
ALWAYS_INTERLEAVE = 1 << 0,
CACHE_INVALIDATION_HEADER = 1 << 1,
CATEGORY = 1 << 2,
CORRELATION_ID = 1 << 3,
DEBUG_CONTEXT = 1 << 4, // No longer used
DIRECTION = 1 << 5,
TIME_TO_LIVE = 1 << 6,
FORWARD_COUNT = 1 << 7,
NEW_GRAIN_TYPE = 1 << 8,
GENERIC_GRAIN_TYPE = 1 << 9,
RESULT = 1 << 10,
REJECTION_INFO = 1 << 11,
REJECTION_TYPE = 1 << 12,
READ_ONLY = 1 << 13,
RESEND_COUNT = 1 << 14, // Support removed. Value retained for backwards compatibility.
SENDING_ACTIVATION = 1 << 15,
SENDING_GRAIN = 1 << 16,
SENDING_SILO = 1 << 17,
IS_NEW_PLACEMENT = 1 << 18,
TARGET_ACTIVATION = 1 << 19,
TARGET_GRAIN = 1 << 20,
TARGET_SILO = 1 << 21,
TARGET_OBSERVER = 1 << 22,
IS_UNORDERED = 1 << 23,
REQUEST_CONTEXT = 1 << 24,
INTERFACE_VERSION = 1 << 26,
CALL_CHAIN_ID = 1 << 29,
INTERFACE_TYPE = 1 << 31
// Do not add over int.MaxValue of these.
}
public Categories _category;
public Directions? _direction;
public bool _isReadOnly;
public bool _isAlwaysInterleave;
public bool _isUnordered;
public CorrelationId _id;
public int _forwardCount;
public SiloAddress _targetSilo;
public GrainId _targetGrain;
public ActivationId _targetActivation;
public SiloAddress _sendingSilo;
public GrainId _sendingGrain;
public ActivationId _sendingActivation;
public bool _isNewPlacement;
public ushort _interfaceVersion;
public ResponseTypes _result;
public GrainInterfaceType interfaceType;
public TimeSpan? _timeToLive;
public List<ActivationAddress> _cacheInvalidationHeader;
public RejectionTypes _rejectionType;
public string _rejectionInfo;
public Dictionary<string, object> _requestContextData;
public CorrelationId _callChainId;
public readonly DateTime _localCreationTime;
public HeadersContainer()
{
_localCreationTime = DateTime.UtcNow;
}
public Categories Category
{
get { return _category; }
set
{
_category = value;
}
}
public Directions? Direction
{
get { return _direction; }
set
{
_direction = value;
}
}
public bool IsReadOnly
{
get { return _isReadOnly; }
set
{
_isReadOnly = value;
}
}
public bool IsAlwaysInterleave
{
get { return _isAlwaysInterleave; }
set
{
_isAlwaysInterleave = value;
}
}
public bool IsUnordered
{
get { return _isUnordered; }
set
{
_isUnordered = value;
}
}
public CorrelationId Id
{
get { return _id; }
set
{
_id = value;
}
}
public int ForwardCount
{
get { return _forwardCount; }
set
{
_forwardCount = value;
}
}
public SiloAddress TargetSilo
{
get { return _targetSilo; }
set
{
_targetSilo = value;
}
}
public GrainId TargetGrain
{
get { return _targetGrain; }
set
{
_targetGrain = value;
}
}
public ActivationId TargetActivation
{
get { return _targetActivation; }
set
{
_targetActivation = value;
}
}
public SiloAddress SendingSilo
{
get { return _sendingSilo; }
set
{
_sendingSilo = value;
}
}
public GrainId SendingGrain
{
get { return _sendingGrain; }
set
{
_sendingGrain = value;
}
}
public ActivationId SendingActivation
{
get { return _sendingActivation; }
set
{
_sendingActivation = value;
}
}
public bool IsNewPlacement
{
get { return _isNewPlacement; }
set
{
_isNewPlacement = value;
}
}
public ushort InterfaceVersion
{
get { return _interfaceVersion; }
set
{
_interfaceVersion = value;
}
}
public ResponseTypes Result
{
get { return _result; }
set
{
_result = value;
}
}
public TimeSpan? TimeToLive
{
get
{
return _timeToLive - (DateTime.UtcNow - _localCreationTime);
}
set
{
_timeToLive = value;
}
}
public List<ActivationAddress> CacheInvalidationHeader
{
get { return _cacheInvalidationHeader; }
set
{
_cacheInvalidationHeader = value;
}
}
public RejectionTypes RejectionType
{
get { return _rejectionType; }
set
{
_rejectionType = value;
}
}
public string RejectionInfo
{
get { return _rejectionInfo; }
set
{
_rejectionInfo = value;
}
}
public Dictionary<string, object> RequestContextData
{
get { return _requestContextData; }
set
{
_requestContextData = value;
}
}
public CorrelationId CallChainId
{
get { return _callChainId; }
set
{
_callChainId = value;
}
}
public GrainInterfaceType InterfaceType
{
get { return interfaceType; }
set
{
interfaceType = value;
}
}
internal Headers GetHeadersMask()
{
Headers headers = Headers.NONE;
if (Category != default(Categories))
headers = headers | Headers.CATEGORY;
headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION;
if (IsReadOnly)
headers = headers | Headers.READ_ONLY;
if (IsAlwaysInterleave)
headers = headers | Headers.ALWAYS_INTERLEAVE;
if (IsUnordered)
headers = headers | Headers.IS_UNORDERED;
headers = _id.ToInt64() == 0 ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID;
if (_forwardCount != default(int))
headers = headers | Headers.FORWARD_COUNT;
headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO;
headers = _targetGrain.IsDefault ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN;
headers = _targetActivation is null ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION;
headers = _sendingSilo is null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO;
headers = _sendingGrain.IsDefault ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN;
headers = _sendingActivation is null ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION;
headers = _isNewPlacement == default(bool) ? headers & ~Headers.IS_NEW_PLACEMENT : headers | Headers.IS_NEW_PLACEMENT;
headers = _interfaceVersion == 0 ? headers & ~Headers.INTERFACE_VERSION : headers | Headers.INTERFACE_VERSION;
headers = _result == default(ResponseTypes) ? headers & ~Headers.RESULT : headers | Headers.RESULT;
headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE;
headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER;
headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE;
headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO;
headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT;
headers = _callChainId.ToInt64() == 0 ? headers & ~Headers.CALL_CHAIN_ID : headers | Headers.CALL_CHAIN_ID;
headers = interfaceType.IsDefault ? headers & ~Headers.INTERFACE_TYPE : headers | Headers.INTERFACE_TYPE;
return headers;
}
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void AsInt64()
{
var test = new VectorAs__AsInt64();
// Validates basic functionality works
test.RunBasicScenario();
// Validates basic functionality works using the generic form, rather than the type-specific form of the method
test.RunGenericScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorAs__AsInt64
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Vector64<Int64> value;
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<byte> byteResult = value.AsByte();
ValidateResult(byteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<double> doubleResult = value.AsDouble();
ValidateResult(doubleResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<short> shortResult = value.AsInt16();
ValidateResult(shortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<int> intResult = value.AsInt32();
ValidateResult(intResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<long> longResult = value.AsInt64();
ValidateResult(longResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<sbyte> sbyteResult = value.AsSByte();
ValidateResult(sbyteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<float> floatResult = value.AsSingle();
ValidateResult(floatResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<ushort> ushortResult = value.AsUInt16();
ValidateResult(ushortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<uint> uintResult = value.AsUInt32();
ValidateResult(uintResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<ulong> ulongResult = value.AsUInt64();
ValidateResult(ulongResult, value);
}
public void RunGenericScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunGenericScenario));
Vector64<Int64> value;
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<byte> byteResult = value.As<Int64, byte>();
ValidateResult(byteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<double> doubleResult = value.As<Int64, double>();
ValidateResult(doubleResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<short> shortResult = value.As<Int64, short>();
ValidateResult(shortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<int> intResult = value.As<Int64, int>();
ValidateResult(intResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<long> longResult = value.As<Int64, long>();
ValidateResult(longResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<sbyte> sbyteResult = value.As<Int64, sbyte>();
ValidateResult(sbyteResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<float> floatResult = value.As<Int64, float>();
ValidateResult(floatResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<ushort> ushortResult = value.As<Int64, ushort>();
ValidateResult(ushortResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<uint> uintResult = value.As<Int64, uint>();
ValidateResult(uintResult, value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
Vector64<ulong> ulongResult = value.As<Int64, ulong>();
ValidateResult(ulongResult, value);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Vector64<Int64> value;
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object byteResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsByte))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<byte>)(byteResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object doubleResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsDouble))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<double>)(doubleResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object shortResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsInt16))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<short>)(shortResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object intResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsInt32))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<int>)(intResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object longResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsInt64))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<long>)(longResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object sbyteResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsSByte))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<sbyte>)(sbyteResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object floatResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsSingle))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<float>)(floatResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object ushortResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsUInt16))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<ushort>)(ushortResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object uintResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsUInt32))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<uint>)(uintResult), value);
value = Vector64.Create(TestLibrary.Generator.GetInt64());
object ulongResult = typeof(Vector64)
.GetMethod(nameof(Vector64.AsUInt64))
.MakeGenericMethod(typeof(Int64))
.Invoke(null, new object[] { value });
ValidateResult((Vector64<ulong>)(ulongResult), value);
}
private void ValidateResult<T>(Vector64<T> result, Vector64<Int64> value, [CallerMemberName] string method = "")
where T : struct
{
Int64[] resultElements = new Int64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref resultElements[0]), result);
Int64[] valueElements = new Int64[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref valueElements[0]), value);
ValidateResult(resultElements, valueElements, typeof(T), method);
}
private void ValidateResult(Int64[] resultElements, Int64[] valueElements, Type targetType, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < ElementCount; i++)
{
if (resultElements[i] != valueElements[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Int64>.As{targetType.Name}: {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", valueElements)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", resultElements)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using static Elasticsearch.Net.AuditEvent;
namespace Elasticsearch.Net
{
public class RequestPipeline : IRequestPipeline
{
private readonly IConnectionConfigurationValues _settings;
private readonly IConnection _connection;
private readonly IConnectionPool _connectionPool;
private readonly IDateTimeProvider _dateTimeProvider;
private readonly IMemoryStreamFactory _memoryStreamFactory;
private readonly CancellationToken _cancellationToken;
private IRequestParameters RequestParameters { get; }
private IRequestConfiguration RequestConfiguration { get; }
public DateTime StartedOn { get; }
public List<Audit> AuditTrail { get; } = new List<Audit>();
private int _retried = 0;
public int Retried => _retried;
public RequestPipeline(
IConnectionConfigurationValues configurationValues,
IDateTimeProvider dateTimeProvider,
IMemoryStreamFactory memoryStreamFactory,
IRequestParameters requestParameters)
{
this._settings = configurationValues;
this._connectionPool = this._settings.ConnectionPool;
this._connection = this._settings.Connection;
this._dateTimeProvider = dateTimeProvider;
this._memoryStreamFactory = memoryStreamFactory;
this.RequestParameters = requestParameters;
this.RequestConfiguration = requestParameters?.RequestConfiguration;
this._cancellationToken = this.RequestConfiguration?.CancellationToken ?? CancellationToken.None;
this.StartedOn = dateTimeProvider.Now();
}
public int MaxRetries =>
this.RequestConfiguration?.ForceNode != null
? 0
: Math.Min(this.RequestConfiguration?.MaxRetries ?? this._settings.MaxRetries.GetValueOrDefault(int.MaxValue), this._connectionPool.MaxRetries);
public bool FirstPoolUsageNeedsSniffing =>
(!this.RequestConfiguration?.DisableSniff).GetValueOrDefault(true)
&& this._connectionPool.SupportsReseeding && this._settings.SniffsOnStartup && !this._connectionPool.SniffedOnStartup;
public bool SniffsOnConnectionFailure =>
(!this.RequestConfiguration?.DisableSniff).GetValueOrDefault(true)
&& this._connectionPool.SupportsReseeding && this._settings.SniffsOnConnectionFault;
public bool SniffsOnStaleCluster =>
(!this.RequestConfiguration?.DisableSniff).GetValueOrDefault(true)
&& this._connectionPool.SupportsReseeding && this._settings.SniffInformationLifeSpan.HasValue;
public bool StaleClusterState
{
get
{
if (!SniffsOnStaleCluster) return false;
// ReSharper disable once PossibleInvalidOperationException
// already checked by SniffsOnStaleCluster
var sniffLifeSpan = this._settings.SniffInformationLifeSpan.Value;
var now = this._dateTimeProvider.Now();
var lastSniff = this._connectionPool.LastUpdate;
return sniffLifeSpan < (now - lastSniff);
}
}
private bool PingDisabled(Node node) =>
(this.RequestConfiguration?.DisablePing).GetValueOrDefault(false)
|| this._settings.DisablePings || !this._connectionPool.SupportsPinging || !node.IsResurrected;
TimeSpan PingTimeout =>
this.RequestConfiguration?.PingTimeout
?? this._settings.PingTimeout
?? (this._connectionPool.UsingSsl ? ConnectionConfiguration.DefaultPingTimeoutOnSSL : ConnectionConfiguration.DefaultPingTimeout);
TimeSpan RequestTimeout => this.RequestConfiguration?.RequestTimeout ?? this._settings.RequestTimeout;
public bool IsTakingTooLong
{
get
{
var timeout = this._settings.MaxRetryTimeout.GetValueOrDefault(this.RequestTimeout);
var now = this._dateTimeProvider.Now();
//we apply a soft margin so that if a request timesout at 59 seconds when the maximum is 60 we also abort.
var margin = (timeout.TotalMilliseconds / 100.0) * 98;
var marginTimeSpan = TimeSpan.FromMilliseconds(margin);
var timespanCall = (now - this.StartedOn);
var tookToLong = timespanCall >= marginTimeSpan;
return tookToLong;
}
}
public bool Refresh { get; private set; }
public bool DepleededRetries => this.Retried >= this.MaxRetries + 1 || this.IsTakingTooLong;
private Auditable Audit(AuditEvent type) => new Auditable(type, this.AuditTrail, this._dateTimeProvider);
public void MarkDead(Node node)
{
var deadUntil = this._dateTimeProvider.DeadTime(node.FailedAttempts, this._settings.DeadTimeout, this._settings.MaxDeadTimeout);
node.MarkDead(deadUntil);
this._retried++;
}
public void MarkAlive(Node node) => node.MarkAlive();
public void FirstPoolUsage(SemaphoreSlim semaphore)
{
if (!this.FirstPoolUsageNeedsSniffing) return;
if (!semaphore.Wait(this._settings.RequestTimeout))
throw new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup, (Exception)null);
if (!this.FirstPoolUsageNeedsSniffing) return;
try
{
using (this.Audit(SniffOnStartup))
{
this.Sniff();
this._connectionPool.SniffedOnStartup = true;
}
}
finally
{
semaphore.Release();
}
}
public async Task FirstPoolUsageAsync(SemaphoreSlim semaphore)
{
if (!this.FirstPoolUsageNeedsSniffing) return;
var success = await semaphore.WaitAsync(this._settings.RequestTimeout, this._cancellationToken);
if (!success)
throw new PipelineException(PipelineFailure.CouldNotStartSniffOnStartup, (Exception)null);
if (!this.FirstPoolUsageNeedsSniffing) return;
try
{
using (this.Audit(SniffOnStartup))
{
await this.SniffAsync();
this._connectionPool.SniffedOnStartup = true;
}
}
finally
{
semaphore.Release();
}
}
public void SniffOnStaleCluster()
{
if (!StaleClusterState) return;
using (this.Audit(AuditEvent.SniffOnStaleCluster))
{
this.Sniff();
this._connectionPool.SniffedOnStartup = true;
}
}
public async Task SniffOnStaleClusterAsync()
{
if (!StaleClusterState) return;
using (this.Audit(AuditEvent.SniffOnStaleCluster))
{
await this.SniffAsync();
this._connectionPool.SniffedOnStartup = true;
}
}
public IEnumerable<Node> NextNode()
{
if (this.RequestConfiguration?.ForceNode != null)
{
yield return new Node(this.RequestConfiguration.ForceNode);
yield break;
}
//This for loop allows to break out of the view state machine if we need to
//force a refresh (after reseeding connectionpool). We have a hardcoded limit of only
//allowing 100 of these refreshes per call
var refreshed = false;
for (var i = 0; i < 100; i++)
{
if (this.DepleededRetries) yield break;
foreach (var node in this._connectionPool
.CreateView((e, n)=> { using (new Auditable(e, this.AuditTrail, this._dateTimeProvider) { Node = n }) {} })
.TakeWhile(node => !this.DepleededRetries))
{
yield return node;
if (!this.Refresh) continue;
this.Refresh = false;
refreshed = true;
break;
}
//unless a refresh was requested we will not iterate over more then a single view.
//keep in mind refreshes are also still bound to overall maxretry count/timeout.
if (!refreshed) break;
}
}
private RequestData CreatePingRequestData(Node node, Auditable audit)
{
audit.Node = node;
var requestOverrides = new RequestConfiguration
{
PingTimeout = this.PingTimeout,
RequestTimeout = this.RequestTimeout,
BasicAuthenticationCredentials = this._settings.BasicAuthenticationCredentials,
EnableHttpPipelining = this.RequestConfiguration?.EnableHttpPipelining ?? this._settings.HttpPipeliningEnabled,
ForceNode = this.RequestConfiguration?.ForceNode,
CancellationToken = this.RequestConfiguration?.CancellationToken ?? default(CancellationToken)
};
return new RequestData(HttpMethod.HEAD, "/", null, this._settings, requestOverrides, this._memoryStreamFactory) { Node = node };
}
public void Ping(Node node)
{
if (PingDisabled(node)) return;
using (var audit = this.Audit(PingSuccess))
{
try
{
var pingData = CreatePingRequestData(node, audit);
var response = this._connection.Request<VoidResponse>(pingData);
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//ping should not silently accept bad but valid http responses
if (!response.Success) throw new PipelineException(PipelineFailure.BadResponse);
}
catch (Exception e)
{
audit.Event = PingFailure;
audit.Exception = e;
throw new PipelineException(PipelineFailure.PingFailure, e);
}
}
}
public async Task PingAsync(Node node)
{
if (PingDisabled(node)) return;
using (var audit = this.Audit(PingSuccess))
{
try
{
var pingData = CreatePingRequestData(node, audit);
var response = await this._connection.RequestAsync<VoidResponse>(pingData);
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//ping should not silently accept bad but valid http responses
if (!response.Success) throw new PipelineException(PipelineFailure.BadResponse);
}
catch (Exception e)
{
audit.Event = PingFailure;
audit.Exception = e;
throw new PipelineException(PipelineFailure.PingFailure, e);
}
}
}
private void ThrowBadAuthPipelineExceptionWhenNeeded<TReturn>(ElasticsearchResponse<TReturn> response)
{
if (response.HttpStatusCode == 401)
throw new PipelineException(PipelineFailure.BadAuthentication, response.OriginalException);
}
public string SniffPath => "_nodes/_all/settings?flat_settings&timeout=" + this.PingTimeout.ToTimeUnit();
public IEnumerable<Node> SniffNodes => this._connectionPool
.CreateView((e, n)=> { using (new Auditable(e, this.AuditTrail, this._dateTimeProvider) { Node = n }) {} })
.ToList()
.OrderBy(n => n.MasterEligable ? n.Uri.Port : int.MaxValue);
public void SniffOnConnectionFailure()
{
if (!this.SniffsOnConnectionFailure) return;
using (this.Audit(SniffOnFail))
this.Sniff();
}
public async Task SniffOnConnectionFailureAsync()
{
if (!this.SniffsOnConnectionFailure) return;
using (this.Audit(SniffOnFail))
await this.SniffAsync();
}
public void Sniff()
{
var path = this.SniffPath;
var exceptions = new List<Exception>();
foreach (var node in this.SniffNodes)
{
using (var audit = this.Audit(SniffSuccess))
{
audit.Node = node;
try
{
var requestData = new RequestData(HttpMethod.GET, path, null, this._settings, this._memoryStreamFactory) { Node = node };
var response = this._connection.Request<SniffResponse>(requestData);
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//sniff should not silently accept bad but valid http responses
if (!response.Success) throw new PipelineException(PipelineFailure.BadResponse);
var nodes = response.Body.ToNodes(this._connectionPool.UsingSsl);
this._connectionPool.Reseed(nodes);
this.Refresh = true;
return;
}
catch (Exception e)
{
audit.Event = SniffFailure;
audit.Exception = e;
exceptions.Add(e);
continue;
}
}
}
throw new PipelineException(PipelineFailure.SniffFailure, new AggregateException(exceptions));
}
public async Task SniffAsync()
{
var path = this.SniffPath;
var exceptions = new List<Exception>();
foreach (var node in this.SniffNodes)
{
using (var audit = this.Audit(SniffSuccess))
{
audit.Node = node;
try
{
var requestData = new RequestData(HttpMethod.GET, path, null, this._settings, this._memoryStreamFactory) { Node = node };
var response = await this._connection.RequestAsync<SniffResponse>(requestData);
ThrowBadAuthPipelineExceptionWhenNeeded(response);
//sniff should not silently accept bad but valid http responses
if (!response.Success) throw new PipelineException(PipelineFailure.BadResponse);
this._connectionPool.Reseed(response.Body.ToNodes(this._connectionPool.UsingSsl));
this.Refresh = true;
return;
}
catch (Exception e)
{
audit.Event = SniffFailure;
audit.Exception = e;
exceptions.Add(e);
continue;
}
}
}
throw new PipelineException(PipelineFailure.SniffFailure, new AggregateException(exceptions));
}
public ElasticsearchResponse<TReturn> CallElasticsearch<TReturn>(RequestData requestData) where TReturn : class
{
using (var audit = this.Audit(HealthyResponse))
{
audit.Node = requestData.Node;
audit.Path = requestData.Path;
ElasticsearchResponse<TReturn> response = null;
try
{
response = this._connection.Request<TReturn>(requestData);
response.AuditTrail = this.AuditTrail;
ThrowBadAuthPipelineExceptionWhenNeeded(response);
if (!response.Success) audit.Event = AuditEvent.BadResponse;
return response;
}
catch (Exception e)
{
(response as ElasticsearchResponse<Stream>)?.Body?.Dispose();
audit.Event = AuditEvent.BadResponse;
audit.Exception = e;
e.RethrowKeepingStackTrace();
return null; //dead code due to call to RethrowKeepingStackTrace()
}
}
}
public async Task<ElasticsearchResponse<TReturn>> CallElasticsearchAsync<TReturn>(RequestData requestData) where TReturn : class
{
using (var audit = this.Audit(HealthyResponse))
{
audit.Node = requestData.Node;
audit.Path = requestData.Path;
ElasticsearchResponse<TReturn> response = null;
try
{
response = await this._connection.RequestAsync<TReturn>(requestData);
response.AuditTrail = this.AuditTrail;
ThrowBadAuthPipelineExceptionWhenNeeded(response);
if (!response.Success) audit.Event = AuditEvent.BadResponse;
return response;
}
catch (Exception e)
{
(response as ElasticsearchResponse<Stream>)?.Body?.Dispose();
audit.Event = AuditEvent.BadResponse;
audit.Exception = e;
e.RethrowKeepingStackTrace();
return null; //dead code due to call to RethrowKeepingStackTrace()
}
}
}
public void BadResponse<TReturn>(ref ElasticsearchResponse<TReturn> response, RequestData data, List<PipelineException> pipelineExceptions)
where TReturn : class
{
var pipelineFailure = PipelineFailure.BadResponse;
if (pipelineExceptions.HasAny())
pipelineFailure = pipelineExceptions.Last().FailureReason;
var innerException = pipelineExceptions.HasAny()
? new AggregateException(pipelineExceptions)
: response?.OriginalException;
var exceptionMessage = innerException?.Message ?? "Could not complete the request to Elasticsearch.";
if (this.IsTakingTooLong)
{
pipelineFailure = PipelineFailure.MaxTimeoutReached;
this.Audit(MaxTimeoutReached);
exceptionMessage = "Maximum timout reached while retrying request";
}
else if (this.Retried >= this.MaxRetries && this.MaxRetries > 0)
{
pipelineFailure = PipelineFailure.MaxRetriesReached;
this.Audit(MaxRetriesReached);
exceptionMessage = "Maximum number of retries reached.";
}
var clientException = new ElasticsearchClientException(pipelineFailure, exceptionMessage, innerException)
{
Request = data,
Response = response,
AuditTrail = this.AuditTrail
};
if (_settings.ThrowExceptions) throw clientException;
if (response == null)
response = new ResponseBuilder<TReturn>(data) { Exception = clientException }.ToResponse();
response.AuditTrail = this.AuditTrail;
}
public void Dispose()
{
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//
// Activator is an object that contains the Activation (CreateInstance/New)
// methods for late bound support.
//
//
//
//
namespace System {
using System;
using System.Reflection;
using System.Runtime.Remoting;
#if FEATURE_REMOTING
using System.Runtime.Remoting.Activation;
using Message = System.Runtime.Remoting.Messaging.Message;
#endif
using System.Security;
using CultureInfo = System.Globalization.CultureInfo;
using Evidence = System.Security.Policy.Evidence;
using StackCrawlMark = System.Threading.StackCrawlMark;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using AssemblyHashAlgorithm = System.Configuration.Assemblies.AssemblyHashAlgorithm;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
// Only statics, does not need to be marked with the serializable attribute
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_Activator))]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class Activator : _Activator
{
internal const int LookupMask = 0x000000FF;
internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public);
internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
// This class only contains statics, so hide the worthless constructor
private Activator()
{
}
// CreateInstance
// The following methods will create a new instance of an Object
// Full Binding Support
// For all of these methods we need to get the underlying RuntimeType and
// call the Impl version.
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture)
{
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes)
{
if ((object)type == null)
throw new ArgumentNullException("type");
Contract.EndContractBlock();
if (type is System.Reflection.Emit.TypeBuilder)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
// If they didn't specify a lookup, then we will provide the default lookup.
if ((bindingAttr & (BindingFlags) LookupMask) == 0)
bindingAttr |= Activator.ConstructorDefault;
if (activationAttributes != null && activationAttributes.Length > 0){
// If type does not derive from MBR
// throw notsupportedexception
#if FEATURE_REMOTING
if(type.IsMarshalByRef){
// The fix below is preventative.
//
if(!(type.IsContextful)){
if(activationAttributes.Length > 1 || !(activationAttributes[0] is UrlAttribute))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonUrlAttrOnMBR"));
}
}
else
#endif
throw new NotSupportedException(Environment.GetResourceString("NotSupported_ActivAttrOnNonMBR" ));
}
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"type");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceImpl(bindingAttr,binder,args,culture,activationAttributes, ref stackMark);
}
static public Object CreateInstance(Type type, params Object[] args)
{
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage) && type != null)
{
FrameworkEventSource.Log.ActivatorCreateInstance(type.GetFullNameForEtw());
}
#endif
return CreateInstance(type,
Activator.ConstructorDefault,
null,
args,
null,
null);
}
static public Object CreateInstance(Type type,
Object[] args,
Object[] activationAttributes)
{
return CreateInstance(type,
Activator.ConstructorDefault,
null,
args,
null,
activationAttributes);
}
static public Object CreateInstance(Type type)
{
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage) && type != null)
{
FrameworkEventSource.Log.ActivatorCreateInstance(type.GetFullNameForEtw());
}
#endif
return Activator.CreateInstance(type, false);
}
/*
* Create an instance using the name of type and the assembly where it exists. This allows
* types to be created remotely without having to load the type locally.
*/
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public ObjectHandle CreateInstance(String assemblyName,
String typeName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
null,
null,
ref stackMark);
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
Object[] activationAttributes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
activationAttributes,
null,
ref stackMark);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public Object CreateInstance(Type type, bool nonPublic)
{
if ((object)type == null)
throw new ArgumentNullException("type");
Contract.EndContractBlock();
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "type");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
static public T CreateInstance<T>()
{
RuntimeType rt = typeof(T) as RuntimeType;
#if !FEATURE_CORECLR
if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage) && rt != null)
{
FrameworkEventSource.Log.ActivatorCreateInstanceT(rt.GetFullNameForEtw());
}
#endif
// This is a hack to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[].
// Array, Ref, and Pointer types don't have default constructors.
if (rt.HasElementType)
throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor"));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
// Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions).
#if FEATURE_CORECLR
// In SL2/3 CreateInstance<T> doesn't do any security checks. This would mean that Assembly B can create instances of an internal
// type in Assembly A upon A's request:
// TypeInAssemblyA.DoWork() { AssemblyB.Create<InternalTypeInAssemblyA>();}
// TypeInAssemblyB.Create<T>() {return new T();}
// This violates type safety but we saw multiple user apps that have put a dependency on it. So for compatability we allow this if
// the SL app was built against SL2/3.
// Note that in SL2/3 it is possible for app code to instantiate public transparent types with public critical default constructors.
// Fortunately we don't have such types in out platform assemblies.
if (CompatibilitySwitches.IsAppEarlierThanSilverlight4 ||
CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
return (T)rt.CreateInstanceSlow(true /*publicOnly*/, true /*skipCheckThis*/, false /*fillCache*/, ref stackMark);
else
#endif // FEATURE_CORECLR
return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName)
{
return CreateInstanceFrom(assemblyFile, typeName, null);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
Object[] activationAttributes)
{
return CreateInstanceFrom(assemblyFile,
typeName,
false,
Activator.ConstructorDefault,
null,
null,
null,
activationAttributes);
}
[System.Security.SecuritySafeCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
securityInfo,
ref stackMark);
}
[SecuritySafeCritical]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public static ObjectHandle CreateInstance(string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
null,
ref stackMark);
}
[System.Security.SecurityCritical] // auto-generated
static internal ObjectHandle CreateInstance(String assemblyString,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo,
ref StackCrawlMark stackMark)
{
#if FEATURE_CAS_POLICY
if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
}
#endif // FEATURE_CAS_POLICY
Type type = null;
Assembly assembly = null;
if (assemblyString == null) {
assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
} else {
RuntimeAssembly assemblyFromResolveEvent;
AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent);
if (assemblyFromResolveEvent != null) {
// Assembly was resolved via AssemblyResolve event
assembly = assemblyFromResolveEvent;
} else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) {
// WinRT type - we have to use Type.GetType
type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase);
} else {
// Classic managed type
assembly = RuntimeAssembly.InternalLoadAssemblyName(
assemblyName, securityInfo, null, ref stackMark,
true /*thrownOnFileNotFound*/, false /*forIntrospection*/, false /*suppressSecurityChecks*/);
}
}
if (type == null) {
// It's classic managed type (not WinRT type)
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString);
if(assembly == null) return null;
type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase);
}
Object o = Activator.CreateInstance(type,
bindingAttr,
binder,
args,
culture,
activationAttributes);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if(o == null)
return null;
else {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo)
{
#if FEATURE_CAS_POLICY
if (securityInfo != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
}
#endif // FEATURE_CAS_POLICY
return CreateInstanceFromInternal(assemblyFile,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
securityInfo);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static ObjectHandle CreateInstanceFrom(string assemblyFile,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes)
{
return CreateInstanceFromInternal(assemblyFile,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
null);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static ObjectHandle CreateInstanceFromInternal(String assemblyFile,
String typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityInfo)
{
#if FEATURE_CAS_POLICY
Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled || securityInfo == null);
#endif // FEATURE_CAS_POLICY
#pragma warning disable 618
Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
#pragma warning restore 618
Type t = assembly.GetType(typeName, true, ignoreCase);
Object o = Activator.CreateInstance(t,
bindingAttr,
binder,
args,
culture,
activationAttributes);
Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if(o == null)
return null;
else {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
//
// This API is designed to be used when a host needs to execute code in an AppDomain
// with restricted security permissions. In that case, we demand in the client domain
// and assert in the server domain because the server domain might not be trusted enough
// to pass the security checks when activating the type.
//
[System.Security.SecurityCritical] // auto-generated_required
public static ObjectHandle CreateInstance (AppDomain domain, string assemblyName, string typeName) {
if (domain == null)
throw new ArgumentNullException("domain");
Contract.EndContractBlock();
return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName);
}
[System.Security.SecurityCritical] // auto-generated_required
[Obsolete("Methods which use evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstance which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static ObjectHandle CreateInstance (AppDomain domain,
string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes) {
if (domain == null)
throw new ArgumentNullException("domain");
Contract.EndContractBlock();
#if FEATURE_CAS_POLICY
if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
}
#endif // FEATURE_CAS_POLICY
return domain.InternalCreateInstanceWithNoSecurity(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
}
[SecurityCritical]
public static ObjectHandle CreateInstance(AppDomain domain,
string assemblyName,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes)
{
if (domain == null)
throw new ArgumentNullException("domain");
Contract.EndContractBlock();
return domain.InternalCreateInstanceWithNoSecurity(assemblyName,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
null);
}
//
// This API is designed to be used when a host needs to execute code in an AppDomain
// with restricted security permissions. In that case, we demand in the client domain
// and assert in the server domain because the server domain might not be trusted enough
// to pass the security checks when activating the type.
//
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) {
if (domain == null)
throw new ArgumentNullException("domain");
Contract.EndContractBlock();
return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName);
}
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
[Obsolete("Methods which use Evidence to sandbox are obsolete and will be removed in a future release of the .NET Framework. Please use an overload of CreateInstanceFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
public static ObjectHandle CreateInstanceFrom (AppDomain domain,
string assemblyFile,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes,
Evidence securityAttributes) {
if (domain == null)
throw new ArgumentNullException("domain");
Contract.EndContractBlock();
#if FEATURE_CAS_POLICY
if (securityAttributes != null && !AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_RequiresCasPolicyImplicit"));
}
#endif // FEATURE_CAS_POLICY
return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, securityAttributes);
}
[SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static ObjectHandle CreateInstanceFrom(AppDomain domain,
string assemblyFile,
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
object[] args,
CultureInfo culture,
object[] activationAttributes)
{
if (domain == null)
throw new ArgumentNullException("domain");
Contract.EndContractBlock();
return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile,
typeName,
ignoreCase,
bindingAttr,
binder,
args,
culture,
activationAttributes,
null);
}
#if FEATURE_COMINTEROP
#if FEATURE_CLICKONCE
[System.Security.SecuritySafeCritical] // auto-generated
public static ObjectHandle CreateInstance (ActivationContext activationContext) {
AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
if (domainManager == null)
domainManager = new AppDomainManager();
return domainManager.ApplicationActivator.CreateInstance(activationContext);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static ObjectHandle CreateInstance (ActivationContext activationContext, string[] activationCustomData) {
AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
if (domainManager == null)
domainManager = new AppDomainManager();
return domainManager.ApplicationActivator.CreateInstance(activationContext, activationCustomData);
}
#endif // FEATURE_CLICKONCE
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
String typeName)
{
return CreateComInstanceFrom(assemblyName,
typeName,
null,
AssemblyHashAlgorithm.None);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
String typeName,
byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm)
{
Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm);
Type t = assembly.GetType(typeName, true, false);
Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute),false);
if (Attr.Length > 0)
{
if (((ComVisibleAttribute)Attr[0]).Value == false)
throw new TypeLoadException(Environment.GetResourceString( "Argument_TypeMustBeVisibleFromCom" ));
}
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
if(assembly == null) return null;
Object o = Activator.CreateInstance(t,
Activator.ConstructorDefault,
null,
null,
null,
null);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
if(o == null)
return null;
else {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
}
#endif // FEATURE_COMINTEROP
#if FEATURE_REMOTING
// This method is a helper method and delegates to the remoting
// services to do the actual work.
[System.Security.SecurityCritical] // auto-generated_required
static public Object GetObject(Type type, String url)
{
return GetObject(type, url, null);
}
// This method is a helper method and delegates to the remoting
// services to do the actual work.
[System.Security.SecurityCritical] // auto-generated_required
static public Object GetObject(Type type, String url, Object state)
{
if (type == null)
throw new ArgumentNullException("type");
Contract.EndContractBlock();
return RemotingServices.Connect(type, url, state);
}
#endif
[System.Diagnostics.Conditional("_DEBUG")]
private static void Log(bool test, string title, string success, string failure)
{
#if FEATURE_REMOTING
if(test)
BCLDebug.Trace("REMOTE", "{0}{1}", title, success);
else
BCLDebug.Trace("REMOTE", "{0}{1}", title, failure);
#endif
}
void _Activator.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _Activator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _Activator.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _Activator.Invoke in VM\DangerousAPIs.h and
// include _Activator in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _Activator.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// MessageDisplayComponent.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace NetworkStateManagement
{
/// <summary>
/// Component implements the IMessageDisplay interface. This is used to show
/// notification messages when interesting events occur, for instance when
/// gamers join or leave the network session
/// </summary>
class MessageDisplayComponent : DrawableGameComponent, IMessageDisplay
{
#region Fields
SpriteBatch spriteBatch;
SpriteFont font;
// List of the currently visible notification messages.
List<NotificationMessage> messages = new List<NotificationMessage>();
// Coordinates threadsafe access to the message list.
object syncObject = new object();
// Tweakable settings control how long each message is visible.
static readonly TimeSpan fadeInTime = TimeSpan.FromSeconds(0.25);
static readonly TimeSpan showTime = TimeSpan.FromSeconds(5);
static readonly TimeSpan fadeOutTime = TimeSpan.FromSeconds(0.5);
#endregion
#region Initialization
/// <summary>
/// Constructs a new message display component.
/// </summary>
public MessageDisplayComponent(Game game)
: base(game)
{
// Register ourselves to implement the IMessageDisplay service.
game.Services.AddService(typeof(IMessageDisplay), this);
}
/// <summary>
/// Load graphics content for the message display.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Game.Content.Load<SpriteFont>("menufont");
}
#endregion
#region Update and Draw
/// <summary>
/// Updates the message display component.
/// </summary>
public override void Update(GameTime gameTime)
{
lock (syncObject)
{
int index = 0;
float targetPosition = 0;
// Update each message in turn.
while (index < messages.Count)
{
NotificationMessage message = messages[index];
// Gradually slide the message toward its desired position.
float positionDelta = targetPosition - message.Position;
float velocity = (float)gameTime.ElapsedGameTime.TotalSeconds * 2;
message.Position += positionDelta * Math.Min(velocity, 1);
// Update the age of the message.
message.Age += gameTime.ElapsedGameTime;
if (message.Age < showTime + fadeOutTime)
{
// This message is still alive.
index++;
// Any subsequent messages should be positioned below
// this one, unless it has started to fade out.
if (message.Age < showTime)
targetPosition++;
}
else
{
// This message is old, and should be removed.
messages.RemoveAt(index);
}
}
}
}
/// <summary>
/// Draws the message display component.
/// </summary>
public override void Draw(GameTime gameTime)
{
lock (syncObject)
{
// Early out if there are no messages to display.
if (messages.Count == 0)
return;
Vector2 position = new Vector2(GraphicsDevice.Viewport.Width - 100, 0);
spriteBatch.Begin();
// Draw each message in turn.
foreach (NotificationMessage message in messages)
{
const float scale = 0.75f;
// Compute the alpha of this message.
float alpha = 1;
if (message.Age < fadeInTime)
{
// Fading in.
alpha = (float)(message.Age.TotalSeconds /
fadeInTime.TotalSeconds);
}
else if (message.Age > showTime)
{
// Fading out.
TimeSpan fadeOut = showTime + fadeOutTime - message.Age;
alpha = (float)(fadeOut.TotalSeconds /
fadeOutTime.TotalSeconds);
}
// Compute the message position.
position.Y = 80 + message.Position * font.LineSpacing * scale;
// Compute an origin value to right align each message.
Vector2 origin = font.MeasureString(message.Text);
origin.Y = 0;
// Draw the message text, with a drop shadow.
spriteBatch.DrawString(font, message.Text, position + Vector2.One,
Color.Black * alpha, 0,
origin, scale, SpriteEffects.None, 0);
spriteBatch.DrawString(font, message.Text, position,
Color.White * alpha, 0,
origin, scale, SpriteEffects.None, 0);
}
spriteBatch.End();
}
}
#endregion
#region Implement IMessageDisplay
/// <summary>
/// Shows a new notification message.
/// </summary>
public void ShowMessage(string message, params object[] parameters)
{
string formattedMessage = string.Format(message, parameters);
lock (syncObject)
{
float startPosition = messages.Count;
messages.Add(new NotificationMessage(formattedMessage, startPosition));
}
}
#endregion
#region Nested Types
/// <summary>
/// Helper class stores the position and text of a single notification message.
/// </summary>
class NotificationMessage
{
public string Text;
public float Position;
public TimeSpan Age;
public NotificationMessage(string text, float position)
{
Text = text;
Position = position;
Age = TimeSpan.Zero;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Net.Mime;
using System.Text;
namespace System.Net.Mail
{
public enum MailPriority
{
Normal = 0,
Low = 1,
High = 2
}
internal class Message
{
#region Fields
private MailAddress _from;
private MailAddress _sender;
private MailAddressCollection _replyToList;
private MailAddress _replyTo;
private MailAddressCollection _to;
private MailAddressCollection _cc;
private MailAddressCollection _bcc;
private MimeBasePart _content;
private HeaderCollection _headers;
private HeaderCollection _envelopeHeaders;
private string _subject;
private Encoding _subjectEncoding;
private Encoding _headersEncoding;
private MailPriority _priority = (MailPriority)(-1);
#endregion Fields
#region Constructors
internal Message()
{
}
internal Message(string from, string to) : this()
{
if (from == null)
throw new ArgumentNullException(nameof(from));
if (to == null)
throw new ArgumentNullException(nameof(to));
if (from == string.Empty)
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(from)), nameof(from));
if (to == string.Empty)
throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(to)), nameof(to));
_from = new MailAddress(from);
MailAddressCollection collection = new MailAddressCollection();
collection.Add(to);
_to = collection;
}
internal Message(MailAddress from, MailAddress to) : this()
{
_from = from;
To.Add(to);
}
#endregion Constructors
#region Properties
public MailPriority Priority
{
get
{
return (((int)_priority == -1) ? MailPriority.Normal : _priority);
}
set
{
_priority = value;
}
}
internal MailAddress From
{
get
{
return _from;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_from = value;
}
}
internal MailAddress Sender
{
get
{
return _sender;
}
set
{
_sender = value;
}
}
internal MailAddress ReplyTo
{
get
{
return _replyTo;
}
set
{
_replyTo = value;
}
}
internal MailAddressCollection ReplyToList
{
get
{
if (_replyToList == null)
_replyToList = new MailAddressCollection();
return _replyToList;
}
}
internal MailAddressCollection To
{
get
{
if (_to == null)
_to = new MailAddressCollection();
return _to;
}
}
internal MailAddressCollection Bcc
{
get
{
if (_bcc == null)
_bcc = new MailAddressCollection();
return _bcc;
}
}
internal MailAddressCollection CC
{
get
{
if (_cc == null)
_cc = new MailAddressCollection();
return _cc;
}
}
internal string Subject
{
get
{
return _subject;
}
set
{
Encoding inputEncoding = null;
try
{
// extract the encoding from =?encoding?BorQ?blablalba?=
inputEncoding = MimeBasePart.DecodeEncoding(value);
}
catch (ArgumentException) { };
if (inputEncoding != null && value != null)
{
try
{
// Store the decoded value, we'll re-encode before sending
value = MimeBasePart.DecodeHeaderValue(value);
_subjectEncoding = _subjectEncoding ?? inputEncoding;
}
// Failed to decode, just pass it through as ascii (legacy)
catch (FormatException) { }
}
if (value != null && MailBnfHelper.HasCROrLF(value))
{
throw new ArgumentException(SR.MailSubjectInvalidFormat);
}
_subject = value;
if (_subject != null)
{
_subject = _subject.Normalize(NormalizationForm.FormC);
if (_subjectEncoding == null && !MimeBasePart.IsAscii(_subject, false))
{
_subjectEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
}
}
}
internal Encoding SubjectEncoding
{
get
{
return _subjectEncoding;
}
set
{
_subjectEncoding = value;
}
}
internal HeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = new HeaderCollection();
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _headers);
}
return _headers;
}
}
internal Encoding HeadersEncoding
{
get
{
return _headersEncoding;
}
set
{
_headersEncoding = value;
}
}
internal HeaderCollection EnvelopeHeaders
{
get
{
if (_envelopeHeaders == null)
{
_envelopeHeaders = new HeaderCollection();
if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _envelopeHeaders);
}
return _envelopeHeaders;
}
}
internal virtual MimeBasePart Content
{
get
{
return _content;
}
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_content = value;
}
}
#endregion Properties
#region Sending
internal void EmptySendCallback(IAsyncResult result)
{
Exception e = null;
if (result.CompletedSynchronously)
{
return;
}
EmptySendContext context = (EmptySendContext)result.AsyncState;
try
{
context._writer.EndGetContentStream(result).Close();
}
catch (Exception ex)
{
e = ex;
}
context._result.InvokeCallback(e);
}
internal class EmptySendContext
{
internal EmptySendContext(BaseWriter writer, LazyAsyncResult result)
{
_writer = writer;
_result = result;
}
internal LazyAsyncResult _result;
internal BaseWriter _writer;
}
internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
AsyncCallback callback, object state)
{
PrepareHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
if (Content != null)
{
return Content.BeginSend(writer, callback, allowUnicode, state);
}
else
{
LazyAsyncResult result = new LazyAsyncResult(this, state, callback);
IAsyncResult newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer, result));
if (newResult.CompletedSynchronously)
{
writer.EndGetContentStream(newResult).Close();
}
return result;
}
}
internal virtual void EndSend(IAsyncResult asyncResult)
{
if (asyncResult == null)
{
throw new ArgumentNullException(nameof(asyncResult));
}
if (Content != null)
{
Content.EndSend(asyncResult);
}
else
{
LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
{
throw new ArgumentException(SR.net_io_invalidasyncresult);
}
if (castedAsyncResult.EndCalled)
{
throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndSend)));
}
castedAsyncResult.InternalWaitForCompletion();
castedAsyncResult.EndCalled = true;
if (castedAsyncResult.Result is Exception)
{
throw (Exception)castedAsyncResult.Result;
}
}
}
internal virtual void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode)
{
if (sendEnvelope)
{
PrepareEnvelopeHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(EnvelopeHeaders, allowUnicode);
}
PrepareHeaders(sendEnvelope, allowUnicode);
writer.WriteHeaders(Headers, allowUnicode);
if (Content != null)
{
Content.Send(writer, allowUnicode);
}
else
{
writer.GetContentStream().Close();
}
}
internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode)
{
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
EncodeHeaders(EnvelopeHeaders, allowUnicode);
// Only add X-Sender header if it wasn't already set by the user
string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender);
if (!IsHeaderSet(xSenderHeader))
{
MailAddress sender = Sender ?? From;
EnvelopeHeaders.InternalSet(xSenderHeader, sender.Encode(xSenderHeader.Length, allowUnicode));
}
string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver);
EnvelopeHeaders.Remove(headerName);
foreach (MailAddress address in To)
{
EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode));
}
foreach (MailAddress address in CC)
{
EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode));
}
foreach (MailAddress address in Bcc)
{
EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode));
}
}
internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode)
{
string headerName;
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
//ContentType is written directly to the stream so remove potential user duplicate
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType));
Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0";
// add sender to headers first so that it is written first to allow the IIS smtp svc to
// send MAIL FROM with the sender if both sender and from are present
headerName = MailHeaderInfo.GetString(MailHeaderID.Sender);
if (Sender != null)
{
Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
headerName = MailHeaderInfo.GetString(MailHeaderID.From);
Headers.InternalAdd(headerName, From.Encode(headerName.Length, allowUnicode));
headerName = MailHeaderInfo.GetString(MailHeaderID.To);
if (To.Count > 0)
{
Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
headerName = MailHeaderInfo.GetString(MailHeaderID.Cc);
if (CC.Count > 0)
{
Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo);
if (ReplyTo != null)
{
Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode));
}
else if (ReplyToList.Count > 0)
{
Headers.InternalAdd(headerName, ReplyToList.Encode(headerName.Length, allowUnicode));
}
else
{
Headers.Remove(headerName);
}
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc));
if (_priority == MailPriority.High)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "1";
Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "urgent";
Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "high";
}
else if (_priority == MailPriority.Low)
{
Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "5";
Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "non-urgent";
Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "low";
}
//if the priority was never set, allow the app to set the headers directly.
else if (((int)_priority) != -1)
{
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority));
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority));
Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance));
}
Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date),
MailBnfHelper.GetDateTimeString(DateTime.Now, null));
headerName = MailHeaderInfo.GetString(MailHeaderID.Subject);
if (!string.IsNullOrEmpty(_subject))
{
if (allowUnicode)
{
Headers.InternalAdd(headerName, _subject);
}
else
{
Headers.InternalAdd(headerName,
MimeBasePart.EncodeHeaderValue(_subject, _subjectEncoding,
MimeBasePart.ShouldUseBase64Encoding(_subjectEncoding),
headerName.Length));
}
}
else
{
Headers.Remove(headerName);
}
EncodeHeaders(_headers, allowUnicode);
}
internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode)
{
if (_headersEncoding == null)
{
_headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
}
System.Diagnostics.Debug.Assert(_headersEncoding != null);
for (int i = 0; i < headers.Count; i++)
{
string headerName = headers.GetKey(i);
//certain well-known values are encoded by PrepareHeaders and PrepareEnvelopeHeaders
//so we can ignore them because either we encoded them already or there is no
//way for the user to have set them. If a header is well known and user settable then
//we should encode it here, otherwise we have already encoded it if necessary
if (!MailHeaderInfo.IsUserSettable(headerName))
{
continue;
}
string[] values = headers.GetValues(headerName);
string encodedValue = string.Empty;
for (int j = 0; j < values.Length; j++)
{
//encode if we need to
if (MimeBasePart.IsAscii(values[j], false)
|| (allowUnicode && MailHeaderInfo.AllowsUnicode(headerName) // EAI
&& !MailBnfHelper.HasCROrLF(values[j])))
{
encodedValue = values[j];
}
else
{
encodedValue = MimeBasePart.EncodeHeaderValue(values[j],
_headersEncoding,
MimeBasePart.ShouldUseBase64Encoding(_headersEncoding),
headerName.Length);
}
//potentially there are multiple values per key
if (j == 0)
{
//if it's the first or only value, set will overwrite all the values assigned to that key
//which is fine since we have them stored in values[]
headers.Set(headerName, encodedValue);
}
else
{
//this is a subsequent key, so we must Add it since the first key will have overwritten the
//other values
headers.Add(headerName, encodedValue);
}
}
}
}
private bool IsHeaderSet(string headerName)
{
for (int i = 0; i < Headers.Count; i++)
{
if (string.Equals(Headers.GetKey(i), headerName, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
#endregion Sending
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Primitives;
using Moq;
using NUnit.Framework;
namespace Azure.Extensions.AspNetCore.Configuration.Secrets.Tests
{
public class AzureKeyVaultConfigurationTests
{
private static readonly TimeSpan NoReloadDelay = TimeSpan.FromMilliseconds(1);
private void SetPages(Mock<SecretClient> mock, params KeyVaultSecret[][] pages)
{
SetPages(mock, null, pages);
}
private void SetPages(Mock<SecretClient> mock, Func<string, Task> getSecretCallback, params KeyVaultSecret[][] pages)
{
getSecretCallback ??= (_ => Task.CompletedTask);
var pagesOfProperties = pages.Select(
page => page.Select(secret => secret.Properties).ToArray()).ToArray();
mock.Setup(m => m.GetPropertiesOfSecretsAsync(default)).Returns(new MockAsyncPageable(pagesOfProperties));
foreach (var page in pages)
{
foreach (var secret in page)
{
mock.Setup(client => client.GetSecretAsync(secret.Name, null, default))
.Returns(async (string name, string label, CancellationToken token) =>
{
await getSecretCallback(name);
return Response.FromValue(secret, Mock.Of<Response>());
}
);
}
}
}
private class MockAsyncPageable : AsyncPageable<SecretProperties>
{
private readonly SecretProperties[][] _pages;
public MockAsyncPageable(SecretProperties[][] pages)
{
_pages = pages;
}
public override async IAsyncEnumerable<Page<SecretProperties>> AsPages(string continuationToken = null, int? pageSizeHint = null)
{
foreach (var page in _pages)
{
yield return Page<SecretProperties>.FromValues(page, null, Mock.Of<Response>());
}
await Task.CompletedTask;
}
}
[Test]
public void LoadsAllSecretsFromVault()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1")
},
new[]
{
CreateSecret("Secret2", "Value2")
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }))
{
provider.Load();
var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), null).ToArray();
Assert.AreEqual(new[] { "Secret1", "Secret2" }, childKeys);
Assert.AreEqual("Value1", provider.Get("Secret1"));
Assert.AreEqual("Value2", provider.Get("Secret2"));
}
}
private KeyVaultSecret CreateSecret(string name, string value, bool? enabled = true, DateTimeOffset? updated = null)
{
var id = new Uri("http://azure.keyvault/" + name);
var secretProperties = SecretModelFactory.SecretProperties(id, name: name, updatedOn: updated);
secretProperties.Enabled = enabled;
return SecretModelFactory.KeyVaultSecret(secretProperties, value);
}
[Test]
public void DoesNotLoadFilteredItems()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1")
},
new[]
{
CreateSecret("Secret2", "Value2")
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new EndsWithOneKeyVaultSecretManager() }))
{
provider.Load();
// Assert
var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), null).ToArray();
Assert.AreEqual(new[] { "Secret1" }, childKeys);
Assert.AreEqual("Value1", provider.Get("Secret1"));
}
}
[Test]
public void DoesNotLoadDisabledItems()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1")
},
new[]
{
CreateSecret("Secret2", "Value2", enabled: false),
CreateSecret("Secret3", "Value3", enabled: null),
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }))
{
provider.Load();
// Assert
var childKeys = provider.GetChildKeys(Enumerable.Empty<string>(), null).ToArray();
Assert.AreEqual(new[] { "Secret1" }, childKeys);
Assert.AreEqual("Value1", provider.Get("Secret1"));
Assert.Throws<InvalidOperationException>(() => provider.Get("Secret2"));
Assert.Throws<InvalidOperationException>(() => provider.Get("Secret3"));
}
}
[Test]
public void SupportsReload()
{
var updated = DateTime.Now;
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1", enabled: true, updated: updated)
}
);
// Act & Assert
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }))
{
provider.Load();
Assert.AreEqual("Value1", provider.Get("Secret1"));
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value2", enabled: true, updated: updated.AddSeconds(1))
}
);
provider.Load();
Assert.AreEqual("Value2", provider.Get("Secret1"));
}
}
[Test]
public async Task SupportsAutoReload()
{
var updated = DateTime.Now;
int numOfTokensFired = 0;
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1", enabled: true, updated: updated)
}
);
// Act & Assert
using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay))
{
ChangeToken.OnChange(
() => provider.GetReloadToken(),
() => {
numOfTokensFired++;
});
provider.Load();
Assert.AreEqual("Value1", provider.Get("Secret1"));
await provider.Wait();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value2", enabled: true, updated: updated.AddSeconds(1))
}
);
provider.Release();
await provider.Wait();
Assert.AreEqual("Value2", provider.Get("Secret1"));
Assert.AreEqual(1, numOfTokensFired);
}
}
[Test]
public async Task DoesntReloadUnchanged()
{
var updated = DateTime.Now;
int numOfTokensFired = 0;
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1", enabled: true, updated: updated)
}
);
// Act & Assert
using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay))
{
ChangeToken.OnChange(
() => provider.GetReloadToken(),
() => {
numOfTokensFired++;
});
provider.Load();
Assert.AreEqual("Value1", provider.Get("Secret1"));
await provider.Wait();
provider.Release();
await provider.Wait();
Assert.AreEqual("Value1", provider.Get("Secret1"));
Assert.AreEqual(0, numOfTokensFired);
}
}
[Test]
public async Task SupportsReloadOnRemove()
{
int numOfTokensFired = 0;
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1"),
CreateSecret("Secret2", "Value2")
}
);
// Act & Assert
using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay))
{
ChangeToken.OnChange(
() => provider.GetReloadToken(),
() => {
numOfTokensFired++;
});
provider.Load();
Assert.AreEqual("Value1", provider.Get("Secret1"));
await provider.Wait();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value2")
}
);
provider.Release();
await provider.Wait();
Assert.Throws<InvalidOperationException>(() => provider.Get("Secret2"));
Assert.AreEqual(1, numOfTokensFired);
}
}
[Test]
public async Task SupportsReloadOnEnabledChange()
{
int numOfTokensFired = 0;
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1"),
CreateSecret("Secret2", "Value2")
}
);
// Act & Assert
using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay))
{
ChangeToken.OnChange(
() => provider.GetReloadToken(),
() => {
numOfTokensFired++;
});
provider.Load();
Assert.AreEqual("Value2", provider.Get("Secret2"));
await provider.Wait();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value2"),
CreateSecret("Secret2", "Value2", enabled: false)
}
);
provider.Release();
await provider.Wait();
Assert.Throws<InvalidOperationException>(() => provider.Get("Secret2"));
Assert.AreEqual(1, numOfTokensFired);
}
}
[Test]
public async Task SupportsReloadOnAdd()
{
int numOfTokensFired = 0;
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1")
}
);
// Act & Assert
using (var provider = new ReloadControlKeyVaultProvider(client.Object, new KeyVaultSecretManager(), reloadPollDelay: NoReloadDelay))
{
ChangeToken.OnChange(
() => provider.GetReloadToken(),
() => {
numOfTokensFired++;
});
provider.Load();
Assert.AreEqual("Value1", provider.Get("Secret1"));
await provider.Wait();
SetPages(client,
new[]
{
CreateSecret("Secret1", "Value1"),
},
new[]
{
CreateSecret("Secret2", "Value2")
}
);
provider.Release();
await provider.Wait();
Assert.AreEqual("Value1", provider.Get("Secret1"));
Assert.AreEqual("Value2", provider.Get("Secret2"));
Assert.AreEqual(1, numOfTokensFired);
}
}
[Test]
public void ReplaceDoubleMinusInKeyName()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Section--Secret1", "Value1")
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }))
{
provider.Load();
// Assert
Assert.AreEqual("Value1", provider.Get("Section:Secret1"));
}
}
[Test]
public void ReturnsCaseInsensitiveDictionary()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Section--Secret1", "Value1")
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }))
{
provider.Load();
// Assert
Assert.AreEqual("Value1", provider.Get("section:secret1"));
}
}
[Test]
public void HandleCollisions()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Section---Secret1", "Value1")
},
new[]
{
CreateSecret("Section--Secret1", "Value2")
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManagerMultiDash() }))
{
provider.Load();
// Assert
Assert.AreEqual("Value1", provider.Get("Section:Secret1"));
}
}
[Test]
public void HandleCollisionsUseLatestValue()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Section----Secret1", "Value1", updated: new DateTimeOffset(new DateTime(2038, 1, 19), TimeSpan.Zero))
},
new[]
{
CreateSecret("Section---Secret1", "Value2", updated: new DateTimeOffset(new DateTime(2038, 1, 20), TimeSpan.Zero))
},
new[]
{
CreateSecret("Section--Secret1", "Value3", updated: new DateTimeOffset(new DateTime(2038, 1, 18), TimeSpan.Zero))
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManagerMultiDash() }))
{
provider.Load();
// Assert
Assert.AreEqual("Value2", provider.Get("Section:Secret1"));
}
}
[Test]
public void CanCustomizeSecretTransformation()
{
var client = new Mock<SecretClient>();
SetPages(client,
new[]
{
CreateSecret("Secret1", "{\"innerKey1\": \"innerValue1\", \"innerKey2\": \"innerValue2\"}", updated: new DateTimeOffset(new DateTime(2038, 1, 19), TimeSpan.Zero)),
CreateSecret("Secret2", "{\"innerKey3\": \"innerValue3\"}", updated: new DateTimeOffset(new DateTime(2038, 1, 18), TimeSpan.Zero))
}
);
// Act
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new JsonKeyVaultSecretManager() }))
{
provider.Load();
// Assert
Assert.AreEqual("innerValue1", provider.Get("innerKey1"));
Assert.AreEqual("innerValue2", provider.Get("innerKey2"));
Assert.AreEqual("innerValue3", provider.Get("innerKey3"));
}
}
[Test]
public async Task LoadsSecretsInParallel()
{
var tcs = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
var expectedCount = 2;
var client = new Mock<SecretClient>();
SetPages(client,
async (string id) =>
{
if (Interlocked.Decrement(ref expectedCount) == 0)
{
tcs.SetResult(null);
}
await tcs.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
},
new[]
{
CreateSecret("Secret1", "Value1"),
CreateSecret("Secret2", "Value2")
}
);
// Act
var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() });
provider.Load();
await tcs.Task;
// Assert
Assert.AreEqual("Value1", provider.Get("Secret1"));
Assert.AreEqual("Value2", provider.Get("Secret2"));
}
[Test]
public void LimitsMaxParallelism()
{
var expectedCount = 100;
var currentParallel = 0;
var maxParallel = 0;
var client = new Mock<SecretClient>();
// Create 10 pages of 10 secrets
var pages = Enumerable.Range(0, 10).Select(a =>
Enumerable.Range(0, 10).Select(b => CreateSecret("Secret" + (a * 10 + b), (a * 10 + b).ToString())).ToArray()
).ToArray();
SetPages(client,
async (string id) =>
{
var i = Interlocked.Increment(ref currentParallel);
maxParallel = Math.Max(i, maxParallel);
await Task.Delay(30);
Interlocked.Decrement(ref currentParallel);
},
pages
);
// Act
var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() });
provider.Load();
// Assert
for (int i = 0; i < expectedCount; i++)
{
Assert.AreEqual(i.ToString(), provider.Get("Secret" + i));
}
Assert.LessOrEqual(maxParallel, 32);
}
[Test]
public void ConstructorThrowsForNullManager()
{
Assert.Throws<ArgumentNullException>(() => new AzureKeyVaultConfigurationProvider(Mock.Of<SecretClient>(), new AzureKeyVaultConfigurationOptions() { Manager = null }));
}
[Test]
public void ConstructorThrowsForZeroRefreshPeriodValue()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new AzureKeyVaultConfigurationProvider(Mock.Of<SecretClient>(), new AzureKeyVaultConfigurationOptions() { ReloadInterval = TimeSpan.Zero }));
}
[Test]
public void ConstructorThrowsForNegativeRefreshPeriodValue()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new AzureKeyVaultConfigurationProvider(Mock.Of<SecretClient>(), new AzureKeyVaultConfigurationOptions() { ReloadInterval = TimeSpan.FromMilliseconds(-1) }));
}
[Test]
public void DisposeCanBeCalledMultipleTimes()
{
// Arrange
var client = new Mock<SecretClient>();
using (var provider = new AzureKeyVaultConfigurationProvider(client.Object, new AzureKeyVaultConfigurationOptions() { Manager = new KeyVaultSecretManager() }))
{
provider.Dispose();
// Act & Assert
Assert.DoesNotThrow(() => provider.Dispose());
}
}
private class EndsWithOneKeyVaultSecretManager : KeyVaultSecretManager
{
public override bool Load(SecretProperties secret)
{
return secret.Name.EndsWith("1");
}
}
private class ReloadControlKeyVaultProvider : AzureKeyVaultConfigurationProvider
{
private TaskCompletionSource<object> _releaseTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
private TaskCompletionSource<object> _signalTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
public ReloadControlKeyVaultProvider(SecretClient client, KeyVaultSecretManager manager, TimeSpan? reloadPollDelay = null)
: base(client, new AzureKeyVaultConfigurationOptions() { Manager = manager, ReloadInterval = reloadPollDelay})
{
}
internal override async Task WaitForReload()
{
_signalTaskCompletionSource.SetResult(null);
await _releaseTaskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
}
public async Task Wait()
{
await _signalTaskCompletionSource.Task.TimeoutAfter(TimeSpan.FromSeconds(10));
}
public void Release()
{
if (!_signalTaskCompletionSource.Task.IsCompleted)
{
throw new InvalidOperationException("Provider is not waiting for reload");
}
var releaseTaskCompletionSource = _releaseTaskCompletionSource;
_releaseTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
_signalTaskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
releaseTaskCompletionSource.SetResult(null);
}
}
private class KeyVaultSecretManagerMultiDash : KeyVaultSecretManager
{
public override string GetKey(KeyVaultSecret secret)
{
return secret.Name
.Replace("----", ConfigurationPath.KeyDelimiter)
.Replace("---", ConfigurationPath.KeyDelimiter)
.Replace("--", ConfigurationPath.KeyDelimiter);
}
}
private class JsonKeyVaultSecretManager: KeyVaultSecretManager
{
public override Dictionary<string, string> GetData(IEnumerable<KeyVaultSecret> secrets)
{
var data = new Dictionary<string, string>();
foreach (var secret in secrets)
{
using var doc = JsonDocument.Parse(secret.Value);
foreach (var property in doc.RootElement.EnumerateObject())
{
data[property.Name] = property.Value.GetString();
}
}
return data;
}
}
}
}
| |
using Cofoundry.Core;
using Cofoundry.Core.EntityFramework;
using Microsoft.EntityFrameworkCore;
namespace Cofoundry.Domain.Data
{
/// <summary>
/// The main Cofoundry entity framework DbContext representing all the main
/// entities in the Cofoundry database. Direct access to the <see cref="CofoundryDbContext"/>
/// is discouraged, instead we advise you use the domain queries and commands
/// available in the Cofoundry data repositories, see
/// https://www.cofoundry.org/docs/framework/data-access
/// </summary>
public partial class CofoundryDbContext : DbContext
{
private readonly ICofoundryDbContextInitializer _cofoundryDbContextInitializer;
public CofoundryDbContext(
ICofoundryDbContextInitializer cofoundryDbContextInitializer
)
{
_cofoundryDbContextInitializer = cofoundryDbContextInitializer;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
_cofoundryDbContextInitializer.Configure(this, optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder
.HasDefaultSchema(DbConstants.CofoundrySchema)
.MapCofoundryContent()
.ApplyConfiguration(new SettingMap())
.ApplyConfiguration(new RewriteRuleMap())
;
}
/// <summary>
/// <para>
/// Authorized tasks represent a single user-based operation that can be executed without
/// being logged in. Task authorization is validated by a crytographically random
/// generated token, often communicated via an out-of-band communication mechanism
/// such as an email. Examples include password reset or email address validation flows.
/// </para>
/// <para>
/// Tasks tend to be single-use and can be marked when completed, and can also be
/// invalidated explicitly. They can also be rate-limited by IPAddress and time-limited
/// by validating against the <see cref="CreateDate"/>.
/// </para>
/// </summary>
public DbSet<AuthorizedTask> AuthorizedTasks { get; set; }
/// <summary>
/// This queue keeps track of files belonging to assets that
/// have been deleted in the system. The files don't get deleted
/// at the same time as the asset record and instead are queued
/// and deleted by a background task to avoid issues with file
/// locking and other errors that may cause the delete operation
/// to fail. It also enabled the file deletion to run in a
/// transaction.
/// </summary>
public DbSet<AssetFileCleanupQueueItem> AssetFileCleanupQueueItems { get; set; }
/// <summary>
/// <para>
/// Custom entity definitions are used to define the identity and
/// behavior of a custom entity type. This includes meta data such
/// as the name and description, but also the configuration of
/// features such as whether the identity can contain a locale
/// and whether versioning (i.e. auto-publish) is enabled.
/// </para>
/// <para>
/// Definitions are defined in code by implementing ICustomEntityDefinition
/// but they are also stored in the database to help with queries and data
/// integrity.
/// </para>
/// <para>
/// The code definition is the source of truth and the database is updated
/// at runtime when an entity is added/updated. This is done via
/// EnsureCustomEntityDefinitionExistsCommand.
/// </para>
/// </summary>
public DbSet<CustomEntityDefinition> CustomEntityDefinitions { get; set; }
/// <summary>
/// <para>
/// Custom entities are a flexible system for developer defined
/// data structures. The identity for these entities are persisted in
/// this CustomEntity table, while the majority of data is versioned in
/// the CustomEntityVersion table.
/// </para>
/// <para>
/// The CustomEntityVersion table also contains the custom data model
/// data, which is serialized as unstructured data. Entity relations
/// on the unstructured data model are tracked via the
/// UnstructuredDataDependency table.
/// </para>
/// </summary>
public DbSet<CustomEntity> CustomEntities { get; set; }
/// <summary>
/// <para>
/// Custom entities can have one or more version, with a collection
/// of versions representing the change history of custom entity
/// data.
/// </para>
/// <para>
/// Only one draft version can exist at any one time, and
/// only one version may be published at any one time. Although
/// you can revert to a previous version, this is done by copying
/// the old version data to a new version, so that a full history is
/// always maintained.
/// </para>
/// <param>
/// Typically you should query for version data via the
/// CustomEntityPublishStatusQuery table, which serves as a quicker
/// look up for an applicable version for various PublishStatusQuery
/// states.
/// </param>
/// </summary>
public DbSet<CustomEntityVersion> CustomEntityVersions { get; set; }
/// <summary>
/// Page block data for a specific custom entity version on a custom entity
/// details page.
/// </summary>
public DbSet<CustomEntityVersionPageBlock> CustomEntityVersionPageBlocks { get; set; }
/// <summary>
/// Lookup cache used for quickly finding the correct version for a
/// specific publish status query e.g. 'Latest', 'Published',
/// 'PreferPublished'. These records are generated when custom entities
/// are published or unpublished.
/// </summary>
public DbSet<CustomEntityPublishStatusQuery> CustomEntityPublishStatusQueries { get; set; }
public DbSet<EntityDefinition> EntityDefinitions { get; set; }
/// <summary>
/// A domain used as part of an email address i.e. the part after
/// the '@'. These are stored as "unique" email domains, whereby
/// multiple domains that resolve to the same mailboxes will only have
/// a single EmailDomain entry in the database.
/// </summary>
public DbSet<EmailDomain> EmailDomains { get; set; }
public DbSet<DocumentAssetGroupItem> DocumentAssetGroupItems { get; set; }
public DbSet<DocumentAssetGroup> DocumentAssetGroups { get; set; }
/// <summary>
/// Represents a non-image file that has been uploaded to the
/// CMS. The name could be misleading here as any file type except
/// images are supported, but at least it is less ambigous than the
/// term 'file'.
/// </summary>
public DbSet<DocumentAsset> DocumentAssets { get; set; }
public DbSet<DocumentAssetTag> DocumentAssetTags { get; set; }
public DbSet<ImageAssetGroupItem> ImageAssetGroupItems { get; set; }
public DbSet<ImageAssetGroup> ImageAssetGroups { get; set; }
/// <summary>
/// Represents an image that has been uploaded to the CMS.
/// </summary>
public DbSet<ImageAsset> ImageAssets { get; set; }
public DbSet<ImageAssetTag> ImageAssetTags { get; set; }
/// <summary>
/// A central logging table of IP addresses which supports optional
/// hashing of the IP addresses for privacy purposes.
/// </summary>
public DbSet<IPAddress> IPAddresses { get; set; }
/// <summary>
/// A Page Template represents a physical view template file and is used
/// by a Page to render out content.
/// </summary>
public DbSet<PageTemplate> PageTemplates { get; set; }
/// <summary>
/// Each PageTemplate can have zero or more regions which are defined in the
/// template file using the CofoundryTemplate helper,
/// e.g. @Cofoundry.Template.Region("MyRegionName"). These regions represent
/// areas where page blocks can be placed (i.e. insert content).
/// </summary>
public DbSet<PageTemplateRegion> PageTemplateRegions { get; set; }
public DbSet<Locale> Locales { get; set; }
/// <summary>
/// Pages represent the dynamically navigable pages of your website. Each page uses a template
/// which defines the regions of content that users can edit. Pages are a versioned entity and
/// therefore have many page version records. At one time a page may only have one draft
/// version, but can have many published versions; the latest published version is the one that
/// is rendered when the page is published.
/// </summary>
public DbSet<Page> Pages { get; set; }
/// <summary>
/// <para>
/// Access rules are used to restrict access to a website resource to users
/// fulfilling certain criteria such as a specific user area or role. Page
/// access rules are used to define the rules at a <see cref="Page"/> level,
/// however rules are also inherited from the directories the page is parented to.
/// </para>
/// <para>
/// Note that access rules do not apply to users from the Cofoundry Admin user
/// area. They aren't intended to be used to restrict editor access in the admin UI
/// but instead are used to restrict public access to website pages and routes.
/// </para>
/// </summary>
public DbSet<PageAccessRule> PageAccessRules { get; set; }
/// <summary>
/// Represents a folder in the dynamic web page heirarchy. There is always a
/// single root directory.
/// </summary>
public DbSet<PageDirectory> PageDirectories { get; set; }
/// <summary>
/// Information about the full directory path and it's position in the directory
/// heirachy. This table is automatically updated whenever changes are made to the page
/// directory heirarchy and should be treated as read-only.
/// </summary>
public DbSet<PageDirectoryPath> PageDirectoryPaths { get; set; }
/// <summary>
/// <para>
/// A "closure table" for the page directory heirarchy structure that connects
/// every page directory with each of it's ancestor directories. The table also
/// includes a self-referencing node (the same ancestor and descendant id).
/// </para>
/// <para>
/// This table is automatically updated whenever changes are made to the page
/// directory heirarchy and should be treated as read-only.
/// </para>
/// </summary>
public DbSet<PageDirectoryClosure> PageDirectoryClosures { get; set; }
/// <summary>
/// <para>
/// Access rules are used to restrict access to a website resource to users
/// fulfilling certain criteria such as a specific user area or role. Page
/// directory access rules are used to define the rules at a <see cref="PageDirectory"/>
/// level. These rules are inherited by child directories and pages.
/// </para>
/// <para>
/// Note that access rules do not apply to users from the Cofoundry Admin user
/// area. They aren't intended to be used to restrict editor access in the admin UI
/// but instead are used to restrict public access to website pages and routes.
/// </para>
/// </summary>
public DbSet<PageDirectoryAccessRule> PageDirectoryAccessRules { get; set; }
public DbSet<PageDirectoryLocale> PageDirectoryLocales { get; set; }
/// <summary>
/// A block can optionally have display templates associated with it,
/// which will give the user a choice about how the data is rendered out
/// e.g. 'Wide', 'Headline', 'Large', 'Reversed'. If no template is set then
/// the default view is used for rendering.
/// </summary>
public DbSet<PageBlockTypeTemplate> PageBlockTypeTemplates { get; set; }
/// <summary>
/// Page block types represent a type of content that can be inserted into a content
/// region of a page which could be simple content like 'RawHtml', 'Image' or
/// 'PlainText'. Custom and more complex block types can be defined by a
/// developer. Block types are typically created when the application
/// starts up in the auto-update process.
/// </summary>
public DbSet<PageBlockType> PageBlockTypes { get; set; }
public DbSet<PageGroupItem> PageGroupItems { get; set; }
public DbSet<PageGroup> PageGroups { get; set; }
public DbSet<PageTag> PageTags { get; set; }
/// <summary>
/// Pages are a versioned entity and therefore have many page version
/// records. At one time a page may only have one draft version, but
/// can have many published versions; the latest published version is
/// the one that is rendered when the page is published.
/// </summary>
public DbSet<PageVersion> PageVersions { get; set; }
public DbSet<PageVersionBlock> PageVersionBlocks { get; set; }
/// <summary>
/// Lookup cache used for quickly finding the correct version for a
/// specific publish status query e.g. 'Latest', 'Published',
/// 'PreferPublished'. These records are generated when pages
/// are published or unpublished.
/// </summary>
public DbSet<PagePublishStatusQuery> PagePublishStatusQueries { get; set; }
/// <summary>
/// A permission represents an type action a user can
/// be permitted to perform. Typically this is associated
/// with a specified entity type, but doesn't have to be e.g.
/// "read pages", "access dashboard", "delete images". The
/// combination of EntityDefinitionCode and PermissionCode
/// must be unique
/// </summary>
public DbSet<Permission> Permissions { get; set; }
public DbSet<RewriteRule> RewriteRules { get; set; }
/// <summary>
/// Roles are an assignable collection of permissions. Every user has to
/// be assigned to one role.
/// </summary>
public DbSet<Role> Roles { get; set; }
public DbSet<RolePermission> RolePermissions { get; set; }
public DbSet<Setting> Settings { get; set; }
public DbSet<Tag> Tags { get; set; }
/// <summary>
/// Represents the user in the Cofoundry custom identity system. Users can be partitioned into
/// different 'User Areas' that enabled the identity system use by the Cofoundry administration area
/// to be reused for other purposes, but this isn't a common scenario and often there will only be the Cofoundry UserArea.
/// </summary>
public DbSet<User> Users { get; set; }
/// <summary>
/// Users can be partitioned into different 'User Areas' that enabled the identity system use by the Cofoundry administration area
/// to be reused for other purposes, but this isn't a common scenario and often there will only be the Cofoundry UserArea. UserAreas
/// are defined in code by defining an IUserAreaDefinition
/// </summary>
public DbSet<UserArea> UserAreas { get; set; }
/// <summary>
/// A logging table that record failed user authentication attempts.
/// </summary>
public DbSet<UserAuthenticationFailLog> UserAuthenticationFailLogs { get; set; }
/// <summary>
/// A logging table that record successful user authentication events.
/// </summary>
public DbSet<UserAuthenticationLog> UserAuthenticationLogs { get; set; }
/// <summary>
/// Contains a record of a relation between one entitiy and another
/// when it's defined in unstructured data. Also contains information on how deletions
/// should cascade for the relationship.
/// </summary>
public DbSet<UnstructuredDataDependency> UnstructuredDataDependencies { get; set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.IO;
//
// infrastructure
//
public class Trace
{
public Trace(string tag, string expected)
{
Console.WriteLine("-----------------------------");
Console.WriteLine(tag);
Console.WriteLine("-----------------------------");
_expected = expected;
}
public void Write(string str)
{
_actual += str;
// Console.Write(str);
}
public void WriteLine(string str)
{
_actual += str;
_actual += Environment.NewLine;
// Console.WriteLine(str);
}
public int Match()
{
// Console.WriteLine("");
Console.Write(_expected);
if (_actual.Equals(_expected))
{
Console.WriteLine(": PASS");
return 100;
}
else
{
Console.WriteLine(": FAIL: _actual='" + _actual + "'");
Console.WriteLine("_expected='" + _expected + "'");
return 999;
}
}
string _actual;
string _expected;
}
//
// main
//
public class TestSet
{
static void CountResults(int testReturnValue, ref int nSuccesses, ref int nFailures)
{
if (100 == testReturnValue)
{
nSuccesses++;
}
else
{
nFailures++;
}
}
public static int Main()
{
int nSuccesses = 0;
int nFailures = 0;
// @TODO: SDM: // CountResults(new StackOverflowInLeafFunction().Run(), ref nSuccesses, ref nFailures);
CountResults(new BaseClassTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new TryCatchInFinallyTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new RecurseTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new ThrowInFinallyNestedInTryTest().Run(), ref nSuccesses, ref nFailures); // FAIL: needs skip to parent code <TODO> investigate </TODO>
CountResults(new GoryManagedPresentTest().Run(), ref nSuccesses, ref nFailures); // FAIL: needs skip to parent code <TODO> investigate </TODO>
CountResults(new InnerFinallyAndCatchTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new InnerFinallyTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new ThrowInFinallyTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new RecursiveRethrow().Run(), ref nSuccesses, ref nFailures);
CountResults(new RecursiveThrowNew().Run(), ref nSuccesses, ref nFailures);
CountResults(new PendingTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new CollidedUnwindTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new BaadbaadTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new GoryNativePastTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new ThrowInCatchTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new StrSwitchFinalTest().Run(), ref nSuccesses, ref nFailures);
CountResults(new RethrowAndFinallysTest().Run(), ref nSuccesses, ref nFailures);
if (0 == nFailures)
{
Console.WriteLine("OVERALL PASS: " + nSuccesses + " tests");
return 100;
}
else
{
Console.WriteLine("OVERALL FAIL: " + nFailures + " tests failed");
return 999;
}
}
}
//
// tests
//
public class RecursiveRethrow
{
Trace _trace;
public int Run()
{
_trace = new Trace("RecursiveRethrow", "210C0C1C2");
try
{
LoveToRecurse(2);
}
catch (Exception e)
{
Console.WriteLine(e);
}
return _trace.Match();
}
void SeparatorMethod(int i)
{
LoveToRecurse(i);
}
void LoveToRecurse(int i)
{
try
{
_trace.Write(i.ToString());
if (0 == i)
{
throw new Exception("RecursionIsFun");
}
else
{
SeparatorMethod(i - 1);
}
}
catch (Exception e)
{
_trace.Write("C" + i.ToString());
Console.WriteLine(e);
throw e;
}
}
}
public class RecursiveThrowNew
{
Trace _trace;
public int Run()
{
_trace = new Trace("RecursiveThrowNew", "210C0(eX)C1(e0)C2(e1)CM(e2)");
try
{
LoveToRecurse(2);
}
catch (Exception e)
{
_trace.Write("CM(" + e.Message + ")");
Console.WriteLine(e);
}
return _trace.Match();
}
void SeparatorMethod(int i)
{
LoveToRecurse(i);
}
void LoveToRecurse(int i)
{
try
{
_trace.Write(i.ToString());
if (0 == i)
{
throw new Exception("eX");
}
else
{
SeparatorMethod(i - 1);
}
}
catch (Exception e)
{
_trace.Write("C" + i.ToString() + "(" + e.Message + ")");
Console.WriteLine(e);
throw new Exception("e" + i.ToString());
}
}
}
public class BaadbaadTest
{
Trace _trace;
public int Run()
{
_trace = new Trace("BaadbaadTest", "1234");
try
{
DoStuff();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("4");
}
return _trace.Match();
}
void DoStuff()
{
try
{
try
{
try
{
throw new Exception();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("1");
throw;
}
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("2");
throw;
}
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("3");
throw;
}
}
}
class BaseClassTest
{
Trace _trace;
void f2()
{
throw new FileNotFoundException("1");
}
void f1()
{
try
{
f2();
}
catch(FileNotFoundException e)
{
Console.WriteLine(e);
_trace.Write("0" + e.Message);
throw e;
}
catch(IOException e)
{
Console.WriteLine(e);
_trace.Write("!" + e.Message);
throw e;
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("@" + e.Message);
throw e;
}
}
public int Run()
{
_trace = new Trace("BaseClassTest", "0121");
try
{
f1();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("2" + e.Message);
}
return _trace.Match();
}
}
public class CollidedUnwindTest
{
class ExType1 : Exception
{
}
class ExType2 : Exception
{
}
Trace _trace;
public int Run()
{
_trace = new Trace("CollidedUnwindTest", "0123456789ABCDE");
try
{
_trace.Write("0");
Foo();
}
catch (ExType2 e)
{
Console.WriteLine(e);
_trace.Write("E");
}
return _trace.Match();
}
void Foo()
{
try
{
_trace.Write("1");
FnAAA();
}
catch (ExType1 e)
{
Console.WriteLine(e);
_trace.Write(" BAD ");
}
}
void FnAAA()
{
try
{
_trace.Write("2");
FnBBB();
}
finally
{
_trace.Write("D");
}
}
void FnBBB()
{
try
{
_trace.Write("3");
Bar();
}
finally
{
_trace.Write("C");
}
}
void Bar()
{
try
{
_trace.Write("4");
FnCCC();
}
finally
{
_trace.Write("B");
throw new ExType2();
}
}
void FnCCC()
{
try
{
_trace.Write("5");
FnDDD();
}
finally
{
_trace.Write("A");
}
}
void FnDDD()
{
try
{
_trace.Write("6");
Fubar();
}
finally
{
_trace.Write("9");
}
}
void Fubar()
{
try
{
_trace.Write("7");
throw new ExType1();
}
finally
{
_trace.Write("8");
}
}
}
public class ThrowInFinallyNestedInTryTest
{
Trace _trace;
void MiddleMethod()
{
_trace.Write("2");
try
{
_trace.Write("3");
try
{
_trace.Write("4");
}
finally
{
_trace.Write("5");
try
{
_trace.Write("6");
throw new System.ArgumentException();
}
finally
{
_trace.Write("7");
}
}
}
finally
{
_trace.Write("8");
}
}
public int Run()
{
_trace = new Trace("ThrowInFinallyNestedInTryTest", "0123456789a");
_trace.Write("0");
try
{
_trace.Write("1");
MiddleMethod();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("9");
}
_trace.Write("a");
return _trace.Match();
}
}
class ThrowInFinallyTest
{
Trace _trace;
void Dumb()
{
_trace.Write("2");
try
{
_trace.Write("3");
try
{
_trace.Write("4");
try
{
_trace.Write("5");
throw new Exception("A");
}
finally
{
_trace.Write("6");
throw new Exception("B");
}
}
finally
{
_trace.Write("7");
throw new Exception("C");
}
}
finally
{
_trace.Write("8");
}
}
public int Run()
{
_trace = new Trace("ThrowInFinallyTest", "0123456789Ca");
_trace.Write("0");
try
{
_trace.Write("1");
Dumb();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("9");
_trace.Write(e.Message);
}
_trace.Write("a");
return _trace.Match();
}
}
class ThrowInCatchTest
{
Trace _trace;
public int Run()
{
_trace = new Trace("ThrowInCatchTest", "0123456");
_trace.Write("0");
try
{
_trace.Write("1");
try
{
_trace.Write("2");
throw new Exception(".....");
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("3");
throw new Exception("5");
}
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("4");
_trace.Write(e.Message);
}
_trace.Write("6");
return _trace.Match();
}
}
class RecurseTest
{
Trace _trace;
void DoTest(int level)
{
_trace.Write(level.ToString());
if (level <= 0)
return;
try
{
throw new Exception("" + (level - 1));
}
catch (Exception e)
{
Console.WriteLine(e);
_trace.Write(e.Message);
DoTest(level - 2);
}
}
public int Run()
{
int n = 8;
string expected = "";
// create expected result string
for (int i = n; i >= 0; i--)
{
expected += i.ToString();
}
_trace = new Trace("RecurseTest", expected);
DoTest(n);
return _trace.Match();
}
}
class PendingTest
{
Trace _trace;
void f3()
{
throw new Exception();
}
void f2()
{
try
{
_trace.Write("1");
f3();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("2");
throw;
}
}
void f1()
{
try
{
_trace.Write("0");
f2();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("3");
throw e;
}
}
public int Run()
{
_trace = new Trace("PendingTest", "0123401235");
try
{
f1();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("4");
}
try
{
f1();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("5");
}
return _trace.Match();
}
}
class GoryNativePastTest
{
Trace _trace;
void bar()
{
_trace.Write("2");
throw new Exception("6");
}
void foo()
{
_trace.Write("1");
try
{
bar();
}
finally
{
_trace.Write("3");
}
}
public int Run()
{
_trace = new Trace("GoryNativePastTest", "0123456");
_trace.Write("0");
try
{
try
{
foo();
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("4");
throw;
}
}
catch(Exception e)
{
_trace.Write("5");
_trace.Write(e.Message);
}
return _trace.Match();
}
}
class GoryManagedPresentTest
{
Trace _trace;
void foo(int dummy)
{
_trace.Write("1");
try
{
_trace.Write("2");
try
{
_trace.Write("3");
if (1234 == dummy)
{
goto MyLabel;
}
_trace.Write("....");
}
finally
{
_trace.Write("4");
}
}
finally
{
_trace.Write("5");
if (1234 == dummy)
{
int i = 0;
int q = 167 / i;
}
}
_trace.Write("****");
MyLabel:
_trace.Write("~~~~");
}
public int Run()
{
_trace = new Trace("GoryManagedPresentTest", "0123456");
try
{
_trace.Write("0");
foo(1234);
_trace.Write("%%%%");
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("6");
}
return _trace.Match();
}
}
class TryCatchInFinallyTest
{
Trace _trace;
public int Run()
{
_trace = new Trace("TryCatchInFinallyTest", "0123456");
_trace.Write("0");
try
{
_trace.Write("1");
}
finally
{
_trace.Write("2");
try
{
_trace.Write("3");
throw new InvalidProgramException();
}
catch(InvalidProgramException e)
{
Console.WriteLine(e);
_trace.Write("4");
}
_trace.Write("5");
}
_trace.Write("6");
return _trace.Match();
}
}
class StrSwitchFinalTest
{
Trace _trace;
static string _expected;
static StrSwitchFinalTest()
{
// Create test writer object to hold expected output
System.IO.StringWriter expectedOut = new System.IO.StringWriter();
// Write expected output to string writer object
expectedOut.WriteLine("s == one");
expectedOut.WriteLine("In inner finally");
expectedOut.WriteLine("In outer finally\r\n");
expectedOut.WriteLine("s == two");
expectedOut.WriteLine("After two");
expectedOut.WriteLine("In inner finally");
expectedOut.WriteLine("In outer finally\r\n");
expectedOut.WriteLine("s == three");
expectedOut.WriteLine("After three");
expectedOut.WriteLine("Ok");
expectedOut.WriteLine("After after three");
expectedOut.WriteLine("In inner finally");
expectedOut.WriteLine("Caught an exception\r\n");
expectedOut.WriteLine("Ok\r\n");
expectedOut.WriteLine("In outer finally\r\n");
expectedOut.WriteLine("In four's finally");
expectedOut.WriteLine("In inner finally");
expectedOut.WriteLine("Caught an exception\r\n");
expectedOut.WriteLine("Ok\r\n");
expectedOut.WriteLine("In outer finally\r\n");
expectedOut.WriteLine("s == five");
expectedOut.WriteLine("Five's finally 0");
expectedOut.WriteLine("Five's finally 1");
expectedOut.WriteLine("Five's finally 2");
expectedOut.WriteLine("In inner finally");
expectedOut.WriteLine("In outer finally\r\n");
expectedOut.WriteLine("Greater than five");
expectedOut.WriteLine("in six's finally");
expectedOut.WriteLine("In inner finally");
expectedOut.WriteLine("In outer finally\r\n");
_expected = expectedOut.ToString();
}
public int Run()
{
_trace = new Trace("StrSwitchFinalTest", _expected);
string[] s = {"one", "two", "three", "four", "five", "six"};
for(int i = 0; i < s.Length; i++)
{
beginloop:
try
{
try
{
try
{
switch(s[i])
{
case "one":
try
{
_trace.WriteLine("s == one");
}
catch
{
_trace.WriteLine("Exception at one");
}
break;
case "two":
try
{
_trace.WriteLine("s == two");
}
finally
{
_trace.WriteLine("After two");
}
break;
case "three":
try
{
try
{
_trace.WriteLine("s == three");
}
catch(System.Exception e)
{
_trace.WriteLine(e.ToString());
goto continueloop;
}
}
finally
{
_trace.WriteLine("After three");
try
{
switch(s[s.Length-1])
{
case "six":
_trace.WriteLine("Ok");
_trace.WriteLine(s[s.Length]);
goto label2;
default:
try
{
_trace.WriteLine("Ack");
goto label;
}
catch
{
_trace.WriteLine("I don't think so ...");
}
break;
}
label:
_trace.WriteLine("Unreached");
throw new Exception();
}
finally
{
_trace.WriteLine("After after three");
}
label2:
_trace.WriteLine("Unreached");
}
goto continueloop;
case "four":
try
{
try
{
_trace.WriteLine("s == " + s[s.Length]);
try
{
}
finally
{
_trace.WriteLine("Unreached");
}
}
catch (Exception e)
{
goto test;
rethrowex:
throw;
test:
if (e is System.ArithmeticException)
{
try
{
_trace.WriteLine("unreached ");
goto finishfour;
}
finally
{
_trace.WriteLine("also unreached");
}
}
else
{
goto rethrowex;
}
}
}
finally
{
_trace.WriteLine("In four's finally");
}
finishfour:
break;
case "five":
try
{
try
{
try
{
_trace.WriteLine("s == five");
}
finally
{
_trace.WriteLine("Five's finally 0");
}
}
catch (Exception)
{
_trace.WriteLine("Unreached");
}
finally
{
_trace.WriteLine("Five's finally 1");
}
break;
}
finally
{
_trace.WriteLine("Five's finally 2");
}
default:
try
{
_trace.WriteLine("Greater than five");
goto finish;
}
finally
{
_trace.WriteLine("in six's finally");
}
};
continue;
}
finally
{
_trace.WriteLine("In inner finally");
}
}
catch (Exception e)
{
_trace.WriteLine("Caught an exception\r\n");
switch(s[i])
{
case "three":
if (e is System.IndexOutOfRangeException)
{
_trace.WriteLine("Ok\r\n");
i++;
goto beginloop;
}
_trace.WriteLine("Unreached\r\n");
break;
case "four":
if (e is System.IndexOutOfRangeException)
{
_trace.WriteLine("Ok\r\n");
i++;
goto beginloop;
}
_trace.WriteLine("Unreached\r\n");
break;
default:
_trace.WriteLine("****** Unreached");
goto continueloop;
}
}
_trace.WriteLine("Unreached");
}
finally
{
_trace.WriteLine("In outer finally\r\n");
}
continueloop:
_trace.WriteLine("Continuing");
}
finish:
return _trace.Match();;
}
}
public class RethrowAndFinallysTest
{
Trace _trace;
public int Run()
{
_trace = new Trace("RethrowAndFinallysTest", "abcdefF3ED2CB1A[done]");
try
{
_trace.Write("a");
try
{
_trace.Write("b");
try
{
_trace.Write("c");
try
{
_trace.Write("d");
try
{
_trace.Write("e");
try
{
_trace.Write("f");
throw new Exception("ex1");
}
finally
{
_trace.Write("F");
}
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("3");
throw;
}
finally
{
_trace.Write("E");
}
}
finally
{
_trace.Write("D");
}
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("2");
throw;
}
finally
{
_trace.Write("C");
}
}
finally
{
_trace.Write("B");
}
}
catch(Exception e)
{
Console.WriteLine(e);
_trace.Write("1");
}
finally
{
_trace.Write("A");
}
_trace.Write("[done]");
return _trace.Match();
}
}
class InnerFinallyTest
{
Trace _trace;
public InnerFinallyTest()
{
// Create test writer object to hold expected output
System.IO.StringWriter expectedOut = new System.IO.StringWriter();
// Write expected output to string writer object
expectedOut.WriteLine(" try 1");
expectedOut.WriteLine("\t try 1.1");
expectedOut.WriteLine("\t finally 1.1");
expectedOut.WriteLine("\t\t try 1.1.1");
expectedOut.WriteLine("\t\t Throwing an exception here!");
expectedOut.WriteLine("\t\t finally 1.1.1");
expectedOut.WriteLine(" catch 1");
expectedOut.WriteLine(" finally 1");
_trace = new Trace("InnerFinallyTest", expectedOut.ToString());
}
public int Run()
{
int x = 7, y = 0, z;
try
{
_trace.WriteLine(" try 1");
try
{
_trace.WriteLine("\t try 1.1");
}
finally
{
_trace.WriteLine("\t finally 1.1");
try
{
_trace.WriteLine("\t\t try 1.1.1");
_trace.WriteLine("\t\t Throwing an exception here!");
z = x / y;
}
finally
{
_trace.WriteLine("\t\t finally 1.1.1");
}
}
}
catch (Exception)
{
_trace.WriteLine(" catch 1");
}
finally
{
_trace.WriteLine(" finally 1");
}
return _trace.Match();
}
}
class InnerFinallyAndCatchTest
{
Trace _trace;
public int Run()
{
_trace = new Trace("InnerFinallyAndCatchTest", "abcdefghijklm13");
int x = 7, y = 0, z;
int count = 0;
try
{
_trace.Write("a");
count++;
try
{
_trace.Write("b");
count++;
}
finally // 1
{
try
{
_trace.Write("c");
count++;
}
finally // 2
{
try
{
try
{
_trace.Write("d");
count++;
}
finally // 3
{
_trace.Write("e");
count++;
try
{
_trace.Write("f");
count++;
}
finally // 4
{
_trace.Write("g");
count++;
z = x / y;
}
_trace.Write("@@");
count++;
}
}
catch (Exception) // C2
{
_trace.Write("h");
count++;
}
_trace.Write("i");
count++;
}
_trace.Write("j");
count++;
}
_trace.Write("k");
count++;
}
catch (Exception) // C1
{
_trace.Write("!!");
count++;
}
finally // 0
{
_trace.Write("l");
count++;
}
_trace.Write("m");
count++;
_trace.Write(count.ToString());
return _trace.Match();
}
}
class StackOverflowInLeafFunction
{
Trace _trace;
/*
int LeafFunction(int a, int b)
{
int c;
try
{
// raise stack overflow
}
catch
{
c = b / a; // this exception will not be able to dispatch
}
return c;
}
*/
unsafe void RecursiveDeath(int depth)
{
string msg = String.Concat("caught at depth:", depth.ToString());
long* pStuff = stackalloc long[128];
for (int i = 0; i < 128; i++)
{
short d = (short)depth;
long dd = (long)d;
long foo = dd << 48;
foo |= dd << 32;
foo |= dd << 16;
foo |= dd;
pStuff[i] = foo;
}
try
{
RecursiveDeath(depth + 1);
}
catch
{
Console.WriteLine(msg);
}
}
public int Run()
{
_trace = new Trace("", "123");
_trace.Write("1");
try
{
RecursiveDeath(0);
}
catch
{
_trace.Write("2");
}
_trace.Write("3");
return _trace.Match();
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Xml.XPath;
using System.Data;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
namespace fyiReporting.Data
{
/// <summary>
/// Summary description for iTunesDataReader.
/// </summary>
public class iTunesDataReader : IDataReader
{
iTunesConnection _xconn;
iTunesCommand _xcmd;
System.Data.CommandBehavior _behavior;
// xpath
XPathDocument _xpd; // the document
XPathNavigator _xpn; // the navigator
XPathNodeIterator _xpni; // the main iterator
XmlNamespaceManager _nsmgr; // name space manager
ListDictionary _NameSpaces; // names spaces used in xml document
// column information
object[] _Data; // data values of the columns
static readonly string[] _Names = new string[] {
"Track_ID",
"Name",
"Artist",
"Composer",
"Album",
"Album Artist",
"Genre",
"Category",
"Kind",
"Size",
"Total_Time",
"Track_Number",
"Year",
"Date_Modified",
"Date_Added",
"Beats_Per_Minute",
"Bit_Rate",
"Sample_Rate",
"Comments",
"Skip_Count",
"Skip_Date",
"Artwork_Count",
"Persistent_ID",
"Track_Type",
"Location",
"File_Folder_Count",
"Library_Folder_Count",
"Has_Video",
"Movie",
"Play_Count",
"Play_Date",
"Play_Date_UTC",
"Disc_Number",
"Disc_Count",
"Compilation",
"Track_Count"
};
// types of all the columns
static readonly Type _dttype = DateTime.MinValue.GetType(); // work variable for getting the type
static readonly Type _stype = "".GetType();
static readonly Type _btype = true.GetType();
static readonly Type _itype = int.MaxValue.GetType();
static readonly Type _ltype = long.MaxValue.GetType();
static readonly Type _dtype = Double.MinValue.GetType();
static readonly Type[] _Types = new Type[]
{
/* "Track_ID" */ _itype,
/* Name */ _stype,
/* Artist */ _stype,
/* Composer */ _stype,
/* Album */ _stype,
/* Album Artist */ _stype,
/* Genre */ _stype,
/* Category */ _stype,
/* Kind */ _stype,
/* Size */ _itype,
/* Total_Time */ _itype,
/* Track_Number */ _itype,
/* Year */ _itype,
/* Date_Modified */ _dttype,
/* Date_Added */ _dttype,
/* Beats_Per_Minute */ _itype,
/* Bit_Rate */ _itype,
/* Sample_Rate */ _itype,
/* Comments */ _stype,
/* Skip_Count */ _itype,
/* Skip_Date */ _dttype,
/* Artwork_Count */ _itype,
/* Persistent_ID */ _stype,
/* Track_Type */ _stype,
/* Location */ _stype,
/* File_Folder_Count */ _itype,
/* Library_Folder_Count */ _itype,
/* Has_Video */ _btype,
/* Movie */ _btype,
/* Play_Count */ _itype,
/* Play_Date */ _ltype, /* Play_Date will overflow an integer */
/* Play_Date_UTC */ _dttype,
/* Disc_Number */ _itype,
/* Disc_Count */ _itype,
/* Compilation */ _btype,
/* Track_Count */ _itype
};
public iTunesDataReader(System.Data.CommandBehavior behavior, iTunesConnection conn, iTunesCommand cmd)
{
_xconn = conn;
_xcmd = cmd;
_behavior = behavior;
_Data = new object[_Names.Length]; // allocate enough room for data
if (behavior == CommandBehavior.SchemaOnly)
return;
// create an iterator to the selected rows
_xpd = new XPathDocument(_xconn.File);
_xpn = _xpd.CreateNavigator();
_xpni = _xpn.Select("/plist/dict"); // select the rows
_NameSpaces = new ListDictionary();
// Now determine the actual structure of the row depending on the command
switch (_xcmd.Table)
{
case "Tracks":
default:
_xpni = GetTracksColumns();
break;
}
if (_NameSpaces.Count > 0)
{
_nsmgr = new XmlNamespaceManager(new NameTable());
foreach (string nsprefix in _NameSpaces.Keys)
{
_nsmgr.AddNamespace(nsprefix, _NameSpaces[nsprefix] as string); // setup namespaces
}
}
else
_nsmgr = null;
}
XPathNodeIterator GetTracksColumns()
{
/* this routine figures out based on first row in file; the problem is not
* all rows contain all the fields. Now fields are hard coded.
XPathNodeIterator ti = PositionToTracks();
while (ti.MoveNext())
{
if (ti.Current.Name != "key")
continue;
if (AddName(ti.Current.Value)) // when duplicate we've gone too far
break;
ti.MoveNext();
Type t;
switch (ti.Current.Name)
{
case "integer":
t = long.MaxValue.GetType();
break;
case "string":
t = string.Empty.GetType();
break;
case "real":
t = Double.MaxValue.GetType();
break;
case "true":
case "false":
t = true.GetType();
break;
case "date":
t = DateTime.MaxValue.GetType();
break;
default:
t = string.Empty.GetType();
break;
}
_Types.Add(t);
}
_Names.TrimExcess(); // no longer need extra space
*/
return PositionToTracks(); // return iterator to first row
}
XPathNodeIterator PositionToTracks()
{
//go to the first row to get info
XPathNodeIterator temp_xpni = _xpni.Clone(); // temporary iterator for determining columns
temp_xpni.MoveNext();
XPathNodeIterator ni = temp_xpni.Current.Select("*");
while (ni.MoveNext())
{
if (ni.Current.Name != "key")
continue;
if (ni.Current.Value == "Tracks")
{
ni.MoveNext();
if (ni.Current.Name != "dict") // next item should be "dict"
break;
string sel = "dict/*";
XPathNodeIterator ti = ni.Current.Select(sel);
return ti;
}
}
return null;
}
// adds name to array; return true when duplicate
//bool AddName(string name)
//{
// string wname = name.Replace(' ', '_');
// if (_Names.ContainsKey(wname))
// return true;
// _Names.Add(wname, _Names.Count);
// return false;
//}
#region IDataReader Members
public int RecordsAffected
{
get
{
return 0;
}
}
public bool IsClosed
{
get
{
return _xconn.IsOpen;
}
}
public bool NextResult()
{
return false;
}
public void Close()
{
_xpd = null;
_xpn = null;
_xpni = null;
_Data = null;
}
public bool Read()
{
if (_xpni == null)
return false;
XPathNodeIterator ti = _xpni;
Hashtable ht = new Hashtable(_Names.Length);
// clear out previous values; previous row might have values this row doesn't
for (int i = 0; i < _Data.Length; i++)
_Data[i] = null;
XPathNodeIterator save_ti = ti.Clone();
bool rc = false;
while (ti.MoveNext())
{
if (ti.Current.Name != "key")
continue;
string name = ti.Current.Value.Replace(' ', '_');
// we only know we're on the next row when a column repeats
if (ht.Contains(name))
{
break;
}
ht.Add(name, name);
int ix;
try
{
ix = this.GetOrdinal(name);
rc = true; // we know we got at least one column value
}
catch // this isn't a know column; skip it
{
ti.MoveNext();
save_ti = ti.Clone();
continue; // but keep trying
}
ti.MoveNext();
save_ti = ti.Clone();
try
{
switch (ti.Current.Name)
{
case "integer":
if (_Names[ix] == "Play_Date") // will overflow a long
_Data[ix] = ti.Current.ValueAsLong;
else
_Data[ix] = ti.Current.ValueAsInt;
break;
case "string":
_Data[ix] = ti.Current.Value;
break;
case "real":
_Data[ix] = ti.Current.ValueAsDouble;
break;
case "true":
_Data[ix] = true;
break;
case "false":
_Data[ix] = false;
break;
case "date":
_Data[ix] = ti.Current.ValueAsDateTime;
break;
default:
_Data[ix] = ti.Current.Value;
break;
}
}
catch { _Data[ix] = null; }
}
_xpni = save_ti;
return rc;
}
public int Depth
{
get
{
// TODO: Add XmlDataReader.Depth getter implementation
return 0;
}
}
public DataTable GetSchemaTable()
{
// TODO: Add XmlDataReader.GetSchemaTable implementation
return null;
}
#endregion
#region IDisposable Members
public void Dispose()
{
this.Close();
}
#endregion
#region IDataRecord Members
public int GetInt32(int i)
{
return Convert.ToInt32(_Data[i]);
}
public object this[string name]
{
get
{
int ci = this.GetOrdinal(name);
return _Data[ci];
}
}
object System.Data.IDataRecord.this[int i]
{
get
{
return _Data[i];
}
}
public object GetValue(int i)
{
return _Data[i];
}
public bool IsDBNull(int i)
{
return _Data[i] == null;
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException("GetBytes not implemented.");
}
public byte GetByte(int i)
{
return Convert.ToByte(_Data[i]);
}
public Type GetFieldType(int i)
{
return _Types[i];
}
public decimal GetDecimal(int i)
{
return Convert.ToDecimal(_Data[i]);
}
public int GetValues(object[] values)
{
int i;
for (i=0; i < values.Length; i++)
{
values[i] = i >= _Data.Length? System.DBNull.Value: _Data[i];
}
return Math.Min(values.Length, _Data.Length);
}
public string GetName(int i)
{
return _Names[i];
}
public int FieldCount
{
get
{
return _Data.Length;
}
}
public long GetInt64(int i)
{
return Convert.ToInt64(_Data[i]);
}
public double GetDouble(int i)
{
return Convert.ToDouble(_Data[i]);
}
public bool GetBoolean(int i)
{
return Convert.ToBoolean(_Data[i]);
}
public Guid GetGuid(int i)
{
throw new NotImplementedException("GetGuid not implemented.");
}
public DateTime GetDateTime(int i)
{
return Convert.ToDateTime(_Data[i]);
}
public int GetOrdinal(string name)
{
// do case sensitive lookup
int ci = 0;
foreach (string cname in _Names)
{
if (cname == name)
return ci;
ci++;
}
// do case insensitive lookup
ci=0;
foreach (string cname in _Names)
{
if (string.Compare(cname, name, true) == 0)
return ci;
ci++;
}
throw new ArgumentException(string.Format("Column '{0}' not known.", name));
}
public string GetDataTypeName(int i)
{
Type t = _Types[i] as Type;
return t.ToString();
}
public float GetFloat(int i)
{
return Convert.ToSingle(_Data[i]);
}
public IDataReader GetData(int i)
{
throw new NotImplementedException("GetData not implemented.");
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException("GetChars not implemented.");
}
public string GetString(int i)
{
return Convert.ToString(_Data[i]);
}
public char GetChar(int i)
{
return Convert.ToChar(_Data[i]);
}
public short GetInt16(int i)
{
return Convert.ToInt16(_Data[i]);
}
#endregion
}
}
| |
// ****************************************************************
// This is free software licensed under the NUnit license. You
// may obtain a copy of the license as well as information regarding
// copyright ownership at http://nunit.org.
// ****************************************************************
namespace NUnit.Core
{
using System;
using System.Text;
using System.Threading;
using System.Collections;
using System.Reflection;
using NUnit.Core.Filters;
#if CLR_2_0 || CLR_4_0
using System.Collections.Generic;
#endif
/// <summary>
/// Summary description for TestSuite.
/// </summary>
///
[Serializable]
public class TestSuite : Test
{
#region Fields
static Logger log = InternalTrace.GetLogger(typeof(TestSuite));
/// <summary>
/// Our collection of child tests
/// </summary>
private ArrayList tests = new ArrayList();
/// <summary>
/// The fixture setup methods for this suite
/// </summary>
protected MethodInfo[] fixtureSetUpMethods;
/// <summary>
/// The fixture teardown methods for this suite
/// </summary>
protected MethodInfo[] fixtureTearDownMethods;
/// <summary>
/// The setup methods for this suite
/// </summary>
protected MethodInfo[] setUpMethods;
/// <summary>
/// The teardown methods for this suite
/// </summary>
protected MethodInfo[] tearDownMethods;
#if CLR_2_0 || CLR_4_0
/// <summary>
/// The actions for this suite
/// </summary>
protected TestAction[] actions;
#endif
/// <summary>
/// Set to true to suppress sorting this suite's contents
/// </summary>
protected bool maintainTestOrder;
/// <summary>
/// Arguments for use in creating a parameterized fixture
/// </summary>
internal object[] arguments;
/// <summary>
/// The System.Type of the fixture for this test suite, if there is one
/// </summary>
private Type fixtureType;
/// <summary>
/// The fixture object, if it has been created
/// </summary>
private object fixture;
#endregion
#region Constructors
public TestSuite( string name )
: base( name ) { }
public TestSuite( string parentSuiteName, string name )
: base( parentSuiteName, name ) { }
public TestSuite(Type fixtureType)
: this(fixtureType, null) { }
public TestSuite(Type fixtureType, object[] arguments)
: base(fixtureType.FullName)
{
string name = TypeHelper.GetDisplayName(fixtureType, arguments);
this.TestName.Name = name;
this.TestName.FullName = name;
string nspace = fixtureType.Namespace;
if (nspace != null && nspace != "")
this.TestName.FullName = nspace + "." + name;
this.fixtureType = fixtureType;
this.arguments = arguments;
}
#endregion
#region Public Methods
public void Sort()
{
if (!maintainTestOrder)
{
this.tests.Sort();
foreach (Test test in Tests)
{
TestSuite suite = test as TestSuite;
if (suite != null)
suite.Sort();
}
}
}
public void Sort(IComparer comparer)
{
this.tests.Sort(comparer);
foreach( Test test in Tests )
{
TestSuite suite = test as TestSuite;
if ( suite != null )
suite.Sort(comparer);
}
}
public void Add( Test test )
{
// if( test.RunState == RunState.Runnable )
// {
// test.RunState = this.RunState;
// test.IgnoreReason = this.IgnoreReason;
// }
test.Parent = this;
tests.Add(test);
}
public void Add( object fixture )
{
Test test = TestFixtureBuilder.BuildFrom( fixture );
if ( test != null )
Add( test );
}
#endregion
#region Properties
public override IList Tests
{
get { return tests; }
}
public override bool IsSuite
{
get { return true; }
}
public override int TestCount
{
get
{
int count = 0;
foreach(Test test in Tests)
{
count += test.TestCount;
}
return count;
}
}
public override Type FixtureType
{
get { return fixtureType; }
}
public override object Fixture
{
get { return fixture; }
set { fixture = value; }
}
public MethodInfo[] GetSetUpMethods()
{
return setUpMethods;
}
public MethodInfo[] GetTearDownMethods()
{
return tearDownMethods;
}
#if CLR_2_0 || CLR_4_0
internal virtual TestAction[] GetTestActions()
{
List<TestAction> allActions = new List<TestAction>();
if (this.Parent != null && this.Parent is TestSuite)
{
TestAction[] parentActions = ((TestSuite)this.Parent).GetTestActions();
if (parentActions != null)
allActions.AddRange(parentActions);
}
if (this.actions != null)
allActions.AddRange(this.actions);
return allActions.ToArray();
}
#endif
#endregion
#region Test Overrides
public override string TestType
{
get { return "TestSuite"; }
}
public override int CountTestCases(ITestFilter filter)
{
int count = 0;
if(filter.Pass(this))
{
foreach(Test test in Tests)
{
count += test.CountTestCases(filter);
}
}
return count;
}
public override TestResult Run(EventListener listener, ITestFilter filter)
{
listener.SuiteStarted(this.TestName);
long startTime = DateTime.Now.Ticks;
TestResult suiteResult = this.RunState == RunState.Runnable || this.RunState == RunState.Explicit
? RunSuiteInContext(listener, filter)
: SkipSuite(listener, filter);
long stopTime = DateTime.Now.Ticks;
double time = ((double)(stopTime - startTime)) / (double)TimeSpan.TicksPerSecond;
suiteResult.Time = time;
listener.SuiteFinished(suiteResult);
return suiteResult;
}
private TestResult SkipSuite(EventListener listener, ITestFilter filter)
{
TestResult suiteResult = new TestResult(this);
switch (this.RunState)
{
default:
case RunState.Skipped:
SkipAllTests(suiteResult, listener, filter);
break;
case RunState.NotRunnable:
MarkAllTestsInvalid(suiteResult, listener, filter);
break;
case RunState.Ignored:
IgnoreAllTests(suiteResult, listener, filter);
break;
}
return suiteResult;
}
private TestResult RunSuiteInContext(EventListener listener, ITestFilter filter)
{
TestExecutionContext.Save();
try
{
return ShouldRunOnOwnThread
? new TestSuiteThread(this).Run(listener, filter)
: RunSuite(listener, filter);
}
finally
{
TestExecutionContext.Restore();
}
}
public TestResult RunSuite(EventListener listener, ITestFilter filter)
{
TestResult suiteResult = new TestResult(this);
DoOneTimeSetUp(suiteResult);
#if CLR_2_0 || CLR_4_0
DoOneTimeBeforeTestSuiteActions(suiteResult);
#endif
if (this.Properties["_SETCULTURE"] != null)
TestExecutionContext.CurrentContext.CurrentCulture =
new System.Globalization.CultureInfo((string)Properties["_SETCULTURE"]);
if (this.Properties["_SETUICULTURE"] != null)
TestExecutionContext.CurrentContext.CurrentUICulture =
new System.Globalization.CultureInfo((string)Properties["_SETUICULTURE"]);
switch (suiteResult.ResultState)
{
case ResultState.Failure:
case ResultState.Error:
MarkTestsFailed(Tests, suiteResult, listener, filter);
break;
case ResultState.NotRunnable:
MarkTestsNotRun(this.Tests, ResultState.NotRunnable, suiteResult.Message, suiteResult, listener, filter);
break;
default:
try
{
RunAllTests(suiteResult, listener, filter);
}
finally
{
#if CLR_2_0 || CLR_4_0
DoOneTimeAfterTestSuiteActions(suiteResult);
#endif
DoOneTimeTearDown(suiteResult);
}
break;
}
return suiteResult;
}
#endregion
#region Virtual Methods
protected virtual void DoOneTimeSetUp(TestResult suiteResult)
{
if (FixtureType != null)
{
try
{
// In case TestFixture was created with fixture object
if (Fixture == null && !IsStaticClass( FixtureType ) )
CreateUserFixture();
if (this.fixtureSetUpMethods != null)
foreach( MethodInfo fixtureSetUp in fixtureSetUpMethods )
Reflect.InvokeMethod(fixtureSetUp, fixtureSetUp.IsStatic ? null : Fixture);
TestExecutionContext.CurrentContext.Update();
}
catch (Exception ex)
{
if (ex is NUnitException || ex is System.Reflection.TargetInvocationException)
ex = ex.InnerException;
if (ex is InvalidTestFixtureException)
suiteResult.Invalid(ex.Message);
else if (IsIgnoreException(ex))
{
this.RunState = RunState.Ignored;
suiteResult.Ignore(ex.Message);
suiteResult.StackTrace = ex.StackTrace;
this.IgnoreReason = ex.Message;
}
else if (IsAssertException(ex))
suiteResult.Failure(ex.Message, ex.StackTrace, FailureSite.SetUp);
else
suiteResult.Error(ex, FailureSite.SetUp);
}
}
}
#if CLR_2_0 || CLR_4_0
protected virtual void ExecuteActions(ActionPhase phase)
{
List<TestAction> targetActions = new List<TestAction>();
if (this.actions != null)
{
foreach (var action in this.actions)
{
if (action.DoesTarget(TestAction.TargetsSuite) || action.DoesTarget(TestAction.TargetsDefault))
targetActions.Add(action);
}
}
ActionsHelper.ExecuteActions(phase, targetActions, this);
}
protected virtual void DoOneTimeBeforeTestSuiteActions(TestResult suiteResult)
{
try
{
ExecuteActions(ActionPhase.Before);
TestExecutionContext.CurrentContext.Update();
}
catch (Exception ex)
{
if (ex is NUnitException || ex is System.Reflection.TargetInvocationException)
ex = ex.InnerException;
if (ex is InvalidTestFixtureException)
suiteResult.Invalid(ex.Message);
else if (IsIgnoreException(ex))
{
this.RunState = RunState.Ignored;
suiteResult.Ignore(ex.Message);
suiteResult.StackTrace = ex.StackTrace;
this.IgnoreReason = ex.Message;
}
else if (IsAssertException(ex))
suiteResult.Failure(ex.Message, ex.StackTrace, FailureSite.SetUp);
else
suiteResult.Error(ex, FailureSite.SetUp);
}
}
#endif
protected virtual void CreateUserFixture()
{
if (arguments != null && arguments.Length > 0)
Fixture = Reflect.Construct(FixtureType, arguments);
else
Fixture = Reflect.Construct(FixtureType);
}
protected virtual void DoOneTimeTearDown(TestResult suiteResult)
{
if ( this.FixtureType != null)
{
try
{
if (this.fixtureTearDownMethods != null)
{
int index = fixtureTearDownMethods.Length;
while (--index >= 0 )
{
MethodInfo fixtureTearDown = fixtureTearDownMethods[index];
Reflect.InvokeMethod(fixtureTearDown, fixtureTearDown.IsStatic ? null : Fixture);
}
}
IDisposable disposable = Fixture as IDisposable;
if (disposable != null)
disposable.Dispose();
}
catch (Exception ex)
{
// Error in TestFixtureTearDown or Dispose causes the
// suite to be marked as a failure, even if
// all the contained tests passed.
NUnitException nex = ex as NUnitException;
if (nex != null)
ex = nex.InnerException;
suiteResult.Failure(ex.Message, ex.StackTrace, FailureSite.TearDown);
}
this.Fixture = null;
}
}
#if CLR_2_0 || CLR_4_0
protected virtual void DoOneTimeAfterTestSuiteActions(TestResult suiteResult)
{
try
{
ExecuteActions(ActionPhase.After);
}
catch (Exception ex)
{
// Error in TestFixtureTearDown or Dispose causes the
// suite to be marked as a failure, even if
// all the contained tests passed.
NUnitException nex = ex as NUnitException;
if (nex != null)
ex = nex.InnerException;
suiteResult.Failure(ex.Message, ex.StackTrace, FailureSite.TearDown);
}
}
#endif
protected virtual bool IsAssertException(Exception ex)
{
return ex.GetType().FullName == NUnitFramework.AssertException;
}
protected virtual bool IsIgnoreException(Exception ex)
{
return ex.GetType().FullName == NUnitFramework.IgnoreException;
}
#endregion
#region Helper Methods
private bool IsStaticClass(Type type)
{
return type.IsAbstract && type.IsSealed;
}
private void RunAllTests(
TestResult suiteResult, EventListener listener, ITestFilter filter )
{
if (Properties.Contains("Timeout"))
TestExecutionContext.CurrentContext.TestCaseTimeout = (int)Properties["Timeout"];
IDictionary settings = TestExecutionContext.CurrentContext.TestPackage.Settings;
bool stopOnError = settings.Contains("StopOnError") && (bool)settings["StopOnError"];
foreach (Test test in ArrayList.Synchronized(Tests))
{
if (filter.Pass(test))
{
RunState saveRunState = test.RunState;
if (test.RunState == RunState.Runnable && this.RunState != RunState.Runnable && this.RunState != RunState.Explicit )
{
test.RunState = this.RunState;
test.IgnoreReason = this.IgnoreReason;
}
TestResult result = test.Run(listener, filter);
log.Debug("Test result = " + result.ResultState);
suiteResult.AddResult(result);
log.Debug("Suite result = " + suiteResult.ResultState);
if (saveRunState != test.RunState)
{
test.RunState = saveRunState;
test.IgnoreReason = null;
}
if (result.ResultState == ResultState.Cancelled)
break;
if ((result.IsError || result.IsFailure) && stopOnError)
break;
}
}
}
private void SkipAllTests(TestResult suiteResult, EventListener listener, ITestFilter filter)
{
suiteResult.Skip(this.IgnoreReason);
MarkTestsNotRun(this.Tests, ResultState.Skipped, this.IgnoreReason, suiteResult, listener, filter);
}
private void IgnoreAllTests(TestResult suiteResult, EventListener listener, ITestFilter filter)
{
suiteResult.Ignore(this.IgnoreReason);
MarkTestsNotRun(this.Tests, ResultState.Ignored, this.IgnoreReason, suiteResult, listener, filter);
}
private void MarkAllTestsInvalid(TestResult suiteResult, EventListener listener, ITestFilter filter)
{
suiteResult.Invalid(this.IgnoreReason);
MarkTestsNotRun(this.Tests, ResultState.NotRunnable, this.IgnoreReason, suiteResult, listener, filter);
}
private void MarkTestsNotRun(
IList tests, ResultState resultState, string ignoreReason, TestResult suiteResult, EventListener listener, ITestFilter filter)
{
foreach (Test test in ArrayList.Synchronized(tests))
{
if (filter.Pass(test))
MarkTestNotRun(test, resultState, ignoreReason, suiteResult, listener, filter);
}
}
private void MarkTestNotRun(
Test test, ResultState resultState, string ignoreReason, TestResult suiteResult, EventListener listener, ITestFilter filter)
{
if (test is TestSuite)
{
listener.SuiteStarted(test.TestName);
TestResult result = new TestResult( new TestInfo(test) );
result.SetResult( resultState, ignoreReason, null );
MarkTestsNotRun(test.Tests, resultState, ignoreReason, result, listener, filter);
suiteResult.AddResult(result);
listener.SuiteFinished(result);
}
else
{
listener.TestStarted(test.TestName);
TestResult result = new TestResult( new TestInfo(test) );
result.SetResult( resultState, ignoreReason, null );
suiteResult.AddResult(result);
listener.TestFinished(result);
}
}
private void MarkTestsFailed(
IList tests, TestResult suiteResult, EventListener listener, ITestFilter filter)
{
foreach (Test test in ArrayList.Synchronized(tests))
if (filter.Pass(test))
MarkTestFailed(test, suiteResult, listener, filter);
}
private void MarkTestFailed(
Test test, TestResult suiteResult, EventListener listener, ITestFilter filter)
{
if (test is TestSuite)
{
listener.SuiteStarted(test.TestName);
TestResult result = new TestResult( new TestInfo(test) );
string msg = this.FixtureType == null
? "Parent SetUp failed"
: string.Format( "Parent SetUp failed in {0}", this.FixtureType.Name );
result.Failure(msg, null, FailureSite.Parent);
MarkTestsFailed(test.Tests, result, listener, filter);
suiteResult.AddResult(result);
listener.SuiteFinished(result);
}
else
{
listener.TestStarted(test.TestName);
TestResult result = new TestResult( new TestInfo(test) );
string msg = this.FixtureType == null
? "TestFixtureSetUp failed"
: string.Format( "TestFixtureSetUp failed in {0}", this.FixtureType.Name );
result.Failure(msg, null, FailureSite.Parent);
suiteResult.AddResult(result);
listener.TestFinished(result);
}
}
#endregion
}
}
| |
// This code is part of the Fungus library (https://github.com/snozbot/fungus)
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
// Adapted from the Unity Test Tools project (MIT license)
// https://bitbucket.org/Unity-Technologies/unitytesttools/src/a30d562427e9/Assets/UnityTestTools/
using System;
using System.Collections;
using UnityEngine;
using Debug = UnityEngine.Debug;
using Object = UnityEngine.Object;
namespace Fungus
{
[Flags]
public enum ExecuteMethod
{
AfterPeriodOfTime = 1 << 0,
Start = 1 << 1,
Update = 1 << 2,
FixedUpdate = 1 << 3,
LateUpdate = 1 << 4,
OnDestroy = 1 << 5,
OnEnable = 1 << 6,
OnDisable = 1 << 7,
OnControllerColliderHit = 1 << 8,
OnParticleCollision = 1 << 9,
OnJointBreak = 1 << 10,
OnBecameInvisible = 1 << 11,
OnBecameVisible = 1 << 12,
OnTriggerEnter = 1 << 13,
OnTriggerExit = 1 << 14,
OnTriggerStay = 1 << 15,
OnCollisionEnter = 1 << 16,
OnCollisionExit = 1 << 17,
OnCollisionStay = 1 << 18,
OnTriggerEnter2D = 1 << 19,
OnTriggerExit2D = 1 << 20,
OnTriggerStay2D = 1 << 21,
OnCollisionEnter2D = 1 << 22,
OnCollisionExit2D = 1 << 23,
OnCollisionStay2D = 1 << 24,
}
/// <summary>
/// Executes an LuaScript component in the same gameobject when a condition occurs.
/// </summary>
public class ExecuteHandler : MonoBehaviour, IExecuteHandlerConfigurator
{
[Tooltip("Execute after a period of time.")]
[SerializeField] protected float executeAfterTime = 1f;
[Tooltip("Repeat execution after a period of time.")]
[SerializeField] protected bool repeatExecuteTime = true;
[Tooltip("Repeat forever.")]
[SerializeField] protected float repeatEveryTime = 1f;
[Tooltip("Execute after a number of frames have elapsed.")]
[SerializeField] protected int executeAfterFrames = 1;
[Tooltip("Repeat execution after a number of frames have elapsed.")]
[SerializeField] protected bool repeatExecuteFrame = true;
[Tooltip("Execute on every frame.")]
[SerializeField] protected int repeatEveryFrame = 1;
[Tooltip("The bitmask for the currently selected execution methods.")]
[SerializeField] protected ExecuteMethod executeMethods = ExecuteMethod.Start;
[Tooltip("Name of the method on a component in this gameobject to call when executing.")]
[SerializeField] protected string executeMethodName = "OnExecute";
protected int m_ExecuteOnFrame;
// Recursively build the full hierarchy path to this game object
protected static string GetPath(Transform current)
{
if (current.parent == null)
{
return current.name;
}
return GetPath(current.parent) + "." + current.name;
}
protected void Start()
{
Execute(ExecuteMethod.Start);
if (IsExecuteMethodSelected(ExecuteMethod.AfterPeriodOfTime))
{
StartCoroutine(ExecutePeriodically());
}
if (IsExecuteMethodSelected(ExecuteMethod.Update))
{
m_ExecuteOnFrame = Time.frameCount + executeAfterFrames;
}
}
protected IEnumerator ExecutePeriodically()
{
yield return new WaitForSeconds(executeAfterTime);
Execute(ExecuteMethod.AfterPeriodOfTime);
while (repeatExecuteTime)
{
yield return new WaitForSeconds(repeatEveryTime);
Execute(ExecuteMethod.AfterPeriodOfTime);
}
}
protected bool ShouldExecuteOnFrame()
{
if (Time.frameCount > m_ExecuteOnFrame)
{
if (repeatExecuteFrame)
m_ExecuteOnFrame += repeatEveryFrame;
else
m_ExecuteOnFrame = Int32.MaxValue;
return true;
}
return false;
}
protected void OnDisable()
{
Execute(ExecuteMethod.OnDisable);
}
protected void OnEnable()
{
Execute(ExecuteMethod.OnEnable);
}
protected void OnDestroy()
{
Execute(ExecuteMethod.OnDestroy);
}
protected void Update()
{
if (IsExecuteMethodSelected(ExecuteMethod.Update) && ShouldExecuteOnFrame())
{
Execute(ExecuteMethod.Update);
}
}
protected void FixedUpdate()
{
Execute(ExecuteMethod.FixedUpdate);
}
protected void LateUpdate()
{
Execute(ExecuteMethod.LateUpdate);
}
protected void OnControllerColliderHit()
{
Execute(ExecuteMethod.OnControllerColliderHit);
}
protected void OnParticleCollision()
{
Execute(ExecuteMethod.OnParticleCollision);
}
protected void OnJointBreak()
{
Execute(ExecuteMethod.OnJointBreak);
}
protected void OnBecameInvisible()
{
Execute(ExecuteMethod.OnBecameInvisible);
}
protected void OnBecameVisible()
{
Execute(ExecuteMethod.OnBecameVisible);
}
protected void OnTriggerEnter()
{
Execute(ExecuteMethod.OnTriggerEnter);
}
protected void OnTriggerExit()
{
Execute(ExecuteMethod.OnTriggerExit);
}
protected void OnTriggerStay()
{
Execute(ExecuteMethod.OnTriggerStay);
}
protected void OnCollisionEnter()
{
Execute(ExecuteMethod.OnCollisionEnter);
}
protected void OnCollisionExit()
{
Execute(ExecuteMethod.OnCollisionExit);
}
protected void OnCollisionStay()
{
Execute(ExecuteMethod.OnCollisionStay);
}
protected void OnTriggerEnter2D()
{
Execute(ExecuteMethod.OnTriggerEnter2D);
}
protected void OnTriggerExit2D()
{
Execute(ExecuteMethod.OnTriggerExit2D);
}
protected void OnTriggerStay2D()
{
Execute(ExecuteMethod.OnTriggerStay2D);
}
protected void OnCollisionEnter2D()
{
Execute(ExecuteMethod.OnCollisionEnter2D);
}
protected void OnCollisionExit2D()
{
Execute(ExecuteMethod.OnCollisionExit2D);
}
protected void OnCollisionStay2D()
{
Execute(ExecuteMethod.OnCollisionStay2D);
}
protected void Execute(ExecuteMethod executeMethod)
{
if (IsExecuteMethodSelected(executeMethod))
{
Execute();
}
}
#region Public members
/// <summary>
/// Execute after a period of time.
/// </summary>
public virtual float ExecuteAfterTime { get { return executeAfterTime; } set { executeAfterTime = value; } }
/// <summary>
/// Repeat execution after a period of time.
/// </summary>
public virtual bool RepeatExecuteTime { get { return repeatExecuteTime; } set { repeatExecuteTime = value; } }
/// <summary>
/// Repeat forever.
/// </summary>
public virtual float RepeatEveryTime { get { return repeatEveryTime; } set { repeatEveryTime = value; } }
/// <summary>
/// Execute after a number of frames have elapsed.
/// </summary>
public virtual int ExecuteAfterFrames { get { return executeAfterFrames; } set { executeAfterFrames = value; } }
/// <summary>
/// Repeat execution after a number of frames have elapsed.
/// </summary>
public virtual bool RepeatExecuteFrame { get { return repeatExecuteFrame; } set { repeatExecuteFrame = value; } }
/// <summary>
/// Execute on every frame.
/// </summary>
public virtual int RepeatEveryFrame { get { return repeatEveryFrame; } set { repeatEveryFrame = value; } }
/// <summary>
/// The bitmask for the currently selected execution methods.
/// </summary>
public virtual ExecuteMethod ExecuteMethods { get { return executeMethods; } set { executeMethods = value; } }
/// <summary>
/// Returns true if the specified execute method option has been enabled.
/// </summary>
public virtual bool IsExecuteMethodSelected(ExecuteMethod method)
{
return method == (executeMethods & method);
}
/// <summary>
/// Execute the Lua script immediately.
/// This is the function to call if you want to trigger execution from an external script.
/// </summary>
public virtual void Execute()
{
// Call any OnExecute methods in components on this gameobject
if (executeMethodName != "")
{
SendMessage(executeMethodName, SendMessageOptions.DontRequireReceiver);
}
}
#endregion
#region AssertionComponentConfigurator implementation
public int UpdateExecuteStartOnFrame { set { executeAfterFrames = value; } }
public int UpdateExecuteRepeatFrequency { set { repeatEveryFrame = value; } }
public bool UpdateExecuteRepeat { set { repeatExecuteFrame = value; } }
public float TimeExecuteStartAfter { set { executeAfterTime = value; } }
public float TimeExecuteRepeatFrequency { set { repeatEveryTime = value; } }
public bool TimeExecuteRepeat { set { repeatExecuteTime = value; } }
public ExecuteHandler Component { get { return this; } }
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.VisualStudio.Services.Agent.Util;
namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration
{
[ServiceLocator(Default = typeof(AutoLogonManager))]
public interface IAutoLogonManager : IAgentService
{
Task ConfigureAsync(CommandSettings command);
void Unconfigure();
}
public class AutoLogonManager : AgentService, IAutoLogonManager
{
private ITerminal _terminal;
private INativeWindowsServiceHelper _windowsServiceHelper;
private IAutoLogonRegistryManager _autoLogonRegManager;
private IConfigurationStore _store;
public override void Initialize(IHostContext hostContext)
{
ArgUtil.NotNull(hostContext, nameof(hostContext));
base.Initialize(hostContext);
_terminal = hostContext.GetService<ITerminal>();
_windowsServiceHelper = hostContext.GetService<INativeWindowsServiceHelper>();
_autoLogonRegManager = HostContext.GetService<IAutoLogonRegistryManager>();
_store = hostContext.GetService<IConfigurationStore>();
}
public async Task ConfigureAsync(CommandSettings command)
{
ArgUtil.NotNull(command, nameof(command));
if (!_windowsServiceHelper.IsRunningInElevatedMode())
{
Trace.Error("Needs Administrator privileges to configure agent with AutoLogon capability.");
throw new SecurityException(StringUtil.Loc("NeedAdminForAutologonCapability"));
}
string domainName;
string userName;
string logonAccount;
string logonPassword;
while (true)
{
logonAccount = command.GetWindowsLogonAccount(defaultValue: string.Empty, descriptionMsg: StringUtil.Loc("AutoLogonAccountNameDescription"));
GetAccountSegments(logonAccount, out domainName, out userName);
if ((string.IsNullOrEmpty(domainName) || domainName.Equals(".", StringComparison.CurrentCultureIgnoreCase)) && !logonAccount.Contains("@"))
{
logonAccount = String.Format("{0}\\{1}", Environment.MachineName, userName);
domainName = Environment.MachineName;
}
Trace.Info("LogonAccount after transforming: {0}, user: {1}, domain: {2}", logonAccount, userName, domainName);
logonPassword = command.GetWindowsLogonPassword(logonAccount);
if (_windowsServiceHelper.IsValidAutoLogonCredential(domainName, userName, logonPassword))
{
Trace.Info("Credential validation succeeded");
break;
}
if (command.Unattended())
{
throw new SecurityException(StringUtil.Loc("InvalidAutoLogonCredential"));
}
Trace.Error("Invalid credential entered.");
_terminal.WriteError(StringUtil.Loc("InvalidAutoLogonCredential"));
}
_autoLogonRegManager.GetAutoLogonUserDetails(out string currentAutoLogonUserDomainName, out string currentAutoLogonUserName);
if (currentAutoLogonUserName != null
&& !userName.Equals(currentAutoLogonUserName, StringComparison.CurrentCultureIgnoreCase)
&& !domainName.Equals(currentAutoLogonUserDomainName, StringComparison.CurrentCultureIgnoreCase))
{
string currentAutoLogonAccount = String.Format("{0}\\{1}", currentAutoLogonUserDomainName, currentAutoLogonUserName);
if (string.IsNullOrEmpty(currentAutoLogonUserDomainName) || currentAutoLogonUserDomainName.Equals(".", StringComparison.CurrentCultureIgnoreCase))
{
currentAutoLogonAccount = String.Format("{0}\\{1}", Environment.MachineName, currentAutoLogonUserName);
}
Trace.Warning($"AutoLogon already enabled for {currentAutoLogonAccount}.");
if (!command.GetOverwriteAutoLogon(currentAutoLogonAccount))
{
Trace.Error("Marking the agent configuration as failed due to the denial of autologon setting overwriting by the user.");
throw new InvalidOperationException(StringUtil.Loc("AutoLogonOverwriteDeniedError", currentAutoLogonAccount));
}
Trace.Info($"Continuing with the autologon configuration.");
}
// grant permission for agent root folder and work folder
Trace.Info("Create local group and grant folder permission to logon account.");
string agentRoot = HostContext.GetDirectory(WellKnownDirectory.Root);
string workFolder = HostContext.GetDirectory(WellKnownDirectory.Work);
Directory.CreateDirectory(workFolder);
_windowsServiceHelper.GrantDirectoryPermissionForAccount(logonAccount, new[] { agentRoot, workFolder });
_autoLogonRegManager.UpdateRegistrySettings(command, domainName, userName, logonPassword);
_windowsServiceHelper.SetAutoLogonPassword(logonPassword);
await ConfigurePowerOptions();
SaveAutoLogonSettings(domainName, userName);
RestartBasedOnUserInput(command);
}
public void Unconfigure()
{
if (!_windowsServiceHelper.IsRunningInElevatedMode())
{
Trace.Error("Needs Administrator privileges to unconfigure an agent running with AutoLogon capability.");
throw new SecurityException(StringUtil.Loc("NeedAdminForAutologonRemoval"));
}
var autoLogonSettings = _store.GetAutoLogonSettings();
_autoLogonRegManager.ResetRegistrySettings(autoLogonSettings.UserDomainName, autoLogonSettings.UserName);
_windowsServiceHelper.ResetAutoLogonPassword();
// Delete local group we created during configure.
string agentRoot = HostContext.GetDirectory(WellKnownDirectory.Root);
string workFolder = HostContext.GetDirectory(WellKnownDirectory.Work);
_windowsServiceHelper.RevokeDirectoryPermissionForAccount(new[] { agentRoot, workFolder });
Trace.Info("Deleting the autologon settings now.");
_store.DeleteAutoLogonSettings();
Trace.Info("Successfully deleted the autologon settings.");
}
private void SaveAutoLogonSettings(string domainName, string userName)
{
Trace.Entering();
var settings = new AutoLogonSettings()
{
UserDomainName = domainName,
UserName = userName
};
_store.SaveAutoLogonSettings(settings);
Trace.Info("Saved the autologon settings");
}
private async Task ConfigurePowerOptions()
{
var filePath = WhichUtil.Which("powercfg.exe", require: true, trace: Trace);
string[] commands = new string[] { "/Change monitor-timeout-ac 0", "/Change monitor-timeout-dc 0" };
foreach (var command in commands)
{
try
{
Trace.Info($"Running powercfg.exe with {command}");
using (var processInvoker = HostContext.CreateService<IProcessInvoker>())
{
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
Trace.Info(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
Trace.Error(message.Data);
_terminal.WriteError(message.Data);
};
await processInvoker.ExecuteAsync(
workingDirectory: string.Empty,
fileName: filePath,
arguments: command,
environment: null,
cancellationToken: CancellationToken.None);
}
}
catch (Exception ex)
{
//we will not stop the configuration. just show the warning and continue
_terminal.WriteError(StringUtil.Loc("PowerOptionsConfigError"));
Trace.Error(ex);
}
}
}
private void RestartBasedOnUserInput(CommandSettings command)
{
Trace.Info("Asking the user to restart the machine to launch agent and for autologon settings to take effect.");
_terminal.WriteLine(StringUtil.Loc("RestartMessage"));
var noRestart = command.GetNoRestart();
if (!noRestart)
{
var shutdownExePath = WhichUtil.Which("shutdown.exe", trace: Trace);
Trace.Info("Restarting the machine in 15 seconds");
_terminal.WriteLine(StringUtil.Loc("RestartIn15SecMessage"));
string msg = StringUtil.Loc("ShutdownMessage");
//we are not using ProcessInvoker here as today it is not designed for 'fire and forget' pattern
//ExecuteAsync API of ProcessInvoker waits for the process to exit
var args = $@"-r -t 15 -c ""{msg}""";
Trace.Info($"Shutdown.exe path: {shutdownExePath}. Arguments: {args}");
Process.Start(shutdownExePath, $@"{args}");
}
else
{
_terminal.WriteLine(StringUtil.Loc("NoRestartSuggestion"));
}
}
//todo: move it to a utility class so that at other places it can be re-used
private void GetAccountSegments(string account, out string domain, out string user)
{
string[] segments = account.Split('\\');
domain = string.Empty;
user = account;
if (segments.Length == 2)
{
domain = segments[0];
user = segments[1];
}
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.DataAccessLib;
using Vevo.Domain;
using Vevo.Domain.Users;
using Vevo.Shared.DataAccess;
using Vevo.WebAppLib;
using Vevo.WebUI.Ajax;
using Vevo.WebUI.Users;
public partial class AdminAdvanced_MainControls_StateList : AdminAdvancedBaseUserControl
{
private bool _emptyRow = false;
private int _checkBoxColumn = 0;
private int _editColunm = 4;
private bool IsContainingOnlyEmptyRow
{
get { return _emptyRow; }
set { _emptyRow = value; }
}
private bool IsStateAlreadyExisted( string stateCode )
{
State state = DataAccessContext.StateRepository.GetOne( CountryCode, stateCode );
return !state.IsNull;
}
protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e )
{
GridHelper.SelectSorting( e.SortExpression );
RefreshGrid();
}
private GridViewHelper GridHelper
{
get
{
if (ViewState["GridHelper"] == null)
ViewState["GridHelper"] = new GridViewHelper( uxGrid, "StateName" );
return (GridViewHelper) ViewState["GridHelper"];
}
}
private string CurrentStateCode
{
get
{
if (ViewState["StateCode"] == null)
return String.Empty;
else
return ViewState["StateCode"].ToString();
}
set
{
ViewState["StateCode"] = value;
}
}
private string CountryCode
{
get
{
return MainContext.QueryString["CountryCode"];
}
}
private void SetFooterRowFocus()
{
Control textBox = uxGrid.FooterRow.FindControl( "uxStateNameText" );
AjaxUtilities.GetScriptManager( textBox ).SetFocus( textBox );
}
protected void PopulateControls()
{
if (IsAdminModifiable())
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteButton";
uxResetConfirmButton.TargetControlID = "uxResetButton";
uxReSetConfirmModalPopup.TargetControlID = "uxResetButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
uxResetConfirmButton.TargetControlID = "uxResetDummyButton";
uxReSetConfirmModalPopup.TargetControlID = "uxResetDummyButton";
}
}
else
{
uxAddButton.Visible = false;
uxEnabledButton.Visible = false;
uxDisableButton.Visible = false;
}
RefreshGrid();
}
protected void uxGrid_DataBound( object sender, EventArgs e )
{
// Do not display empty row
//if (IsContainingOnlyEmptyRow())
//{
// uxGrid.Rows[0].Visible = false;
//}
}
protected void uxDeleteButton_Click( object sender, EventArgs e )
{
bool deleted = false;
foreach (GridViewRow row in uxGrid.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck != null &&
deleteCheck.Checked)
{
string stateCode = uxGrid.DataKeys[row.RowIndex]["StateCode"].ToString();
DataAccessContext.StateRepository.Delete( CountryCode, stateCode );
deleted = true;
}
}
uxGrid.EditIndex = -1;
if (deleted)
{
uxMessage.DisplayMessage( Resources.CustomerMessages.DeleteSuccess );
}
RefreshGrid();
}
protected void uxEnabledButton_Click( object sender, EventArgs e )
{
bool enabled = false;
foreach (GridViewRow row in uxGrid.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck != null &&
deleteCheck.Checked)
{
string stateCode = uxGrid.DataKeys[row.RowIndex]["StateCode"].ToString();
State state = DataAccessContext.StateRepository.GetOne( CountryCode, stateCode );
state.Enabled = true;
DataAccessContext.StateRepository.Update( state );
enabled = true;
}
}
uxGrid.EditIndex = -1;
if (enabled)
{
uxMessage.DisplayMessage( Resources.CustomerMessages.EnabledSuccess );
}
RefreshGrid();
}
protected void uxDisableButton_Click( object sender, EventArgs e )
{
bool enabled = false;
foreach (GridViewRow row in uxGrid.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck != null &&
deleteCheck.Checked)
{
string stateCode = uxGrid.DataKeys[row.RowIndex]["StateCode"].ToString();
State state = DataAccessContext.StateRepository.GetOne( CountryCode, stateCode );
state.Enabled = false;
DataAccessContext.StateRepository.Update( state );
enabled = true;
}
}
uxGrid.EditIndex = -1;
if (enabled)
{
uxMessage.DisplayMessage( Resources.CustomerMessages.DisableSuccess );
}
RefreshGrid();
}
protected void Page_Load( object sender, EventArgs e )
{
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!MainContext.IsPostBack)
{
PopulateControls();
}
}
protected void uxResetButton_Click( object sender, EventArgs e )
{
ResetStateData();
RefreshGrid();
}
protected void uxAddButton_Click( object sender, EventArgs e )
{
uxGrid.EditIndex = -1;
uxGrid.ShowFooter = true;
uxGrid.ShowHeader = true;
RefreshGrid();
uxAddButton.Visible = false;
SetFooterRowFocus();
}
private void InsertEmptyRow( IList<State> stateList )
{
State state = new State();
state.SortOrder = -1;
state.CountryCode = String.Empty;
state.StateCode = String.Empty;
state.StateName = String.Empty;
state.Enabled = true;
stateList.Add( state );
}
private IList<State> CreateSourceList()
{
IList<State> stateList = DataAccessContext.StateRepository.GetAllByCountryCode( CountryCode, "StateName", BoolFilter.ShowAll );
IList<State> stateListSource = new List<State>();
for (int i = 0; i < stateList.Count; i++)
{
stateListSource.Add( stateList[i] );
}
return stateListSource;
}
private void RefreshGrid()
{
if (!String.IsNullOrEmpty( CountryCode ))
{
if (CountryCode == "US" && IsAdminModifiable())
ResetVisible( true );
else
ResetVisible( false );
IList<State> stateList = CreateSourceList();
if (stateList.Count == 0)
{
IsContainingOnlyEmptyRow = true;
InsertEmptyRow( stateList );
}
else
{
IsContainingOnlyEmptyRow = false;
uxGrid.ShowHeader = true;
}
uxGrid.DataSource = stateList;
uxGrid.DataBind();
if (IsContainingOnlyEmptyRow)
{
uxGrid.Rows[0].Visible = false;
}
RefreshDeleteButton();
if (!uxAddButton.Visible)
{
if (IsAdminModifiable())
{
uxGrid.ShowFooter = true;
}
}
if (uxGrid.ShowFooter)
{
Control stateNameText = uxGrid.FooterRow.FindControl( "uxStateNameText" );
Control stateCodeText = uxGrid.FooterRow.FindControl( "uxStateCodeText" );
Control addButton = uxGrid.FooterRow.FindControl( "uxAddButton" );
WebUtilities.TieButton( this.Page, stateNameText, addButton );
WebUtilities.TieButton( this.Page, stateCodeText, addButton );
}
}
else
MainContext.RedirectMainControl( "CountryList.ascx", "" );
}
private void ResetVisible( bool value )
{
uxResetButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxResetConfirmButton.TargetControlID = "uxResetButton";
uxReSetConfirmModalPopup.TargetControlID = "uxResetButton";
}
else
{
uxResetConfirmButton.TargetControlID = "uxResetDummyButton";
uxReSetConfirmModalPopup.TargetControlID = "uxResetDummyButton";
}
}
else
{
uxResetConfirmButton.TargetControlID = "uxResetDummyButton";
uxReSetConfirmModalPopup.TargetControlID = "uxResetDummyButton";
}
}
private void DeleteVisible( bool value )
{
uxDeleteButton.Visible = value;
uxEnabledButton.Visible = value;
uxDisableButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
private void RefreshDeleteButton()
{
if (IsAdminModifiable())
{
if (IsContainingOnlyEmptyRow)
DeleteVisible( false );
else
DeleteVisible( true );
}
else
{
DeleteVisible( false );
uxGrid.Columns[_checkBoxColumn].Visible = false;
uxGrid.Columns[_editColunm].Visible = false;
}
}
protected void uxGrid_RowEditing( object sender, GridViewEditEventArgs e )
{
uxGrid.EditIndex = e.NewEditIndex;
RefreshGrid();
}
protected void uxGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e )
{
uxGrid.EditIndex = -1;
CurrentStateCode = "";
RefreshGrid();
}
protected void uxGrid_RowCommand( object sender, GridViewCommandEventArgs e )
{
if (e.CommandName == "Add")
{
try
{
string stateName = ((TextBox) uxGrid.FooterRow.FindControl( "uxStateNameText" )).Text;
string stateCode = ((TextBox) uxGrid.FooterRow.FindControl( "uxStateCodeText" )).Text;
bool enabled = ((CheckBox) uxGrid.FooterRow.FindControl( "uxEnabledCheck" )).Checked;
State state = DataAccessContext.StateRepository.GetOne( CountryCode, stateCode );
if (state.IsNull)
{
State newState = new State();
newState.CountryCode = CountryCode;
newState.StateCode = stateCode;
newState.StateName = stateName;
newState.SortOrder = DataAccessContext.StateRepository.GetAllByCountryCode( CountryCode, "", BoolFilter.ShowAll ).Count;
newState.Enabled = enabled;
DataAccessContext.StateRepository.Create( newState );
((TextBox) uxGrid.FooterRow.FindControl( "uxStateNameText" )).Text = "";
((TextBox) uxGrid.FooterRow.FindControl( "uxStateCodeText" )).Text = "";
uxMessage.DisplayMessage( Resources.StateListMessages.AddSuccess );
}
else
uxMessage.DisplayError( "State code can't duplicate." );
}
catch (Exception ex)
{
string message;
if (ex.InnerException is DuplicatedPrimaryKeyException)
message = Resources.StateListMessages.AddErrorDuplicated;
else
message = Resources.StateListMessages.AddError;
throw new VevoException( message );
}
finally
{
}
RefreshGrid();
}
if (e.CommandName == "Edit")
{
try
{
CurrentStateCode = e.CommandArgument.ToString();
uxGrid.ShowFooter = false;
uxAddButton.Visible = true;
}
catch (Exception ex)
{
uxMessage.DisplayError( ex.Message );
}
}
}
protected void uxGrid_RowUpdating( object sender, GridViewUpdateEventArgs e )
{
try
{
string stateName = ((TextBox) uxGrid.Rows[e.RowIndex].FindControl( "uxStateNameText" )).Text;
string stateCode = ((TextBox) uxGrid.Rows[e.RowIndex].FindControl( "uxStateCodeText" )).Text;
bool enabled = ((CheckBox) uxGrid.Rows[e.RowIndex].FindControl( "uxEnabledCheck" )).Checked;
if (!String.IsNullOrEmpty( CurrentStateCode ))
{
if (CurrentStateCode == stateCode ||
!IsStateAlreadyExisted( stateCode ))
{
State state = DataAccessContext.StateRepository.GetOne( CountryCode, CurrentStateCode );
state.StateName = stateName;
state.Enabled = enabled;
DataAccessContext.StateRepository.Update( state, stateCode );
uxMessage.DisplayMessage( Resources.StateListMessages.UpdateSuccess );
}
else
uxMessage.DisplayError(Resources.StateListMessages.UpdateErrorDuplicated);
}
// End editing
uxGrid.EditIndex = -1;
CurrentStateCode = "";
RefreshGrid();
}
catch (Exception ex)
{
string message;
if (ex.InnerException is DuplicatedPrimaryKeyException)
message = Resources.StateListMessages.UpdateErrorDuplicated;
else
message = Resources.StateListMessages.UpdateError;
throw new ApplicationException( message );
}
finally
{
// Avoid calling Update() automatically by GridView
e.Cancel = true;
}
}
private void ResetStateData()
{
try
{
AddressUtilities.RestoreDefaultStateCode();
uxMessage.DisplayMessage( "Reset state list successfully." );
}
catch (Exception ex)
{
uxMessage.DisplayError( ex.Message );
}
}
}
| |
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 Postcard.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using CoreLocation;
using Foundation;
using Plugin.Geolocator.Abstractions;
#if __IOS__ || __TVOS__
using UIKit;
#elif __MACOS__
using AppKit;
#endif
#if __IOS__
using Plugin.Permissions.Abstractions;
#endif
namespace Plugin.Geolocator
{
/// <summary>
/// Implementation for Geolocator
/// </summary>
[Preserve(AllMembers = true)]
public class GeolocatorImplementation : IGeolocator
{
bool deferringUpdates;
readonly CLLocationManager manager;
bool includeHeading;
bool isListening;
Position lastPosition;
ListenerSettings listenerSettings;
/// <summary>
/// Constructor for implementation
/// </summary>
public GeolocatorImplementation()
{
DesiredAccuracy = 100;
manager = GetManager();
manager.AuthorizationChanged += OnAuthorizationChanged;
manager.Failed += OnFailed;
#if __IOS__
if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
manager.LocationsUpdated += OnLocationsUpdated;
else
manager.UpdatedLocation += OnUpdatedLocation;
#elif __MACOS__ || __TVOS__
manager.LocationsUpdated += OnLocationsUpdated;
#endif
#if __IOS__ || __MACOS__
manager.DeferredUpdatesFinished += OnDeferredUpdatedFinished;
#endif
#if __TVOS__
RequestAuthorization();
#endif
}
void OnDeferredUpdatedFinished(object sender, NSErrorEventArgs e) => deferringUpdates = false;
#if __IOS__
bool CanDeferLocationUpdate => CLLocationManager.DeferredLocationUpdatesAvailable && UIDevice.CurrentDevice.CheckSystemVersion(6, 0);
#elif __MACOS__
bool CanDeferLocationUpdate => CLLocationManager.DeferredLocationUpdatesAvailable;
#elif __TVOS__
bool CanDeferLocationUpdate => false;
#endif
#if __IOS__
async Task<bool> CheckWhenInUsePermission()
{
var status = await Permissions.CrossPermissions.Current.CheckPermissionStatusAsync<Permissions.LocationWhenInUsePermission>();
if (status != PermissionStatus.Granted)
{
Console.WriteLine("Currently does not have Location permissions, requesting permissions");
status = await Permissions.CrossPermissions.Current.RequestPermissionAsync<Permissions.LocationWhenInUsePermission>();
if (status != PermissionStatus.Granted)
{
Console.WriteLine("Location permission denied, can not get positions async.");
return false;
}
}
return true;
}
async Task<bool> CheckAlwaysPermissions()
{
var status = await Permissions.CrossPermissions.Current.CheckPermissionStatusAsync<Permissions.LocationAlwaysPermission>();
if (status != PermissionStatus.Granted)
{
Console.WriteLine("Currently does not have Location permissions, requesting permissions");
status = await Permissions.CrossPermissions.Current.RequestPermissionAsync<Permissions.LocationAlwaysPermission>();
if (status != PermissionStatus.Granted)
{
Console.WriteLine("Location permission denied, can not get positions async.");
return false;
}
}
return true;
}
#endif
/// <summary>
/// Position error event handler
/// </summary>
public event EventHandler<PositionErrorEventArgs> PositionError;
/// <summary>
/// Position changed event handler
/// </summary>
public event EventHandler<PositionEventArgs> PositionChanged;
/// <summary>
/// Desired accuracy in meters
/// </summary>
public double DesiredAccuracy
{
get;
set;
}
/// <summary>
/// Gets if you are listening for location changes
///
public bool IsListening => isListening;
#if __IOS__ || __MACOS__
/// <summary>
/// Gets if device supports heading (course)
/// </summary>
public bool SupportsHeading => true;
#elif __TVOS__
/// <summary>
/// Gets if device supports heading
/// </summary>
public bool SupportsHeading => false;
#endif
/// <summary>
/// Gets if geolocation is available on device
/// </summary>
public bool IsGeolocationAvailable => true; //all iOS devices support Geolocation
/// <summary>
/// Gets if geolocation is enabled on device
/// </summary>
public bool IsGeolocationEnabled
{
get
{
var status = CLLocationManager.Status;
return CLLocationManager.LocationServicesEnabled;
}
}
void RequestAuthorization()
{
#if __IOS__
var info = NSBundle.MainBundle.InfoDictionary;
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
if (info.ContainsKey(new NSString("NSLocationAlwaysUsageDescription")))
manager.RequestAlwaysAuthorization();
else if (info.ContainsKey(new NSString("NSLocationWhenInUseUsageDescription")))
manager.RequestWhenInUseAuthorization();
else
throw new UnauthorizedAccessException("On iOS 8.0 and higher you must set either NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in your Info.plist file to enable Authorization Requests for Location updates!");
}
#elif __MACOS__
//nothing to do here.
#elif __TVOS__
var info = NSBundle.MainBundle.InfoDictionary;
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
if (info.ContainsKey(new NSString("NSLocationWhenInUseUsageDescription")))
manager.RequestWhenInUseAuthorization();
else
throw new UnauthorizedAccessException("On tvOS 8.0 and higher you must set either NSLocationWhenInUseUsageDescription in your Info.plist file to enable Authorization Requests for Location updates!");
}
#endif
}
/// <summary>
/// Gets the last known and most accurate location.
/// This is usually cached and best to display first before querying for full position.
/// </summary>
/// <returns>Best and most recent location or null if none found</returns>
public async Task<Position> GetLastKnownLocationAsync()
{
#if __IOS__
var hasPermission = await CheckWhenInUsePermission();
if (!hasPermission)
throw new GeolocationException(GeolocationError.Unauthorized);
#endif
var m = GetManager();
var newLocation = m?.Location;
if (newLocation == null)
return null;
var position = new Position();
position.Accuracy = newLocation.HorizontalAccuracy;
position.Altitude = newLocation.Altitude;
position.AltitudeAccuracy = newLocation.VerticalAccuracy;
position.Latitude = newLocation.Coordinate.Latitude;
position.Longitude = newLocation.Coordinate.Longitude;
#if !__TVOS__
position.Speed = newLocation.Speed;
#endif
try
{
position.Timestamp = new DateTimeOffset(newLocation.Timestamp.ToDateTime());
}
catch (Exception ex)
{
position.Timestamp = DateTimeOffset.UtcNow;
}
return position;
}
/// <summary>
/// Gets position async with specified parameters
/// </summary>
/// <param name="timeout">Timeout to wait, Default Infinite</param>
/// <param name="cancelToken">Cancelation token</param>
/// <param name="includeHeading">If you would like to include heading</param>
/// <returns>Position</returns>
public async Task<Position> GetPositionAsync(TimeSpan? timeout, CancellationToken? cancelToken = null, bool includeHeading = false)
{
#if __IOS__
var hasPermission = await CheckWhenInUsePermission();
if (!hasPermission)
throw new GeolocationException(GeolocationError.Unauthorized);
#endif
var timeoutMilliseconds = timeout.HasValue ? (int)timeout.Value.TotalMilliseconds : Timeout.Infinite;
if (timeoutMilliseconds <= 0 && timeoutMilliseconds != Timeout.Infinite)
throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive or Timeout.Infinite");
if (!cancelToken.HasValue)
cancelToken = CancellationToken.None;
TaskCompletionSource<Position> tcs;
if (!IsListening)
{
var m = GetManager();
m.DesiredAccuracy = DesiredAccuracy;
tcs = new TaskCompletionSource<Position>(m);
var singleListener = new GeolocationSingleUpdateDelegate(m, DesiredAccuracy, includeHeading, timeoutMilliseconds, cancelToken.Value);
m.Delegate = singleListener;
#if __IOS__ || __MACOS__
m.StartUpdatingLocation();
#elif __TVOS__
m.RequestLocation();
#endif
return await singleListener.Task;
}
tcs = new TaskCompletionSource<Position>();
if (lastPosition == null)
{
if (cancelToken != CancellationToken.None)
{
cancelToken.Value.Register(() => tcs.TrySetCanceled());
}
EventHandler<PositionErrorEventArgs> gotError = null;
gotError = (s, e) =>
{
tcs.TrySetException(new GeolocationException(e.Error));
PositionError -= gotError;
};
PositionError += gotError;
EventHandler<PositionEventArgs> gotPosition = null;
gotPosition = (s, e) =>
{
tcs.TrySetResult(e.Position);
PositionChanged -= gotPosition;
};
PositionChanged += gotPosition;
}
else
tcs.SetResult(lastPosition);
return await tcs.Task;
}
/// <summary>
/// Retrieve positions for address.
/// </summary>
/// <param name="address">Desired address</param>
/// <param name="mapKey">Map Key required only on UWP</param>
/// <returns>Positions of the desired address</returns>
public async Task<IEnumerable<Position>> GetPositionsForAddressAsync(string address, string mapKey = null)
{
if (address == null)
throw new ArgumentNullException(nameof(address));
using (var geocoder = new CLGeocoder())
{
var positionList = await geocoder.GeocodeAddressAsync(address);
return positionList.Select(p => new Position
{
Latitude = p.Location.Coordinate.Latitude,
Longitude = p.Location.Coordinate.Longitude
});
}
}
/// <summary>
/// Retrieve addresses for position.
/// </summary>
/// <param name="position">Desired position (latitude and longitude)</param>
/// <returns>Addresses of the desired position</returns>
public async Task<IEnumerable<Address>> GetAddressesForPositionAsync(Position position, string mapKey = null)
{
if (position == null)
throw new ArgumentNullException(nameof(position));
using (var geocoder = new CLGeocoder())
{
var addressList = await geocoder.ReverseGeocodeLocationAsync(new CLLocation(position.Latitude, position.Longitude));
return addressList?.ToAddresses() ?? null;
}
}
/// <summary>
/// Start listening for changes
/// </summary>
/// <param name="minimumTime">Time</param>
/// <param name="minimumDistance">Distance</param>
/// <param name="includeHeading">Include heading or not</param>
/// <param name="listenerSettings">Optional settings (iOS only)</param>
public async Task<bool> StartListeningAsync(TimeSpan minimumTime, double minimumDistance, bool includeHeading = false, ListenerSettings listenerSettings = null)
{
if (minimumDistance < 0)
throw new ArgumentOutOfRangeException(nameof(minimumDistance));
if (isListening)
throw new InvalidOperationException("Already listening");
// if no settings were passed in, instantiate the default settings. need to check this and create default settings since
// previous calls to StartListeningAsync might have already configured the location manager in a non-default way that the
// caller of this method might not be expecting. the caller should expect the defaults if they pass no settings.
if (listenerSettings == null)
listenerSettings = new ListenerSettings();
#if __IOS__
var hasPermission = false;
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
{
if (listenerSettings.AllowBackgroundUpdates)
hasPermission = await CheckAlwaysPermissions();
else
hasPermission = await CheckWhenInUsePermission();
}
if (!hasPermission)
throw new GeolocationException(GeolocationError.Unauthorized);
#endif
#if __IOS__ || __MACOS__
this.includeHeading = includeHeading;
#endif
// keep reference to settings so that we can stop the listener appropriately later
this.listenerSettings = listenerSettings;
var desiredAccuracy = DesiredAccuracy;
// set background flag
#if __IOS__
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
manager.ShowsBackgroundLocationIndicator = listenerSettings.ShowsBackgroundLocationIndicator;
if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
manager.AllowsBackgroundLocationUpdates = listenerSettings.AllowBackgroundUpdates;
// configure location update pausing
if (UIDevice.CurrentDevice.CheckSystemVersion(6, 0))
{
manager.PausesLocationUpdatesAutomatically = listenerSettings.PauseLocationUpdatesAutomatically;
switch (listenerSettings.ActivityType)
{
case ActivityType.AutomotiveNavigation:
manager.ActivityType = CLActivityType.AutomotiveNavigation;
break;
case ActivityType.Fitness:
manager.ActivityType = CLActivityType.Fitness;
break;
case ActivityType.OtherNavigation:
manager.ActivityType = CLActivityType.OtherNavigation;
break;
default:
manager.ActivityType = CLActivityType.Other;
break;
}
}
#endif
// to use deferral, CLLocationManager.DistanceFilter must be set to CLLocationDistance.None, and CLLocationManager.DesiredAccuracy must be
// either CLLocation.AccuracyBest or CLLocation.AccuracyBestForNavigation. deferral only available on iOS 6.0 and above.
if (CanDeferLocationUpdate && listenerSettings.DeferLocationUpdates)
{
minimumDistance = CLLocationDistance.FilterNone;
desiredAccuracy = CLLocation.AccuracyBest;
}
isListening = true;
manager.DesiredAccuracy = desiredAccuracy;
manager.DistanceFilter = minimumDistance;
#if __IOS__ || __MACOS__
if (listenerSettings.ListenForSignificantChanges)
manager.StartMonitoringSignificantLocationChanges();
else
manager.StartUpdatingLocation();
#elif __TVOS__
//not supported
#endif
return true;
}
/// <summary>
/// Stop listening
/// </summary>
public Task<bool> StopListeningAsync()
{
if (!isListening)
return Task.FromResult(true);
isListening = false;
#if __IOS__
// it looks like deferred location updates can apply to the standard service or significant change service. disallow deferral in either case.
if ((listenerSettings?.DeferLocationUpdates ?? false) && CanDeferLocationUpdate)
manager.DisallowDeferredLocationUpdates();
#endif
#if __IOS__ || __MACOS__
if (listenerSettings?.ListenForSignificantChanges ?? false)
manager.StopMonitoringSignificantLocationChanges();
else
manager.StopUpdatingLocation();
#endif
listenerSettings = null;
lastPosition = null;
return Task.FromResult(true);
}
CLLocationManager GetManager()
{
CLLocationManager m = null;
new NSObject().InvokeOnMainThread(() => m = new CLLocationManager());
return m;
}
void OnLocationsUpdated(object sender, CLLocationsUpdatedEventArgs e)
{
foreach (var location in e.Locations)
UpdatePosition(location);
// defer future location updates if requested
if ((listenerSettings?.DeferLocationUpdates ?? false) && !deferringUpdates && CanDeferLocationUpdate)
{
#if __IOS__
manager.AllowDeferredLocationUpdatesUntil(listenerSettings.DeferralDistanceMeters == null ? CLLocationDistance.MaxDistance : listenerSettings.DeferralDistanceMeters.GetValueOrDefault(),
listenerSettings.DeferralTime == null ? CLLocationManager.MaxTimeInterval : listenerSettings.DeferralTime.GetValueOrDefault().TotalSeconds);
#endif
deferringUpdates = true;
}
}
#if __IOS__ || __MACOS__
void OnUpdatedLocation(object sender, CLLocationUpdatedEventArgs e) => UpdatePosition(e.NewLocation);
#endif
void UpdatePosition(CLLocation location)
{
var p = (lastPosition == null) ? new Position() : new Position(this.lastPosition);
if (location.HorizontalAccuracy > -1)
{
p.Accuracy = location.HorizontalAccuracy;
p.Latitude = location.Coordinate.Latitude;
p.Longitude = location.Coordinate.Longitude;
}
if (location.VerticalAccuracy > -1)
{
p.Altitude = location.Altitude;
p.AltitudeAccuracy = location.VerticalAccuracy;
}
#if __IOS__ || __MACOS__
if (location.Speed > -1)
p.Speed = location.Speed;
if (includeHeading && location.Course > -1)
p.Heading = location.Course;
#endif
try
{
var date = location.Timestamp.ToDateTime();
p.Timestamp = new DateTimeOffset(date);
}
catch (Exception)
{
p.Timestamp = DateTimeOffset.UtcNow;
}
lastPosition = p;
OnPositionChanged(new PositionEventArgs(p));
location.Dispose();
}
void OnPositionChanged(PositionEventArgs e) => PositionChanged?.Invoke(this, e);
async void OnPositionError(PositionErrorEventArgs e)
{
await StopListeningAsync();
PositionError?.Invoke(this, e);
}
void OnFailed(object sender, NSErrorEventArgs e)
{
if ((CLError)(int)e.Error.Code == CLError.Network)
OnPositionError(new PositionErrorEventArgs(GeolocationError.PositionUnavailable));
}
void OnAuthorizationChanged(object sender, CLAuthorizationChangedEventArgs e)
{
if (e.Status == CLAuthorizationStatus.Denied || e.Status == CLAuthorizationStatus.Restricted)
OnPositionError(new PositionErrorEventArgs(GeolocationError.Unauthorized));
}
}
}
| |
#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 CallableDefinition : TypeMember, INodeWithParameters, INodeWithGenericParameters
{
protected ParameterDeclarationCollection _parameters;
protected GenericParameterDeclarationCollection _genericParameters;
protected TypeReference _returnType;
protected AttributeCollection _returnTypeAttributes;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public CallableDefinition CloneNode()
{
return (CallableDefinition)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public CallableDefinition CleanClone()
{
return (CallableDefinition)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.CallableDefinition; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnCallableDefinition(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 = ( CallableDefinition)node;
if (_modifiers != other._modifiers) return NoMatch("CallableDefinition._modifiers");
if (_name != other._name) return NoMatch("CallableDefinition._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("CallableDefinition._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("CallableDefinition._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("CallableDefinition._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("CallableDefinition._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("CallableDefinition._returnTypeAttributes");
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 (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
CallableDefinition clone = new CallableDefinition();
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(ParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ParameterDeclarationCollection Parameters
{
get { return _parameters ?? (_parameters = new ParameterDeclarationCollection(this)); }
set
{
if (_parameters != value)
{
_parameters = value;
if (null != _parameters)
{
_parameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(GenericParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public GenericParameterDeclarationCollection GenericParameters
{
get { return _genericParameters ?? (_genericParameters = new GenericParameterDeclarationCollection(this)); }
set
{
if (_genericParameters != value)
{
_genericParameters = value;
if (null != _genericParameters)
{
_genericParameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference ReturnType
{
get { return _returnType; }
set
{
if (_returnType != value)
{
_returnType = value;
if (null != _returnType)
{
_returnType.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Attribute))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public AttributeCollection ReturnTypeAttributes
{
get { return _returnTypeAttributes ?? (_returnTypeAttributes = new AttributeCollection(this)); }
set
{
if (_returnTypeAttributes != value)
{
_returnTypeAttributes = value;
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.InitializeParent(this);
}
}
}
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using CmsEngine.Application.EditModels;
using CmsEngine.Application.ViewModels;
using CmsEngine.Application.ViewModels.DataTableViewModels;
using CmsEngine.Data.Entities;
namespace CmsEngine.Application.Extensions.Mapper
{
public static class PostExtensions
{
/// <summary>
/// Maps Post model into a PostEditModel
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static PostEditModel MapToEditModel(this Post item)
{
return new PostEditModel
{
Id = item.Id,
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn,
Status = item.Status,
SelectedCategories = item.PostCategories.Select(x => x.Category.VanityId.ToString()),
SelectedTags = item.PostTags.Select(x => x.Tag.VanityId.ToString())
};
}
/// <summary>
/// Maps an IEnumerable<Post> into an IEnumerable<PostEditModel>
/// </summary>
/// <param name="posts"></param>
/// <returns></returns>
public static IEnumerable<PostEditModel> MapToEditModel(this IEnumerable<Post> posts)
{
var editModels = new List<PostEditModel>();
foreach (var item in posts)
{
editModels.Add(new PostEditModel
{
Id = item.Id,
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn,
Status = item.Status
});
}
return editModels;
}
/// <summary>
/// Maps a PostEditModel into a Post
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static Post MapToModel(this PostEditModel item)
{
return new Post
{
Id = item.Id,
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn,
Status = item.Status
};
}
/// <summary>
/// Maps a PostEditModel into a specific Post
/// </summary>
/// <param name="item"></param>
/// <param name="post"></param>
/// <returns></returns>
public static Post MapToModel(this PostEditModel item, Post post)
{
post.Id = item.Id;
post.VanityId = item.VanityId;
post.Title = item.Title;
post.Slug = item.Slug;
post.Description = item.Description;
post.DocumentContent = item.DocumentContent;
post.HeaderImage = item.HeaderImage;
post.PublishedOn = item.PublishedOn;
post.Status = item.Status;
return post;
}
/// <summary>
/// Maps an IEnumerable<Post> into an IEnumerable<PostTableViewModel>
/// </summary>
/// <param name="posts"></param>
/// <returns></returns>
public static IEnumerable<PostTableViewModel> MapToTableViewModel(this IEnumerable<Post> posts)
{
var tableViewModel = new List<PostTableViewModel>();
foreach (var item in posts)
{
tableViewModel.Add(new PostTableViewModel
{
VanityId = item.VanityId,
Title = item.Title,
Description = item.Description,
Slug = item.Slug,
PublishedOn = item.PublishedOn.ToString(),
Status = item.Status,
Author = item.ApplicationUsers.MapToViewModelSimple().Single()
});
}
return tableViewModel;
}
/// <summary>
/// Maps Post model into a PostViewModel
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static PostViewModel MapToViewModel(this Post item)
{
return new PostViewModel
{
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn.ToShortDateString(),
Categories = item.Categories.MapToViewModelSimple(),
Author = item.ApplicationUsers.MapToViewModelSimple().Single()
};
}
/// <summary>
/// Maps Post model into a PostViewModel
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static IEnumerable<PostViewModel> MapToViewModel(this IEnumerable<Post> posts)
{
var viewModels = new List<PostViewModel>();
foreach (var item in posts)
{
viewModels.Add(new PostViewModel
{
Id = item.Id,
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn.ToShortDateString(),
Status = item.Status
});
}
return viewModels;
}
/// <summary>
/// Maps Post model into a PostViewModel with Categories
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static IEnumerable<PostViewModel> MapToViewModelWithCategories(this IEnumerable<Post> posts)
{
var viewModels = new List<PostViewModel>();
foreach (var item in posts)
{
viewModels.Add(new PostViewModel
{
Id = item.Id,
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn.ToShortDateString(),
Status = item.Status,
Categories = item.PostCategories.Select(x => x.Category).MapToViewModel()
});
}
return viewModels;
}
/// <summary>
/// Maps Post model into a PostViewModel with Tags
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static IEnumerable<PostViewModel> MapToViewModelWithTags(this IEnumerable<Post> posts)
{
var viewModels = new List<PostViewModel>();
foreach (var item in posts)
{
viewModels.Add(new PostViewModel
{
Id = item.Id,
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
DocumentContent = item.DocumentContent,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn.ToShortDateString(),
Status = item.Status,
Tags = item.PostTags.Select(x => x.Tag).MapToViewModel()
});
}
return viewModels;
}
/// <summary>
/// Maps limited information for Partial Views
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static IEnumerable<PostViewModel> MapToViewModelForPartialView(this IEnumerable<Post> posts)
{
var viewModels = new List<PostViewModel>();
foreach (var item in posts)
{
viewModels.Add(new PostViewModel
{
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn.ToShortDateString(),
Categories = item.Categories.MapToViewModelSimple(),
Author = item.ApplicationUsers.MapToViewModelSimple().Single()
});
}
return viewModels;
}
/// <summary>
/// Maps limited information for Partial Views for Tags
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public static IEnumerable<PostViewModel> MapToViewModelForPartialViewForTags(this IEnumerable<Post> posts)
{
var viewModels = new List<PostViewModel>();
foreach (var item in posts)
{
viewModels.Add(new PostViewModel
{
VanityId = item.VanityId,
Title = item.Title,
Slug = item.Slug,
Description = item.Description,
HeaderImage = item.HeaderImage,
PublishedOn = item.PublishedOn.ToShortDateString(),
Categories = item.Categories.MapToViewModelSimple(),
Tags = item.Tags.MapToViewModelSimple(),
Author = item.ApplicationUsers.MapToViewModelSimple().Single()
});
}
return viewModels;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test
{
/// <summary>
/// public so that the tests can also be called by other exe/wrappers eg VSTS test harness.
/// </summary>
public static class PlinqDelegateExceptions
{
/// <summary>
/// A basic test for a query that throws user delegate exceptions
/// </summary>
/// <returns></returns>
[Fact]
public static void DistintOrderBySelect()
{
Exception caughtAggregateException = null;
try
{
var query2 = new int[] { 1, 2, 3 }.AsParallel()
.Distinct()
.OrderBy(i => i)
.Select(i => UserDelegateException.Throw<int, int>(i));
foreach (var x in query2)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
}
/// <summary>
/// Another basic test for a query that throws user delegate exceptions
/// </summary>
/// <returns></returns>
[Fact]
public static void SelectJoin()
{
Exception caughtAggregateException = null;
try
{
var query = new int[] { 1, 2, 3 }.AsParallel()
.Select(i => UserDelegateException.Throw<int, int>(i))
.Join(new int[] { 1 }.AsParallel(), i => i, j => j, (i, j) => 0);
foreach (var x in query)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
}
[Fact]
[OuterLoop]
public static void OrderBy()
{
// the orderby was a particular problem for the June 2008 CTP.
OrderByCore(10);
OrderByCore(100);
OrderByCore(1000);
}
/// <summary>
/// Heavily exercises OrderBy in the face of user-delegate exceptions.
/// On CTP-M1, this would deadlock for DOP=7,9,11,... on 4-core, but works for DOP=1..6 and 8,10,12, ...
///
/// In this test, every call to the key-selector delegate throws.
/// </summary>
private static void OrderByCore(int range)
{
for (int dop = 1; dop <= 30; dop++)
{
AggregateException caughtAggregateException = null;
try
{
var query = Enumerable.Range(0, range)
.AsParallel().WithDegreeOfParallelism(dop)
.OrderBy(i => UserDelegateException.Throw<int, int>(i));
foreach (int i in query)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
}
}
[Fact]
[OuterLoop]
public static void OrderBy_OnlyOneException()
{
// and try situations where only one user delegate exception occurs
OrderBy_OnlyOneExceptionCore(10);
OrderBy_OnlyOneExceptionCore(100);
OrderBy_OnlyOneExceptionCore(1000);
}
/// <summary>
/// Heavily exercises OrderBy, but only throws one user delegate exception to simulate an occasional failure.
/// </summary>
private static void OrderBy_OnlyOneExceptionCore(int range)
{
for (int dop = 1; dop <= 30; dop++)
{
int indexForException = range / (2 * dop); // eg 1000 items on 4-core, throws on item 125.
AggregateException caughtAggregateException = null;
try
{
var query = Enumerable.Range(0, range)
.AsParallel().WithDegreeOfParallelism(dop)
.OrderBy(i =>
{
UserDelegateException.ThrowIf(i == indexForException);
return i;
}
);
foreach (int i in query)
{
}
}
catch (AggregateException e)
{
caughtAggregateException = e;
}
Assert.NotNull(caughtAggregateException);
Assert.True(caughtAggregateException.InnerExceptions.Count == 1, string.Format("PLinqDelegateExceptions.OrderBy_OnlyOneException Range: {0}: AggregateException.InnerExceptions != 1.", range));
}
}
[Fact]
[OuterLoop]
public static void ZipAndOrdering()
{
// zip and ordering was also broken in June 2008 CTP, but this was due to the ordering component.
ZipAndOrderingCore(10);
ZipAndOrderingCore(100);
ZipAndOrderingCore(1000);
}
/// <summary>
/// Zip with ordering on showed issues, but it was due to the ordering component.
/// This is included as a regression test for that particular repro.
/// </summary>
private static void ZipAndOrderingCore(int range)
{
//Console.Write(" DOP: ");
for (int dop = 1; dop <= 30; dop++)
{
AggregateException ex = null;
try
{
var enum1 = Enumerable.Range(1, range);
var enum2 = Enumerable.Repeat(1, range * 2);
var query1 = enum1
.AsParallel()
.AsOrdered().WithDegreeOfParallelism(dop)
.Zip(enum2.AsParallel().AsOrdered(),
(a, b) => UserDelegateException.Throw<int, int, int>(a, b));
var output = query1.ToArray();
}
catch (AggregateException ae)
{
ex = ae;
}
Assert.NotNull(ex != null);
Assert.False(AggregateExceptionContains(ex, typeof(OperationCanceledException)), string.Format("PLinqDelegateExceptions.ZipAndOrdering Range: {0}: the wrong exception was inside the aggregate exception.", range));
Assert.True(AggregateExceptionContains(ex, typeof(UserDelegateException)), string.Format("PLinqDelegateExceptions.ZipAndOrdering Range: {0}: the wrong exception was inside the aggregate exception.", range));
}
}
/// <summary>
/// If the user delegate throws an OperationCanceledException, it should get aggregated.
/// </summary>
/// <returns></returns>
[Fact]
public static void OperationCanceledExceptionsGetAggregated()
{
AggregateException caughtAggregateException = null;
try
{
var enum1 = Enumerable.Range(1, 13);
var query1 =
enum1
.AsParallel()
.Select<int, int>(i => { throw new OperationCanceledException(); });
var output = query1.ToArray();
}
catch (AggregateException ae)
{
caughtAggregateException = ae;
}
Assert.NotNull(caughtAggregateException);
Assert.True(AggregateExceptionContains(caughtAggregateException, typeof(OperationCanceledException)),
"the wrong exception was inside the aggregate exception.");
}
/// <summary>
/// The plinq chunk partitioner calls takes an IEnumerator over the source, and disposes the enumerator when it is
/// finished.
/// If an exception occurs, the calling enumerator disposes the enumerator... but then other callers generate ODEs.
/// These ODEs either should not occur (prefered), or should not get into the aggregate exception.
///
/// Also applies to the standard stand-alone chunk partitioner.
/// Does not apply to other partitioners unless an exception in one consumer would cause flow-on exception in others.
/// </summary>
/// <returns></returns>
[Fact]
public static void PlinqChunkPartitioner_DontEnumerateAfterException()
{
try
{
Enumerable.Range(1, 10)
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Select(x => { if (x == 4) throw new ArgumentException("manual exception"); return x; })
.Zip(Enumerable.Range(1, 10).AsParallel(), (a, b) => a + b)
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.ToArray();
}
catch (AggregateException e)
{
if (!e.Flatten().InnerExceptions.All(ex => ex.GetType() == typeof(ArgumentException)))
{
StringBuilder builder = new StringBuilder();
foreach (var exception in e.Flatten().InnerExceptions)
{
builder.Append(" exception = " + exception);
}
Assert.True(false, string.Format("PlinqChunkPartitioner_DontEnumerateAfterException: FAIL. only a single ArgumentException should appear in the aggregate: {0}", builder.ToString()));
}
}
}
/// <summary>
/// The stand-alone chunk partitioner calls takes an IEnumerator over the source, and disposes the enumerator when it is
/// finished.
/// If an exception occurs, the calling enumerator disposes the enumerator... but then other callers generate ODEs.
/// These ODEs either should not occur (prefered), or should not get into the aggregate exception.
///
/// Also applies to the plinq stand-alone chunk partitioner.
/// Does not apply to other partitioners unless an exception in one consumer would cause flow-on exception in others.
/// </summary>
/// <returns></returns>
[Fact]
public static void ManualChunkPartitioner_DontEnumerateAfterException()
{
try
{
Partitioner.Create(
Enumerable.Range(1, 10)
.AsParallel()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Select(x => { if (x == 4) throw new ArgumentException("manual exception"); return x; })
.Zip(Enumerable.Range(1, 10).AsParallel(), (a, b) => a + b)
)
.AsParallel()
.ToArray();
}
catch (AggregateException e)
{
if (!e.Flatten().InnerExceptions.All(ex => ex.GetType() == typeof(ArgumentException)))
{
StringBuilder builder = new StringBuilder();
foreach (var exception in e.Flatten().InnerExceptions)
{
builder.Append(" exception = " + exception);
}
Assert.True(false, string.Format("ManualChunkPartitioner_DontEnumerateAfterException FAIL. only a single ArgumentException should appear in the aggregate: {0}", builder.ToString()));
}
}
}
[Fact]
public static void MoveNextAfterQueryOpeningFailsIsIllegal()
{
var query = Enumerable.Range(0, 10)
.AsParallel()
.Select<int, int>(x => { throw new ArgumentException(); })
.OrderBy(x => x);
IEnumerator<int> enumerator = query.GetEnumerator();
//moveNext will cause queryOpening to fail (no element generated)
Assert.Throws<AggregateException>(() => enumerator.MoveNext());
//moveNext after queryOpening failed
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
public static bool AggregateExceptionContains(AggregateException aggregateException, Type exceptionType)
{
foreach (Exception innerException in aggregateException.InnerExceptions)
{
if (innerException.GetType() == exceptionType)
{
return true;
}
}
return false;
}
/// <summary>
/// Exception for simulating exceptions from user delegates.
/// </summary>
public class UserDelegateException : Exception
{
public static TOut Throw<TIn, TOut>(TIn input)
{
throw new UserDelegateException();
}
public static TOut Throw<TIn1, TIn2, TOut>(TIn1 input1, TIn2 input2)
{
throw new UserDelegateException();
}
public static void ThrowIf(bool predicate)
{
if (predicate)
throw new UserDelegateException();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using MdToken = System.Reflection.MetadataToken;
namespace System.Reflection
{
internal unsafe sealed class RuntimeParameterInfo : ParameterInfo
{
#region Static Members
internal unsafe static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo dummy;
return GetParameters(method, member, sig, out dummy, false);
}
internal unsafe static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig)
{
Debug.Assert(method is RuntimeMethodInfo || method is RuntimeConstructorInfo);
ParameterInfo returnParameter;
GetParameters(method, member, sig, out returnParameter, true);
return returnParameter;
}
internal unsafe static ParameterInfo[] GetParameters(
IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter)
{
returnParameter = null;
int sigArgCount = sig.Arguments.Length;
ParameterInfo[] args = fetchReturnParameter ? null : new ParameterInfo[sigArgCount];
int tkMethodDef = RuntimeMethodHandle.GetMethodDef(methodHandle);
int cParamDefs = 0;
// Not all methods have tokens. Arrays, pointers and byRef types do not have tokens as they
// are generated on the fly by the runtime.
if (!MdToken.IsNullToken(tkMethodDef))
{
MetadataImport scope = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle));
MetadataEnumResult tkParamDefs;
scope.EnumParams(tkMethodDef, out tkParamDefs);
cParamDefs = tkParamDefs.Length;
// Not all parameters have tokens. Parameters may have no token
// if they have no name and no attributes.
if (cParamDefs > sigArgCount + 1 /* return type */)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
for (int i = 0; i < cParamDefs; i++)
{
#region Populate ParameterInfos
ParameterAttributes attr;
int position, tkParamDef = tkParamDefs[i];
scope.GetParamDefProps(tkParamDef, out position, out attr);
position--;
if (fetchReturnParameter == true && position == -1)
{
// more than one return parameter?
if (returnParameter != null)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
returnParameter = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member);
}
else if (fetchReturnParameter == false && position >= 0)
{
// position beyong sigArgCount?
if (position >= sigArgCount)
throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
args[position] = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member);
}
#endregion
}
}
// Fill in empty ParameterInfos for those without tokens
if (fetchReturnParameter)
{
if (returnParameter == null)
{
returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, (ParameterAttributes)0, member);
}
}
else
{
if (cParamDefs < args.Length + 1)
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] != null)
continue;
args[i] = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, i, (ParameterAttributes)0, member);
}
}
}
return args;
}
#endregion
#region Private Statics
private static readonly Type s_DecimalConstantAttributeType = typeof(DecimalConstantAttribute);
private static readonly Type s_CustomConstantAttributeType = typeof(CustomConstantAttribute);
#endregion
#region Private Data Members
private int m_tkParamDef;
private MetadataImport m_scope;
private Signature m_signature;
private volatile bool m_nameIsCached = false;
private readonly bool m_noMetadata = false;
private bool m_noDefaultValue = false;
private MethodBase m_originalMember = null;
#endregion
#region Internal Properties
internal MethodBase DefiningMethod
{
get
{
MethodBase result = m_originalMember != null ? m_originalMember : MemberImpl as MethodBase;
Debug.Assert(result != null);
return result;
}
}
#endregion
#region Internal Methods
internal void SetName(string name)
{
NameImpl = name;
}
internal void SetAttributes(ParameterAttributes attributes)
{
AttrsImpl = attributes;
}
#endregion
#region Constructor
// used by RuntimePropertyInfo
internal RuntimeParameterInfo(RuntimeParameterInfo accessor, RuntimePropertyInfo property)
: this(accessor, (MemberInfo)property)
{
m_signature = property.Signature;
}
private RuntimeParameterInfo(RuntimeParameterInfo accessor, MemberInfo member)
{
// Change ownership
MemberImpl = member;
// The original owner should always be a method, because this method is only used to
// change the owner from a method to a property.
m_originalMember = accessor.MemberImpl as MethodBase;
Debug.Assert(m_originalMember != null);
// Populate all the caches -- we inherit this behavior from RTM
NameImpl = accessor.Name;
m_nameIsCached = true;
ClassImpl = accessor.ParameterType;
PositionImpl = accessor.Position;
AttrsImpl = accessor.Attributes;
// Strictly speeking, property's don't contain paramter tokens
// However we need this to make ca's work... oh well...
m_tkParamDef = MdToken.IsNullToken(accessor.MetadataToken) ? (int)MetadataTokenType.ParamDef : accessor.MetadataToken;
m_scope = accessor.m_scope;
}
private RuntimeParameterInfo(
Signature signature, MetadataImport scope, int tkParamDef,
int position, ParameterAttributes attributes, MemberInfo member)
{
Debug.Assert(member != null);
Debug.Assert(MdToken.IsNullToken(tkParamDef) == scope.Equals(MetadataImport.EmptyImport));
Debug.Assert(MdToken.IsNullToken(tkParamDef) || MdToken.IsTokenOfType(tkParamDef, MetadataTokenType.ParamDef));
PositionImpl = position;
MemberImpl = member;
m_signature = signature;
m_tkParamDef = MdToken.IsNullToken(tkParamDef) ? (int)MetadataTokenType.ParamDef : tkParamDef;
m_scope = scope;
AttrsImpl = attributes;
ClassImpl = null;
NameImpl = null;
}
// ctor for no metadata MethodInfo in the DynamicMethod and RuntimeMethodInfo cases
internal RuntimeParameterInfo(MethodInfo owner, String name, Type parameterType, int position)
{
MemberImpl = owner;
NameImpl = name;
m_nameIsCached = true;
m_noMetadata = true;
ClassImpl = parameterType;
PositionImpl = position;
AttrsImpl = ParameterAttributes.None;
m_tkParamDef = (int)MetadataTokenType.ParamDef;
m_scope = MetadataImport.EmptyImport;
}
#endregion
#region Public Methods
public override Type ParameterType
{
get
{
// only instance of ParameterInfo has ClassImpl, all its subclasses don't
if (ClassImpl == null)
{
RuntimeType parameterType;
if (PositionImpl == -1)
parameterType = m_signature.ReturnType;
else
parameterType = m_signature.Arguments[PositionImpl];
Debug.Assert(parameterType != null);
// different thread could only write ClassImpl to the same value, so a race condition is not a problem here
ClassImpl = parameterType;
}
return ClassImpl;
}
}
public override String Name
{
get
{
if (!m_nameIsCached)
{
if (!MdToken.IsNullToken(m_tkParamDef))
{
string name;
name = m_scope.GetName(m_tkParamDef).ToString();
NameImpl = name;
}
// other threads could only write it to true, so a race condition is OK
// this field is volatile, so the write ordering is guaranteed
m_nameIsCached = true;
}
// name may be null
return NameImpl;
}
}
public override bool HasDefaultValue
{
get
{
if (m_noMetadata || m_noDefaultValue)
return false;
object defaultValue = GetDefaultValueInternal(false);
return (defaultValue != DBNull.Value);
}
}
public override Object DefaultValue { get { return GetDefaultValue(false); } }
public override Object RawDefaultValue { get { return GetDefaultValue(true); } }
private Object GetDefaultValue(bool raw)
{
// OLD COMMENT (Is this even true?)
// Cannot cache because default value could be non-agile user defined enumeration.
// OLD COMMENT ends
if (m_noMetadata)
return null;
// for dynamic method we pretend to have cached the value so we do not go to metadata
object defaultValue = GetDefaultValueInternal(raw);
if (defaultValue == DBNull.Value)
{
#region Handle case if no default value was found
if (IsOptional)
{
// If the argument is marked as optional then the default value is Missing.Value.
defaultValue = Type.Missing;
}
#endregion
}
return defaultValue;
}
// returns DBNull.Value if the parameter doesn't have a default value
private Object GetDefaultValueInternal(bool raw)
{
Debug.Assert(!m_noMetadata);
if (m_noDefaultValue)
return DBNull.Value;
object defaultValue = null;
// Why check the parameter type only for DateTime and only for the ctor arguments?
// No check on the parameter type is done for named args and for Decimal.
// We should move this after MdToken.IsNullToken(m_tkParamDef) and combine it
// with the other custom attribute logic. But will that be a breaking change?
// For a DateTime parameter on which both an md constant and a ca constant are set,
// which one should win?
if (ParameterType == typeof(DateTime))
{
if (raw)
{
CustomAttributeTypedArgument value =
CustomAttributeData.Filter(
CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0);
if (value.ArgumentType != null)
return new DateTime((long)value.Value);
}
else
{
object[] dt = GetCustomAttributes(typeof(DateTimeConstantAttribute), false);
if (dt != null && dt.Length != 0)
return ((DateTimeConstantAttribute)dt[0]).Value;
}
}
#region Look for a default value in metadata
if (!MdToken.IsNullToken(m_tkParamDef))
{
// This will return DBNull.Value if no constant value is defined on m_tkParamDef in the metadata.
defaultValue = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw);
}
#endregion
if (defaultValue == DBNull.Value)
{
#region Look for a default value in the custom attributes
if (raw)
{
foreach (CustomAttributeData attr in CustomAttributeData.GetCustomAttributes(this))
{
Type attrType = attr.Constructor.DeclaringType;
if (attrType == typeof(DateTimeConstantAttribute))
{
defaultValue = GetRawDateTimeConstant(attr);
}
else if (attrType == typeof(DecimalConstantAttribute))
{
defaultValue = GetRawDecimalConstant(attr);
}
else if (attrType.IsSubclassOf(s_CustomConstantAttributeType))
{
defaultValue = GetRawConstant(attr);
}
}
}
else
{
Object[] CustomAttrs = GetCustomAttributes(s_CustomConstantAttributeType, false);
if (CustomAttrs.Length != 0)
{
defaultValue = ((CustomConstantAttribute)CustomAttrs[0]).Value;
}
else
{
CustomAttrs = GetCustomAttributes(s_DecimalConstantAttributeType, false);
if (CustomAttrs.Length != 0)
{
defaultValue = ((DecimalConstantAttribute)CustomAttrs[0]).Value;
}
}
}
#endregion
}
if (defaultValue == DBNull.Value)
m_noDefaultValue = true;
return defaultValue;
}
private static Decimal GetRawDecimalConstant(CustomAttributeData attr)
{
Debug.Assert(attr.Constructor.DeclaringType == typeof(DecimalConstantAttribute));
foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
{
if (namedArgument.MemberInfo.Name.Equals("Value"))
{
// This is not possible because Decimal cannot be represented directly in the metadata.
Debug.Fail("Decimal cannot be represented directly in the metadata.");
return (Decimal)namedArgument.TypedValue.Value;
}
}
ParameterInfo[] parameters = attr.Constructor.GetParameters();
Debug.Assert(parameters.Length == 5);
System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
Debug.Assert(args.Count == 5);
if (parameters[2].ParameterType == typeof(uint))
{
// DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low)
int low = (int)(UInt32)args[4].Value;
int mid = (int)(UInt32)args[3].Value;
int hi = (int)(UInt32)args[2].Value;
byte sign = (byte)args[1].Value;
byte scale = (byte)args[0].Value;
return new System.Decimal(low, mid, hi, (sign != 0), scale);
}
else
{
// DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low)
int low = (int)args[4].Value;
int mid = (int)args[3].Value;
int hi = (int)args[2].Value;
byte sign = (byte)args[1].Value;
byte scale = (byte)args[0].Value;
return new System.Decimal(low, mid, hi, (sign != 0), scale);
}
}
private static DateTime GetRawDateTimeConstant(CustomAttributeData attr)
{
Debug.Assert(attr.Constructor.DeclaringType == typeof(DateTimeConstantAttribute));
Debug.Assert(attr.ConstructorArguments.Count == 1);
foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
{
if (namedArgument.MemberInfo.Name.Equals("Value"))
{
return new DateTime((long)namedArgument.TypedValue.Value);
}
}
// Look at the ctor argument if the "Value" property was not explicitly defined.
return new DateTime((long)attr.ConstructorArguments[0].Value);
}
private static object GetRawConstant(CustomAttributeData attr)
{
foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
{
if (namedArgument.MemberInfo.Name.Equals("Value"))
return namedArgument.TypedValue.Value;
}
// Return DBNull to indicate that no default value is available.
// Not to be confused with a null return which indicates a null default value.
return DBNull.Value;
}
internal RuntimeModule GetRuntimeModule()
{
RuntimeMethodInfo method = Member as RuntimeMethodInfo;
RuntimeConstructorInfo constructor = Member as RuntimeConstructorInfo;
RuntimePropertyInfo property = Member as RuntimePropertyInfo;
if (method != null)
return method.GetRuntimeModule();
else if (constructor != null)
return constructor.GetRuntimeModule();
else if (property != null)
return property.GetRuntimeModule();
else
return null;
}
public override int MetadataToken
{
get
{
return m_tkParamDef;
}
}
public override Type[] GetRequiredCustomModifiers()
{
return m_signature.GetCustomModifiers(PositionImpl + 1, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return m_signature.GetCustomModifiers(PositionImpl + 1, false);
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<Object>();
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (MdToken.IsNullToken(m_tkParamDef))
return Array.Empty<Object>();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (MdToken.IsNullToken(m_tkParamDef))
return false;
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
}
}
| |
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen
//Copyright 2006-2011 Jeroen van Menen
//
// 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 Copyright
using System;
using System.Diagnostics;
using System.IO;
using Microsoft.Win32;
using WatiN.Core.Logging;
using WatiN.Core.Native.Mozilla;
using WatiN.Core.Native;
using WatiN.Core.UtilityClasses;
// https://developer.mozilla.org/en/Gecko_DOM_Reference
namespace WatiN.Core
{
public class FireFox : Browser
{
public static string IpAdress = FireFoxClientPort.LOCAL_IP_ADRESS;
public static int Port = FireFoxClientPort.DEFAULT_PORT;
private FFBrowser _ffBrowser;
#region Public constructors / destructor
/// <summary>
/// Initializes a new instance of the <see cref="FireFox"/> class.
/// </summary>
public FireFox() : this ("about:blank") {}
/// <summary>
/// Initializes a new instance of the <see cref="FireFox"/> class.
/// </summary>
/// <param name="url">The url to go to</param>
public FireFox(string url) : this(UtilityClass.CreateUri(url)) {}
/// <summary>
/// Initializes a new instance of the <see cref="FireFox"/> class.
/// </summary>
/// <param name="uri">The url to go to</param>
public FireFox(Uri uri)
{
CreateFireFoxInstance(uri.AbsoluteUri);
}
public FireFox(FFBrowser ffBrowser)
{
_ffBrowser = ffBrowser;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="FireFox"/> is reclaimed by garbage collection.
/// </summary>
~FireFox()
{
Dispose(false);
}
#endregion
#region Public instance properties
public override INativeBrowser NativeBrowser
{
get { return _ffBrowser; }
}
#endregion Public instance properties
#region Public instance methods
/// <summary>
/// Gets the current FireFox process (all instances run under 1 process).
/// </summary>
/// <value>The current FireFox process or null if none is found.</value>
internal static Process CurrentProcess
{
get
{
foreach (var process in Process.GetProcesses())
{
if (process.ProcessName.Equals("firefox", StringComparison.OrdinalIgnoreCase))
{
return process;
}
}
return null;
}
}
private static string pathToExe;
/// <summary>
/// Gets or sets the path to FireFox executable. By default the registry and common
/// file locations will be used to find the the firefox executable.
/// When manually setting this property make sure to also include the path and name
/// of the executable (c:\somedirectory\firefox.exe)
/// </summary>
/// <value>The path to exe.</value>
public static string PathToExe
{
get
{
if (pathToExe == null)
{
pathToExe = GetExecutablePath();
}
return pathToExe;
}
set { pathToExe = value; }
}
internal static void CreateProcess(string arguments, bool waitForMainWindow)
{
var ffProcess = new Process {StartInfo = {FileName = PathToExe, Arguments = arguments}};
ffProcess.Start();
ffProcess.WaitForInputIdle(5000);
ffProcess.Refresh();
if (!waitForMainWindow) return;
var action = new TryFuncUntilTimeOut(TimeSpan.FromSeconds(Settings.WaitForCompleteTimeOut))
{
SleepTime = TimeSpan.FromMilliseconds(200)
};
var result = action.Try(() =>
{
ffProcess.Refresh();
if (!ffProcess.HasExited && ffProcess.MainWindowHandle != IntPtr.Zero)
{
Logger.LogAction("Waited for FireFox, main window handle found.");
return true;
}
return false;
});
if (!result)
{
Debug.WriteLine("Timer elapsed waiting for FireFox to start.");
}
}
/// <summary>
/// Initalizes the executable path.
/// </summary>
private static string GetExecutablePath()
{
string path;
var mozillaKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Mozilla\Mozilla Firefox");
if (mozillaKey != null)
{
path = GetExecutablePathUsingRegistry(mozillaKey);
}
else
{
// We try and guess common locations where FireFox might be installed
var tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Mozilla FireFox\FireFox.exe");
if (File.Exists(tempPath))
{
path = tempPath;
}
else
{
tempPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + " (x86)", @"Mozilla FireFox\FireFox.exe");
if (File.Exists(tempPath))
{
path = tempPath;
}
else
{
throw new FireFoxException("Unable to determine the current version of FireFox tried looking in the registry and the common locations on disk, please make sure you have installed FireFox and Jssh correctly");
}
}
}
return path;
}
/// <summary>
/// Initializes the executable path to FireFox using the registry.
/// </summary>
/// <param name="mozillaKey">The mozilla key.</param>
private static string GetExecutablePathUsingRegistry(RegistryKey mozillaKey)
{
var currentVersion = (string)mozillaKey.GetValue("CurrentVersion");
if (string.IsNullOrEmpty(currentVersion))
{
throw new FireFoxException("Unable to determine the current version of FireFox using the registry, please make sure you have installed FireFox and Jssh correctly");
}
var currentMain = mozillaKey.OpenSubKey(string.Format(@"{0}\Main", currentVersion));
if (currentMain == null)
{
throw new FireFoxException(
"Unable to determine the current version of FireFox using the registry, please make sure you have installed FireFox and Jssh correctly");
}
var path = (string)currentMain.GetValue("PathToExe");
if (!File.Exists(path))
{
throw new FireFoxException(
"FireFox executable listed in the registry does not exist, please make sure you have installed FireFox and Jssh correctly");
}
return path;
}
/// <summary>
/// Waits until the page is completely loaded
/// </summary>
public override void WaitForComplete(int waitForCompleteTimeOut)
{
WaitForComplete(new JSWaitForComplete(_ffBrowser, waitForCompleteTimeOut));
}
/// <summary>
/// Closes the browser.
/// </summary>
public override void Close()
{
_ffBrowser.Close();
}
#endregion Public instance methods
#region Protected instance methods
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (IsDisposed) return;
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
_ffBrowser.ClientPort.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
base.Dispose(disposing);
}
#endregion Protected instance methods
private void CreateFireFoxInstance(string url)
{
Logger.LogAction("Creating FireFox instance");
UtilityClass.MoveMousePoinerToTopLeft(Settings.AutoMoveMousePointerToTopLeft);
var clientPort = GetClientPort();
clientPort.Connect(url);
_ffBrowser = new FFBrowser(clientPort);
FinishInitialization();
WaitForComplete();
}
internal static FireFoxClientPort GetClientPort()
{
return new FireFoxClientPort(IpAdress, Port);
}
}
}
| |
//
// System.Xml.XmlTextWriterTests
//
// Authors:
// Kral Ferch <kral_ferch@hotmail.com>
// Martin Willemoes Hansen <mwh@sysrq.dk>
//
// (C) 2002 Kral Ferch
// (C) 2003 Martin Willemoes Hansen
//
using System;
using System.Xml;
using System.Collections;
using NUnit.Framework;
namespace MonoTests.System.Xml
{
[TestFixture]
public class XmlNodeListTests
{
XmlDocument document;
XmlElement documentElement;
XmlElement element;
XmlNode node;
Object obj;
IEnumerator enumerator;
int index;
[SetUp]
public void GetReady ()
{
document = new XmlDocument ();
}
[Test]
public void NodeTypesThatCantHaveChildren ()
{
document.LoadXml ("<foo>bar</foo>");
documentElement = document.DocumentElement;
node = documentElement.FirstChild;
Assert.AreEqual (node.NodeType, XmlNodeType.Text, "Expected a text node.");
Assert.AreEqual (node.HasChildNodes, false, "Shouldn't have children.");
Assert.AreEqual (node.ChildNodes.Count, 0, "Should be empty node list.");
Assert.AreEqual (node.GetEnumerator().MoveNext(), false, "Should be empty node list.");
}
[Test]
public void ZeroChildren ()
{
document.LoadXml ("<foo/>");
documentElement = document.DocumentElement;
Assert.AreEqual (documentElement.GetEnumerator().MoveNext(), false, "Should be empty node list.");
}
[Test]
public void OneChild ()
{
document.LoadXml ("<foo><child1/></foo>");
documentElement = document.DocumentElement;
Assert.AreEqual (documentElement.ChildNodes.Count, 1, "Incorrect number of children returned from Count property.");
index = 1;
foreach (XmlNode childNode in documentElement.ChildNodes)
{
Assert.AreEqual ("child" + index.ToString(), childNode.LocalName, "Enumerator didn't return correct node.");
index++;
}
Assert.AreEqual (index, 2, "foreach didn't loop over all children correctly.");
}
[Test]
public void MultipleChildren ()
{
document.LoadXml ("<foo><child1/><child2/><child3/></foo>");
element = document.DocumentElement;
Assert.AreEqual (element.ChildNodes.Count, 3, "Incorrect number of children returned from Count property.");
Assert.IsNull (element.ChildNodes [-1], "Index less than zero should have returned null.");
Assert.IsNull (element.ChildNodes [3], "Index greater than or equal to Count should have returned null.");
Assert.AreEqual (element.FirstChild, element.ChildNodes[0], "Didn't return the correct child.");
Assert.AreEqual ("child1", element.ChildNodes[0].LocalName, "Didn't return the correct child.");
Assert.AreEqual ("child2", element.ChildNodes[1].LocalName, "Didn't return the correct child.");
Assert.AreEqual ("child3", element.ChildNodes[2].LocalName, "Didn't return the correct child.");
index = 1;
foreach (XmlNode childNode in element.ChildNodes)
{
Assert.AreEqual ("child" + index.ToString(), childNode.LocalName, "Enumerator didn't return correct node.");
index++;
}
Assert.AreEqual (index, 4, "foreach didn't loop over all children correctly.");
}
[Test]
public void AppendChildAffectOnEnumeration ()
{
document.LoadXml ("<foo><child1/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
Assert.AreEqual (enumerator.MoveNext(), true, "MoveNext should have succeeded.");
Assert.AreEqual (enumerator.MoveNext(), false, "MoveNext should have failed.");
enumerator.Reset();
Assert.AreEqual (enumerator.MoveNext(), true, "MoveNext should have succeeded.");
element.AppendChild(document.CreateElement("child2"));
Assert.AreEqual (enumerator.MoveNext(), true, "MoveNext should have succeeded.");
Assert.AreEqual (enumerator.MoveNext(), false, "MoveNext should have failed.");
}
[Test]
public void RemoveChildAffectOnEnumeration ()
{
document.LoadXml ("<foo><child1/><child2/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
element.RemoveChild(element.FirstChild);
enumerator.MoveNext();
Assert.AreEqual (((XmlElement)enumerator.Current).LocalName, "child2", "Expected child2 element.");
}
[Test]
public void RemoveChildAffectOnEnumerationWhenEnumeratorIsOnRemovedChild ()
{
document.LoadXml ("<foo><child1/><child2/><child3/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator ();
enumerator.MoveNext ();
enumerator.MoveNext ();
Assert.AreEqual ("child2", ((XmlElement)enumerator.Current).LocalName, "Expected child2 element.");
Assert.AreEqual ("child2", element.FirstChild.NextSibling.LocalName, "Expected child2 element.");
element.RemoveChild (element.FirstChild.NextSibling);
enumerator.MoveNext ();
try {
element = (XmlElement) enumerator.Current;
Assert.Fail ("Expected an InvalidOperationException.");
} catch (InvalidOperationException) { }
}
// TODO: Take the word save off front of this method when XmlNode.ReplaceChild() is implemented.
public void saveTestReplaceChildAffectOnEnumeration ()
{
document.LoadXml ("<foo><child1/><child2/></foo>");
element = document.DocumentElement;
node = document.CreateElement("child3");
enumerator = element.GetEnumerator();
Assert.AreEqual (enumerator.MoveNext(), true, "MoveNext should have succeeded.");
element.ReplaceChild(node, element.LastChild);
enumerator.MoveNext();
Assert.AreEqual (((XmlElement)enumerator.Current).LocalName, "child3", "Expected child3 element.");
Assert.AreEqual (enumerator.MoveNext(), false, "MoveNext should have failed.");
}
[Test]
public void RemoveOnlyChildAffectOnEnumeration ()
{
document.LoadXml ("<foo><child1/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
element.RemoveChild(element.FirstChild);
Assert.AreEqual (enumerator.MoveNext(), false, "MoveNext should have failed.");
}
// TODO: Take the word save off front of this method when XmlNode.RemoveAll() is fully implemented.
public void saveTestRemoveAllAffectOnEnumeration ()
{
document.LoadXml ("<foo><child1/><child2/><child3/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
Assert.AreEqual (element.ChildNodes.Count, 3, "Expected 3 children.");
Assert.AreEqual (enumerator.MoveNext(), true, "MoveNext should have succeeded.");
element.RemoveAll();
Assert.AreEqual (enumerator.MoveNext(), false, "MoveNext should have failed.");
}
[Test]
public void CurrentBeforeFirstNode ()
{
document.LoadXml ("<foo><child1/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
try
{
obj = enumerator.Current;
Assert.Fail ("Calling Current property before first node in list should have thrown InvalidOperationException.");
} catch (InvalidOperationException) { }
}
[Test]
public void CurrentAfterLastNode ()
{
document.LoadXml ("<foo><child1/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
enumerator.MoveNext();
enumerator.MoveNext();
try
{
obj = enumerator.Current;
Assert.Fail ("Calling Current property after last node in list should have thrown InvalidOperationException.");
}
catch (InvalidOperationException) { }
}
[Test]
public void CurrentDoesntMove ()
{
document.LoadXml ("<foo><child1/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
enumerator.MoveNext();
Assert.AreEqual (Object.ReferenceEquals(enumerator.Current, enumerator.Current), true, "Consecutive calls to Current property should yield same reference.");
}
[Test]
public void Reset ()
{
document.LoadXml ("<foo><child1/><child2/></foo>");
element = document.DocumentElement;
enumerator = element.GetEnumerator();
enumerator.MoveNext();
enumerator.MoveNext();
Assert.AreEqual (((XmlElement)enumerator.Current).LocalName, "child2", "Expected child2.");
enumerator.Reset();
enumerator.MoveNext();
Assert.AreEqual (((XmlElement)enumerator.Current).LocalName, "child1", "Expected child1.");
}
[Test]
public void ReturnNullWhenIndexIsOutOfRange ()
{
document.LoadXml ("<root><foo/></root>");
XmlNodeList nl = document.DocumentElement.GetElementsByTagName ("bar");
Assert.AreEqual (0, nl.Count, "empty list. count");
try {
Assert.IsNull (nl [0], "index 0");
Assert.IsNull (nl [1], "index 1");
Assert.IsNull (nl [-1], "index -1");
} catch (ArgumentOutOfRangeException) {
Assert.Fail ("don't throw index out of range.");
}
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace ExampleMod.NPCs.Abomination
{
//ported from my tAPI mod because I'm lazy
public class CaptiveElement : ModNPC
{
private int center
{
get
{
return (int)npc.ai[0];
}
set
{
npc.ai[0] = value;
}
}
private int captiveType
{
get
{
return (int)npc.ai[1];
}
set
{
npc.ai[1] = value;
}
}
private float attackCool
{
get
{
return npc.ai[2];
}
set
{
npc.ai[2] = value;
}
}
private int change
{
get
{
return (int)npc.ai[3];
}
set
{
npc.ai[3] = value;
}
}
public override void SetDefaults()
{
npc.name = "Captive Element";
npc.displayName = "Captive Element";
npc.aiStyle = -1;
npc.lifeMax = 15000;
npc.damage = 100;
npc.defense = 55;
npc.knockBackResist = 0f;
npc.dontTakeDamage = true;
npc.width = 100;
npc.height = 100;
Main.npcFrameCount[npc.type] = 10;
npc.value = Item.buyPrice(0, 20, 0, 0);
npc.npcSlots = 10f;
npc.boss = true;
npc.lavaImmune = true;
npc.noGravity = true;
npc.noTileCollide = true;
npc.HitSound = SoundID.NPCHit1;
npc.DeathSound = SoundID.NPCDeath1;
music = MusicID.Boss2;
}
public override void ScaleExpertStats(int numPlayers, float bossLifeScale)
{
npc.lifeMax = (int)(npc.lifeMax * 0.6f * bossLifeScale);
npc.damage = (int)(npc.damage * 0.6f);
}
public override void AI()
{
NPC abomination = Main.npc[center];
if (!abomination.active || abomination.type != mod.NPCType("Abomination"))
{
if (change > 0 || NPC.AnyNPCs(mod.NPCType("AbominationRun")))
{
if (change == 0)
{
npc.netUpdate = true;
}
change++;
}
else
{
npc.life = -1;
npc.active = false;
return;
}
}
if (change > 0)
{
Color? color = GetColor();
if (color.HasValue)
{
for (int x = 0; x < 5; x++)
{
int dust = Dust.NewDust(npc.position, npc.width, npc.height, mod.DustType("Pixel"), 0f, 0f, 0, color.Value);
double angle = Main.rand.NextDouble() * 2.0 * Math.PI;
Main.dust[dust].velocity = 3f * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}
}
if (Main.netMode != 1 && change >= 100f)
{
int next = NPC.NewNPC((int)npc.Center.X, (int)npc.position.Y + npc.height, mod.NPCType("CaptiveElement2"));
Main.npc[next].ai[0] = captiveType;
if (captiveType != 4)
{
Main.npc[next].ai[1] = 300f + (float)Main.rand.Next(100);
}
npc.life = -1;
npc.active = false;
}
return;
}
else if (npc.timeLeft < 750)
{
npc.timeLeft = 750;
}
if (npc.localAI[0] == 0f)
{
if (GetDebuff() >= 0f)
{
npc.buffImmune[GetDebuff()] = true;
}
if (captiveType == 3f)
{
npc.buffImmune[20] = true;
}
if (captiveType == 0f)
{
npc.coldDamage = true;
}
npc.localAI[0] = 1f;
}
SetPosition(npc);
attackCool -= 1f;
if (Main.netMode != 1 && attackCool <= 0f)
{
attackCool = 200f + 200f * (float)abomination.life / (float)abomination.lifeMax + (float)Main.rand.Next(200);
Vector2 delta = Main.player[abomination.target].Center - npc.Center;
float magnitude = (float)Math.Sqrt(delta.X * delta.X + delta.Y * delta.Y);
if (magnitude > 0)
{
delta *= 5f / magnitude;
}
else
{
delta = new Vector2(0f, 5f);
}
int damage = (npc.damage - 30) / 2;
if (Main.expertMode)
{
damage = (int)(damage / Main.expertDamage);
}
Projectile.NewProjectile(npc.Center.X, npc.Center.Y, delta.X, delta.Y, mod.ProjectileType("ElementBall"), damage, 3f, Main.myPlayer, GetDebuff(), GetDebuffTime());
npc.netUpdate = true;
}
}
public static void SetPosition(NPC npc)
{
CaptiveElement modNPC = npc.modNPC as CaptiveElement;
if (modNPC != null)
{
Vector2 center = Main.npc[modNPC.center].Center;
double angle = Main.npc[modNPC.center].ai[3] + 2.0 * Math.PI * modNPC.captiveType / 5.0;
npc.position = center + 300f * (new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle))) - npc.Size / 2f;
}
}
public override void FindFrame(int frameHeight)
{
npc.frame.Y = captiveType * frameHeight;
if (captiveType == 1)
{
npc.alpha = 100;
}
if (attackCool < 50f)
{
npc.frame.Y += 5 * frameHeight;
}
}
public override bool CanHitPlayer(Player target, ref int cooldownSlot)
{
if (captiveType == 2 && Main.expertMode)
{
cooldownSlot = 1;
}
return true;
}
public override void OnHitPlayer(Player player, int dmgDealt, bool crit)
{
if (Main.expertMode || Main.rand.Next(2) == 0)
{
int debuff = GetDebuff();
if (debuff >= 0)
{
player.AddBuff(debuff, GetDebuffTime(), true);
}
}
}
public int GetDebuff()
{
switch (captiveType)
{
case 0:
return BuffID.Frostburn;
case 1:
return mod.BuffType("EtherealFlames");
case 3:
return BuffID.Venom;
case 4:
return BuffID.Ichor;
default:
return -1;
}
}
public int GetDebuffTime()
{
int time;
switch (captiveType)
{
case 0:
time = 400;
break;
case 1:
time = 300;
break;
case 3:
time = 400;
break;
case 4:
time = 900;
break;
default:
return -1;
}
return time;
}
public Color? GetColor()
{
switch (captiveType)
{
case 0:
return new Color(0, 230, 230);
case 1:
return new Color(0, 153, 230);
case 3:
return new Color(0, 178, 0);
case 4:
return new Color(230, 192, 0);
default:
return null;
}
}
public override void BossHeadSlot(ref int index)
{
if (captiveType > 0)
{
index = NPCHeadLoader.GetBossHeadSlot(ExampleMod.captiveElementHead + captiveType);
}
}
public override bool PreDraw(SpriteBatch spriteBatch, Color drawColor)
{
Abomination abomination = Main.npc[center].modNPC as Abomination;
if (Main.expertMode && abomination != null && abomination.npc.active && abomination.laserTimer <= 60 && (abomination.laser1 == captiveType || abomination.laser2 == captiveType))
{
Color? color = GetColor();
if (!color.HasValue)
{
color = Color.White;
}
float rotation = abomination.laserTimer / 30f;
if (abomination.laser1 == captiveType)
{
rotation *= -1f;
}
spriteBatch.Draw(ModLoader.GetTexture("ExampleMod/NPCs/Abomination/Rune"), npc.Center - Main.screenPosition, null, color.Value, rotation, new Vector2(64, 64), 1f, SpriteEffects.None, 0f);
}
return true;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using log4net;
using Nini.Config;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
namespace OpenSim.Framework.Monitoring
{
public class ServerStatsCollector
{
private readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private readonly string LogHeader = "[SERVER STATS]";
public bool Enabled = false;
private static Dictionary<string, Stat> RegisteredStats = new Dictionary<string, Stat>();
public readonly string CategoryServer = "server";
public readonly string ContainerThreadpool = "threadpool";
public readonly string ContainerProcessor = "processor";
public readonly string ContainerMemory = "memory";
public readonly string ContainerNetwork = "network";
public readonly string ContainerProcess = "process";
public string NetworkInterfaceTypes = "Ethernet";
readonly int performanceCounterSampleInterval = 500;
// int lastperformanceCounterSampleTime = 0;
private class PerfCounterControl
{
public PerformanceCounter perfCounter;
public int lastFetch;
public string name;
public PerfCounterControl(PerformanceCounter pPc)
: this(pPc, String.Empty)
{
}
public PerfCounterControl(PerformanceCounter pPc, string pName)
{
perfCounter = pPc;
lastFetch = 0;
name = pName;
}
}
PerfCounterControl processorPercentPerfCounter = null;
// IRegionModuleBase.Initialize
public void Initialise(IConfigSource source)
{
if (source == null)
return;
IConfig cfg = source.Configs["Monitoring"];
if (cfg != null)
Enabled = cfg.GetBoolean("ServerStatsEnabled", true);
if (Enabled)
{
NetworkInterfaceTypes = cfg.GetString("NetworkInterfaceTypes", "Ethernet");
}
}
public void Start()
{
if (RegisteredStats.Count == 0)
RegisterServerStats();
}
public void Close()
{
if (RegisteredStats.Count > 0)
{
foreach (Stat stat in RegisteredStats.Values)
{
StatsManager.DeregisterStat(stat);
stat.Dispose();
}
RegisteredStats.Clear();
}
}
private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act)
{
MakeStat(pName, pDesc, pUnit, pContainer, act, MeasuresOfInterest.None);
}
private void MakeStat(string pName, string pDesc, string pUnit, string pContainer, Action<Stat> act, MeasuresOfInterest moi)
{
string desc = pDesc;
if (desc == null)
desc = pName;
Stat stat = new Stat(pName, pName, desc, pUnit, CategoryServer, pContainer, StatType.Pull, moi, act, StatVerbosity.Debug);
StatsManager.RegisterStat(stat);
RegisteredStats.Add(pName, stat);
}
public void RegisterServerStats()
{
// lastperformanceCounterSampleTime = Util.EnvironmentTickCount();
PerformanceCounter tempPC;
Stat tempStat;
string tempName;
try
{
tempName = "CPUPercent";
tempPC = new PerformanceCounter("Processor", "% Processor Time", "_Total");
processorPercentPerfCounter = new PerfCounterControl(tempPC);
// A long time bug in mono is that CPU percent is reported as CPU percent idle. Windows reports CPU percent busy.
tempStat = new Stat(tempName, tempName, "", "percent", CategoryServer, ContainerProcessor,
StatType.Pull, (s) => { GetNextValue(s, processorPercentPerfCounter); },
StatVerbosity.Info);
StatsManager.RegisterStat(tempStat);
RegisteredStats.Add(tempName, tempStat);
MakeStat("TotalProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds, 3); });
MakeStat("UserProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().UserProcessorTime.TotalSeconds, 3); });
MakeStat("PrivilegedProcessorTime", null, "sec", ContainerProcessor,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().PrivilegedProcessorTime.TotalSeconds, 3); });
MakeStat("Threads", null, "threads", ContainerProcessor,
(s) => { s.Value = Process.GetCurrentProcess().Threads.Count; });
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception creating 'Process': {1}", LogHeader, e);
}
MakeStat("BuiltinThreadpoolWorkerThreadsAvailable", null, "threads", ContainerThreadpool,
s =>
{
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
s.Value = workerThreads;
});
MakeStat("BuiltinThreadpoolIOCPThreadsAvailable", null, "threads", ContainerThreadpool,
s =>
{
int workerThreads, iocpThreads;
ThreadPool.GetAvailableThreads(out workerThreads, out iocpThreads);
s.Value = iocpThreads;
});
if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool && Util.GetSmartThreadPoolInfo() != null)
{
MakeStat("STPMaxThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxThreads);
MakeStat("STPMinThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MinThreads);
MakeStat("STPConcurrency", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().MaxConcurrentWorkItems);
MakeStat("STPActiveThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().ActiveThreads);
MakeStat("STPInUseThreads", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().InUseThreads);
MakeStat("STPWorkItemsWaiting", null, "threads", ContainerThreadpool, s => s.Value = Util.GetSmartThreadPoolInfo().WaitingCallbacks);
}
MakeStat(
"HTTPRequestsMade",
"Number of outbound HTTP requests made",
"requests",
ContainerNetwork,
s => s.Value = WebUtil.RequestNumber,
MeasuresOfInterest.AverageChangeOverTime);
try
{
List<string> okInterfaceTypes = new List<string>(NetworkInterfaceTypes.Split(','));
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nic in nics)
{
if (nic.OperationalStatus != OperationalStatus.Up)
continue;
string nicInterfaceType = nic.NetworkInterfaceType.ToString();
if (!okInterfaceTypes.Contains(nicInterfaceType))
{
m_log.DebugFormat("{0} Not including stats for network interface '{1}' of type '{2}'.",
LogHeader, nic.Name, nicInterfaceType);
m_log.DebugFormat("{0} To include, add to comma separated list in [Monitoring]NetworkInterfaceTypes={1}",
LogHeader, NetworkInterfaceTypes);
continue;
}
if (nic.Supports(NetworkInterfaceComponent.IPv4))
{
IPv4InterfaceStatistics nicStats = nic.GetIPv4Statistics();
if (nicStats != null)
{
MakeStat("BytesRcvd/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesReceived; }, 1024.0); });
MakeStat("BytesSent/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesSent; }, 1024.0); });
MakeStat("TotalBytes/" + nic.Name, nic.Name, "KB", ContainerNetwork,
(s) => { LookupNic(s, (ns) => { return ns.BytesSent + ns.BytesReceived; }, 1024.0); });
}
}
// TODO: add IPv6 (it may actually happen someday)
}
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception creating 'Network Interface': {1}", LogHeader, e);
}
MakeStat("ProcessMemory", null, "MB", ContainerMemory,
(s) => { s.Value = Math.Round(Process.GetCurrentProcess().WorkingSet64 / 1024d / 1024d, 3); });
MakeStat("HeapMemory", null, "MB", ContainerMemory,
(s) => { s.Value = Math.Round(GC.GetTotalMemory(false) / 1024d / 1024d, 3); });
MakeStat("LastHeapAllocationRate", null, "MB/sec", ContainerMemory,
(s) => { s.Value = Math.Round(MemoryWatchdog.LastHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
MakeStat("AverageHeapAllocationRate", null, "MB/sec", ContainerMemory,
(s) => { s.Value = Math.Round(MemoryWatchdog.AverageHeapAllocationRate * 1000d / 1024d / 1024d, 3); });
}
// Notes on performance counters:
// "How To Read Performance Counters": http://blogs.msdn.com/b/bclteam/archive/2006/06/02/618156.aspx
// "How to get the CPU Usage in C#": http://stackoverflow.com/questions/278071/how-to-get-the-cpu-usage-in-c
// "Mono Performance Counters": http://www.mono-project.com/Mono_Performance_Counters
private delegate double PerfCounterNextValue();
private void GetNextValue(Stat stat, PerfCounterControl perfControl)
{
if (Util.EnvironmentTickCountSubtract(perfControl.lastFetch) > performanceCounterSampleInterval)
{
if (perfControl != null && perfControl.perfCounter != null)
{
try
{
stat.Value = Math.Round(perfControl.perfCounter.NextValue(), 3);
}
catch (Exception e)
{
m_log.ErrorFormat("{0} Exception on NextValue fetching {1}: {2}", LogHeader, stat.Name, e);
}
perfControl.lastFetch = Util.EnvironmentTickCount();
}
}
}
// Lookup the nic that goes with this stat and set the value by using a fetch action.
// Not sure about closure with delegates inside delegates.
private delegate double GetIPv4StatValue(IPv4InterfaceStatistics interfaceStat);
private void LookupNic(Stat stat, GetIPv4StatValue getter, double factor)
{
// Get the one nic that has the name of this stat
IEnumerable<NetworkInterface> nics = NetworkInterface.GetAllNetworkInterfaces().Where(
(network) => network.Name == stat.Description);
try
{
foreach (NetworkInterface nic in nics)
{
IPv4InterfaceStatistics intrStats = nic.GetIPv4Statistics();
if (intrStats != null)
{
double newVal = Math.Round(getter(intrStats) / factor, 3);
stat.Value = newVal;
}
break;
}
}
catch
{
// There are times interfaces go away so we just won't update the stat for this
m_log.ErrorFormat("{0} Exception fetching stat on interface '{1}'", LogHeader, stat.Description);
}
}
}
public class ServerStatsAggregator : Stat
{
public ServerStatsAggregator(
string shortName,
string name,
string description,
string unitName,
string category,
string container
)
: base(
shortName,
name,
description,
unitName,
category,
container,
StatType.Push,
MeasuresOfInterest.None,
null,
StatVerbosity.Info)
{
}
public override string ToConsoleString()
{
StringBuilder sb = new StringBuilder();
return sb.ToString();
}
public override OSDMap ToOSDMap()
{
OSDMap ret = new OSDMap();
return ret;
}
}
}
| |
#region PDFsharp Charting - A .NET charting library based on PDFsharp
//
// Authors:
// Niklas Schneider
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using PdfSharp.Drawing;
namespace PdfSharp.Charting.Renderers
{
/// <summary>
/// Represents a column chart renderer.
/// </summary>
internal class ColumnChartRenderer : ColumnLikeChartRenderer
{
/// <summary>
/// Initializes a new instance of the ColumnChartRenderer class with the
/// specified renderer parameters.
/// </summary>
internal ColumnChartRenderer(RendererParameters parms)
: base(parms)
{ }
/// <summary>
/// Returns an initialized and renderer specific rendererInfo.
/// </summary>
internal override RendererInfo Init()
{
ChartRendererInfo cri = new ChartRendererInfo();
cri._chart = (Chart)_rendererParms.DrawingItem;
_rendererParms.RendererInfo = cri;
InitSeriesRendererInfo();
LegendRenderer lr = new ColumnLikeLegendRenderer(_rendererParms);
cri.legendRendererInfo = (LegendRendererInfo)lr.Init();
AxisRenderer xar = new HorizontalXAxisRenderer(_rendererParms);
cri.xAxisRendererInfo = (AxisRendererInfo)xar.Init();
AxisRenderer yar = GetYAxisRenderer();
cri.yAxisRendererInfo = (AxisRendererInfo)yar.Init();
PlotArea plotArea = cri._chart.PlotArea;
PlotAreaRenderer renderer = GetPlotAreaRenderer();
cri.plotAreaRendererInfo = (PlotAreaRendererInfo)renderer.Init();
DataLabelRenderer dlr = new ColumnDataLabelRenderer(_rendererParms);
dlr.Init();
return cri;
}
/// <summary>
/// Layouts and calculates the space used by the column chart.
/// </summary>
internal override void Format()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
LegendRenderer lr = new ColumnLikeLegendRenderer(_rendererParms);
lr.Format();
// axes
AxisRenderer xar = new HorizontalXAxisRenderer(_rendererParms);
xar.Format();
AxisRenderer yar = GetYAxisRenderer();
yar.Format();
// Calculate rects and positions.
CalcLayout();
// Calculated remaining plot area, now it's safe to format.
PlotAreaRenderer renderer = GetPlotAreaRenderer();
renderer.Format();
DataLabelRenderer dlr = new ColumnDataLabelRenderer(_rendererParms);
dlr.Format();
}
/// <summary>
/// Draws the column chart.
/// </summary>
internal override void Draw()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
LegendRenderer lr = new ColumnLikeLegendRenderer(_rendererParms);
lr.Draw();
WallRenderer wr = new WallRenderer(_rendererParms);
wr.Draw();
GridlinesRenderer glr = new ColumnLikeGridlinesRenderer(_rendererParms);
glr.Draw();
PlotAreaBorderRenderer pabr = new PlotAreaBorderRenderer(_rendererParms);
pabr.Draw();
PlotAreaRenderer renderer = GetPlotAreaRenderer();
renderer.Draw();
DataLabelRenderer dlr = new ColumnDataLabelRenderer(_rendererParms);
dlr.Draw();
if (cri.xAxisRendererInfo._axis != null)
{
AxisRenderer xar = new HorizontalXAxisRenderer(_rendererParms);
xar.Draw();
}
if (cri.yAxisRendererInfo._axis != null)
{
AxisRenderer yar = GetYAxisRenderer();
yar.Draw();
}
}
/// <summary>
/// Returns the specific plot area renderer.
/// </summary>
private PlotAreaRenderer GetPlotAreaRenderer()
{
Chart chart = (Chart)_rendererParms.DrawingItem;
switch (chart._type)
{
case ChartType.Column2D:
return new ColumnClusteredPlotAreaRenderer(_rendererParms);
case ChartType.ColumnStacked2D:
return new ColumnStackedPlotAreaRenderer(_rendererParms);
}
return null;
}
/// <summary>
/// Returns the specific y axis renderer.
/// </summary>
private YAxisRenderer GetYAxisRenderer()
{
Chart chart = (Chart)_rendererParms.DrawingItem;
switch (chart._type)
{
case ChartType.Column2D:
return new VerticalYAxisRenderer(_rendererParms);
case ChartType.ColumnStacked2D:
return new VerticalStackedYAxisRenderer(_rendererParms);
}
return null;
}
/// <summary>
/// Initializes all necessary data to draw all series for a column chart.
/// </summary>
private void InitSeriesRendererInfo()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
SeriesCollection seriesColl = cri._chart.SeriesCollection;
cri.seriesRendererInfos = new SeriesRendererInfo[seriesColl.Count];
for (int idx = 0; idx < seriesColl.Count; ++idx)
{
SeriesRendererInfo sri = new SeriesRendererInfo();
sri._series = seriesColl[idx];
cri.seriesRendererInfos[idx] = sri;
}
InitSeries();
}
/// <summary>
/// Initializes all necessary data to draw all series for a column chart.
/// </summary>
internal void InitSeries()
{
ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo;
int seriesIndex = 0;
foreach (SeriesRendererInfo sri in cri.seriesRendererInfos)
{
sri.LineFormat = Converter.ToXPen(sri._series._lineFormat, XColors.Black, ChartRenderer.DefaultSeriesLineWidth);
sri.FillFormat = Converter.ToXBrush(sri._series._fillFormat, ColumnColors.Item(seriesIndex++));
sri._pointRendererInfos = new ColumnRendererInfo[sri._series._seriesElements.Count];
for (int pointIdx = 0; pointIdx < sri._pointRendererInfos.Length; ++pointIdx)
{
PointRendererInfo pri = new ColumnRendererInfo();
Point point = sri._series._seriesElements[pointIdx];
pri.Point = point;
if (point != null)
{
pri.LineFormat = sri.LineFormat;
pri.FillFormat = sri.FillFormat;
if (point._lineFormat != null)
pri.LineFormat = Converter.ToXPen(point._lineFormat, sri.LineFormat);
if (point._fillFormat != null && !point._fillFormat._color.IsEmpty)
pri.FillFormat = new XSolidBrush(point._fillFormat._color);
}
sri._pointRendererInfos[pointIdx] = pri;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
private void EmitBinaryExpression(Expression expr)
{
EmitBinaryExpression(expr, CompilationFlags.EmitAsNoTail);
}
private void EmitBinaryExpression(Expression expr, CompilationFlags flags)
{
BinaryExpression b = (BinaryExpression)expr;
Debug.Assert(b.NodeType != ExpressionType.AndAlso && b.NodeType != ExpressionType.OrElse && b.NodeType != ExpressionType.Coalesce);
if (b.Method != null)
{
EmitBinaryMethod(b, flags);
return;
}
// For EQ and NE, if there is a user-specified method, use it.
// Otherwise implement the C# semantics that allow equality
// comparisons on non-primitive nullable structs that don't
// overload "=="
if ((b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual) &&
(b.Type == typeof(bool) || b.Type == typeof(bool?)))
{
// If we have x==null, x!=null, null==x or null!=x where x is
// nullable but not null, then generate a call to x.HasValue.
Debug.Assert(!b.IsLiftedToNull || b.Type == typeof(bool?));
if (ConstantCheck.IsNull(b.Left) && !ConstantCheck.IsNull(b.Right) && TypeUtils.IsNullableType(b.Right.Type))
{
EmitNullEquality(b.NodeType, b.Right, b.IsLiftedToNull);
return;
}
if (ConstantCheck.IsNull(b.Right) && !ConstantCheck.IsNull(b.Left) && TypeUtils.IsNullableType(b.Left.Type))
{
EmitNullEquality(b.NodeType, b.Left, b.IsLiftedToNull);
return;
}
// For EQ and NE, we can avoid some conversions if we're
// ultimately just comparing two managed pointers.
EmitExpression(GetEqualityOperand(b.Left));
EmitExpression(GetEqualityOperand(b.Right));
}
else
{
// Otherwise generate it normally
EmitExpression(b.Left);
EmitExpression(b.Right);
}
EmitBinaryOperator(b.NodeType, b.Left.Type, b.Right.Type, b.Type, b.IsLiftedToNull);
}
private void EmitNullEquality(ExpressionType op, Expression e, bool isLiftedToNull)
{
Debug.Assert(TypeUtils.IsNullableType(e.Type));
Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual);
// If we are lifted to null then just evaluate the expression for its side effects, discard,
// and generate null. If we are not lifted to null then generate a call to HasValue.
if (isLiftedToNull)
{
EmitExpressionAsVoid(e);
_ilg.EmitDefault(typeof(bool?));
}
else
{
EmitAddress(e, e.Type);
_ilg.EmitHasValue(e.Type);
if (op == ExpressionType.Equal)
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
}
}
}
private void EmitBinaryMethod(BinaryExpression b, CompilationFlags flags)
{
if (b.IsLifted)
{
ParameterExpression p1 = Expression.Variable(TypeUtils.GetNonNullableType(b.Left.Type), null);
ParameterExpression p2 = Expression.Variable(TypeUtils.GetNonNullableType(b.Right.Type), null);
MethodCallExpression mc = Expression.Call(null, b.Method, p1, p2);
Type resultType = null;
if (b.IsLiftedToNull)
{
resultType = TypeUtils.GetNullableType(mc.Type);
}
else
{
switch (b.NodeType)
{
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
if (mc.Type != typeof(bool))
{
throw Error.ArgumentMustBeBoolean(nameof(b));
}
resultType = typeof(bool);
break;
default:
resultType = TypeUtils.GetNullableType(mc.Type);
break;
}
}
var variables = new ParameterExpression[] { p1, p2 };
var arguments = new Expression[] { b.Left, b.Right };
ValidateLift(variables, arguments);
EmitLift(b.NodeType, resultType, mc, variables, arguments);
}
else
{
EmitMethodCallExpression(Expression.Call(null, b.Method, b.Left, b.Right), flags);
}
}
private void EmitBinaryOperator(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull)
{
bool leftIsNullable = TypeUtils.IsNullableType(leftType);
bool rightIsNullable = TypeUtils.IsNullableType(rightType);
switch (op)
{
case ExpressionType.ArrayIndex:
if (rightType != typeof(int))
{
throw ContractUtils.Unreachable;
}
EmitGetArrayElement(leftType);
return;
case ExpressionType.Coalesce:
throw Error.UnexpectedCoalesceOperator();
}
if (leftIsNullable || rightIsNullable)
{
EmitLiftedBinaryOp(op, leftType, rightType, resultType, liftedToNull);
}
else
{
EmitUnliftedBinaryOp(op, leftType, rightType);
EmitConvertArithmeticResult(op, resultType);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitUnliftedBinaryOp(ExpressionType op, Type leftType, Type rightType)
{
Debug.Assert(!TypeUtils.IsNullableType(leftType));
Debug.Assert(!TypeUtils.IsNullableType(rightType));
if (op == ExpressionType.Equal || op == ExpressionType.NotEqual)
{
EmitUnliftedEquality(op, leftType);
return;
}
if (!leftType.GetTypeInfo().IsPrimitive)
{
throw Error.OperatorNotImplementedForType(op, leftType);
}
switch (op)
{
case ExpressionType.Add:
_ilg.Emit(OpCodes.Add);
break;
case ExpressionType.AddChecked:
if (TypeUtils.IsFloatingPoint(leftType))
{
_ilg.Emit(OpCodes.Add);
}
else if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Add_Ovf_Un);
}
else
{
_ilg.Emit(OpCodes.Add_Ovf);
}
break;
case ExpressionType.Subtract:
_ilg.Emit(OpCodes.Sub);
break;
case ExpressionType.SubtractChecked:
if (TypeUtils.IsFloatingPoint(leftType))
{
_ilg.Emit(OpCodes.Sub);
}
else if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Sub_Ovf_Un);
}
else
{
_ilg.Emit(OpCodes.Sub_Ovf);
}
break;
case ExpressionType.Multiply:
_ilg.Emit(OpCodes.Mul);
break;
case ExpressionType.MultiplyChecked:
if (TypeUtils.IsFloatingPoint(leftType))
{
_ilg.Emit(OpCodes.Mul);
}
else if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Mul_Ovf_Un);
}
else
{
_ilg.Emit(OpCodes.Mul_Ovf);
}
break;
case ExpressionType.Divide:
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Div_Un);
}
else
{
_ilg.Emit(OpCodes.Div);
}
break;
case ExpressionType.Modulo:
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Rem_Un);
}
else
{
_ilg.Emit(OpCodes.Rem);
}
break;
case ExpressionType.And:
case ExpressionType.AndAlso:
_ilg.Emit(OpCodes.And);
break;
case ExpressionType.Or:
case ExpressionType.OrElse:
_ilg.Emit(OpCodes.Or);
break;
case ExpressionType.LessThan:
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Clt_Un);
}
else
{
_ilg.Emit(OpCodes.Clt);
}
break;
case ExpressionType.LessThanOrEqual:
{
Label labFalse = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Ble_Un_S, labFalse);
}
else
{
_ilg.Emit(OpCodes.Ble_S, labFalse);
}
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Br_S, labEnd);
_ilg.MarkLabel(labFalse);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.MarkLabel(labEnd);
}
break;
case ExpressionType.GreaterThan:
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Cgt_Un);
}
else
{
_ilg.Emit(OpCodes.Cgt);
}
break;
case ExpressionType.GreaterThanOrEqual:
{
Label labFalse = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Bge_Un_S, labFalse);
}
else
{
_ilg.Emit(OpCodes.Bge_S, labFalse);
}
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Br_S, labEnd);
_ilg.MarkLabel(labFalse);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.MarkLabel(labEnd);
}
break;
case ExpressionType.ExclusiveOr:
_ilg.Emit(OpCodes.Xor);
break;
case ExpressionType.LeftShift:
if (rightType != typeof(int))
{
throw ContractUtils.Unreachable;
}
EmitShiftMask(leftType);
_ilg.Emit(OpCodes.Shl);
break;
case ExpressionType.RightShift:
if (rightType != typeof(int))
{
throw ContractUtils.Unreachable;
}
EmitShiftMask(leftType);
if (TypeUtils.IsUnsigned(leftType))
{
_ilg.Emit(OpCodes.Shr_Un);
}
else
{
_ilg.Emit(OpCodes.Shr);
}
break;
default:
throw Error.UnhandledBinary(op);
}
}
// Shift operations have undefined behavior if the shift amount exceeds
// the number of bits in the value operand. See CLI III.3.58 and C# 7.9
// for the bit mask used below.
private void EmitShiftMask(Type leftType)
{
int mask = TypeUtils.IsInteger64(leftType) ? 0x3F : 0x1F;
_ilg.EmitInt(mask);
_ilg.Emit(OpCodes.And);
}
// Binary/unary operations on 8 and 16 bit operand types will leave a
// 32-bit value on the stack, because that's how IL works. For these
// cases, we need to cast it back to the resultType, possibly using a
// checked conversion if the original operator was convert
private void EmitConvertArithmeticResult(ExpressionType op, Type resultType)
{
Debug.Assert(!resultType.IsNullableType());
switch (resultType.GetTypeCode())
{
case TypeCode.Byte:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U1 : OpCodes.Conv_U1);
break;
case TypeCode.SByte:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I1 : OpCodes.Conv_I1);
break;
case TypeCode.UInt16:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U2 : OpCodes.Conv_U2);
break;
case TypeCode.Int16:
_ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I2 : OpCodes.Conv_I2);
break;
}
}
private void EmitUnliftedEquality(ExpressionType op, Type type)
{
Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual);
if (!type.GetTypeInfo().IsPrimitive && type.GetTypeInfo().IsValueType && !type.GetTypeInfo().IsEnum)
{
throw Error.OperatorNotImplementedForType(op, type);
}
_ilg.Emit(OpCodes.Ceq);
if (op == ExpressionType.NotEqual)
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitLiftedBinaryOp(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull)
{
Debug.Assert(TypeUtils.IsNullableType(leftType) || TypeUtils.IsNullableType(rightType));
switch (op)
{
case ExpressionType.And:
if (leftType == typeof(bool?))
{
EmitLiftedBooleanAnd();
}
else
{
EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
}
break;
case ExpressionType.Or:
if (leftType == typeof(bool?))
{
EmitLiftedBooleanOr();
}
else
{
EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
}
break;
case ExpressionType.ExclusiveOr:
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType);
break;
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
EmitLiftedRelational(op, leftType, rightType, resultType, liftedToNull);
break;
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
default:
throw ContractUtils.Unreachable;
}
}
private void EmitLiftedRelational(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull)
{
Debug.Assert(TypeUtils.IsNullableType(leftType));
Label shortCircuit = _ilg.DefineLabel();
LocalBuilder locLeft = GetLocal(leftType);
LocalBuilder locRight = GetLocal(rightType);
// store values (reverse order since they are already on the stack)
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
if (op == ExpressionType.Equal)
{
// test for both null -> true
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Brtrue_S, shortCircuit);
_ilg.Emit(OpCodes.Pop);
// test for either is null -> false
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Brfalse_S, shortCircuit);
_ilg.Emit(OpCodes.Pop);
}
else if (op == ExpressionType.NotEqual)
{
// test for both null -> false
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
_ilg.Emit(OpCodes.Or);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Brfalse_S, shortCircuit);
_ilg.Emit(OpCodes.Pop);
// test for either is null -> true
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Or);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Brtrue_S, shortCircuit);
_ilg.Emit(OpCodes.Pop);
}
else
{
// test for either is null -> false
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
_ilg.Emit(OpCodes.And);
_ilg.Emit(OpCodes.Dup);
_ilg.Emit(OpCodes.Brfalse_S, shortCircuit);
_ilg.Emit(OpCodes.Pop);
}
// do op on values
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(leftType);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(rightType);
//RELEASING locLeft locRight
FreeLocal(locLeft);
FreeLocal(locRight);
EmitBinaryOperator(
op,
TypeUtils.GetNonNullableType(leftType),
TypeUtils.GetNonNullableType(rightType),
TypeUtils.GetNonNullableType(resultType),
false
);
if (!liftedToNull)
{
_ilg.MarkLabel(shortCircuit);
}
if (!TypeUtils.AreEquivalent(resultType, TypeUtils.GetNonNullableType(resultType)))
{
_ilg.EmitConvertToType(TypeUtils.GetNonNullableType(resultType), resultType, true);
}
if (liftedToNull)
{
Label labEnd = _ilg.DefineLabel();
_ilg.Emit(OpCodes.Br, labEnd);
_ilg.MarkLabel(shortCircuit);
_ilg.Emit(OpCodes.Pop);
_ilg.Emit(OpCodes.Ldnull);
_ilg.Emit(OpCodes.Unbox_Any, resultType);
_ilg.MarkLabel(labEnd);
}
}
private void EmitLiftedBinaryArithmetic(ExpressionType op, Type leftType, Type rightType, Type resultType)
{
bool leftIsNullable = TypeUtils.IsNullableType(leftType);
bool rightIsNullable = TypeUtils.IsNullableType(rightType);
Debug.Assert(leftIsNullable || rightIsNullable);
Label labIfNull = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
LocalBuilder locLeft = GetLocal(leftType);
LocalBuilder locRight = GetLocal(rightType);
LocalBuilder locResult = GetLocal(resultType);
// store values (reverse order since they are already on the stack)
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
// test for null
// use short circuiting
if (leftIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(leftType);
_ilg.Emit(OpCodes.Brfalse_S, labIfNull);
}
if (rightIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(rightType);
_ilg.Emit(OpCodes.Brfalse_S, labIfNull);
}
// do op on values
if (leftIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(leftType);
}
else
{
_ilg.Emit(OpCodes.Ldloc, locLeft);
}
if (rightIsNullable)
{
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitGetValueOrDefault(rightType);
}
else
{
_ilg.Emit(OpCodes.Ldloc, locRight);
}
//RELEASING locLeft locRight
FreeLocal(locLeft);
FreeLocal(locRight);
EmitBinaryOperator(op, TypeUtils.GetNonNullableType(leftType), TypeUtils.GetNonNullableType(rightType), TypeUtils.GetNonNullableType(resultType), false);
// construct result type
ConstructorInfo ci = resultType.GetConstructor(new Type[] { TypeUtils.GetNonNullableType(resultType) });
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, locResult);
_ilg.Emit(OpCodes.Br_S, labEnd);
// if null then create a default one
_ilg.MarkLabel(labIfNull);
_ilg.Emit(OpCodes.Ldloca, locResult);
_ilg.Emit(OpCodes.Initobj, resultType);
_ilg.MarkLabel(labEnd);
_ilg.Emit(OpCodes.Ldloc, locResult);
//RELEASING locResult
FreeLocal(locResult);
}
private void EmitLiftedBooleanAnd()
{
Type type = typeof(bool?);
Label labComputeRight = _ilg.DefineLabel();
Label labReturnFalse = _ilg.DefineLabel();
Label labReturnNull = _ilg.DefineLabel();
Label labReturnValue = _ilg.DefineLabel();
Label labExit = _ilg.DefineLabel();
// store values (reverse order since they are already on the stack)
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
// compute left
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labComputeRight);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Brtrue, labReturnFalse);
// compute right
_ilg.MarkLabel(labComputeRight);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locRight);
//RELEASING locRight
FreeLocal(locRight);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Brtrue_S, labReturnFalse);
// check left for null again
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labReturnNull);
// return true
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
// return false
_ilg.MarkLabel(labReturnFalse);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
_ilg.MarkLabel(labReturnValue);
ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) });
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Br, labExit);
// return null
_ilg.MarkLabel(labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.Emit(OpCodes.Initobj, type);
_ilg.MarkLabel(labExit);
_ilg.Emit(OpCodes.Ldloc, locLeft);
//RELEASING locLeft
FreeLocal(locLeft);
}
private void EmitLiftedBooleanOr()
{
Type type = typeof(bool?);
Label labComputeRight = _ilg.DefineLabel();
Label labReturnTrue = _ilg.DefineLabel();
Label labReturnNull = _ilg.DefineLabel();
Label labReturnValue = _ilg.DefineLabel();
Label labExit = _ilg.DefineLabel();
// store values (reverse order since they are already on the stack)
LocalBuilder locLeft = GetLocal(type);
LocalBuilder locRight = GetLocal(type);
_ilg.Emit(OpCodes.Stloc, locRight);
_ilg.Emit(OpCodes.Stloc, locLeft);
// compute left
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labComputeRight);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Brfalse, labReturnTrue);
// compute right
_ilg.MarkLabel(labComputeRight);
_ilg.Emit(OpCodes.Ldloca, locRight);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse_S, labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locRight);
//RELEASING locRight
FreeLocal(locRight);
_ilg.EmitGetValueOrDefault(type);
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
_ilg.Emit(OpCodes.Brfalse_S, labReturnTrue);
// check left for null again
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.EmitHasValue(type);
_ilg.Emit(OpCodes.Brfalse, labReturnNull);
// return false
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
// return true
_ilg.MarkLabel(labReturnTrue);
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Br_S, labReturnValue);
_ilg.MarkLabel(labReturnValue);
ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) });
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, locLeft);
_ilg.Emit(OpCodes.Br, labExit);
// return null
_ilg.MarkLabel(labReturnNull);
_ilg.Emit(OpCodes.Ldloca, locLeft);
_ilg.Emit(OpCodes.Initobj, type);
_ilg.MarkLabel(labExit);
_ilg.Emit(OpCodes.Ldloc, locLeft);
//RELEASING locLeft
FreeLocal(locLeft);
}
}
}
| |
// 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.Runtime.InteropServices;
namespace Internal.Cryptography.Pal.Native
{
internal enum CertQueryObjectType : int
{
CERT_QUERY_OBJECT_FILE = 0x00000001,
CERT_QUERY_OBJECT_BLOB = 0x00000002,
}
[Flags]
internal enum ExpectedContentTypeFlags : int
{
//encoded single certificate
CERT_QUERY_CONTENT_FLAG_CERT = 1 << ContentType.CERT_QUERY_CONTENT_CERT,
//encoded single CTL
CERT_QUERY_CONTENT_FLAG_CTL = 1 << ContentType.CERT_QUERY_CONTENT_CTL,
//encoded single CRL
CERT_QUERY_CONTENT_FLAG_CRL = 1 << ContentType.CERT_QUERY_CONTENT_CRL,
//serialized store
CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_STORE,
//serialized single certificate
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CERT,
//serialized single CTL
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CTL,
//serialized single CRL
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CRL,
//an encoded PKCS#7 signed message
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED,
//an encoded PKCS#7 message. But it is not a signed message
CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_UNSIGNED,
//the content includes an embedded PKCS7 signed message
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED,
//an encoded PKCS#10
CERT_QUERY_CONTENT_FLAG_PKCS10 = 1 << ContentType.CERT_QUERY_CONTENT_PKCS10,
//an encoded PFX BLOB
CERT_QUERY_CONTENT_FLAG_PFX = 1 << ContentType.CERT_QUERY_CONTENT_PFX,
//an encoded CertificatePair (contains forward and/or reverse cross certs)
CERT_QUERY_CONTENT_FLAG_CERT_PAIR = 1 << ContentType.CERT_QUERY_CONTENT_CERT_PAIR,
//an encoded PFX BLOB, and we do want to load it (not included in
//CERT_QUERY_CONTENT_FLAG_ALL)
CERT_QUERY_CONTENT_FLAG_PFX_AND_LOAD = 1 << ContentType.CERT_QUERY_CONTENT_PFX_AND_LOAD,
CERT_QUERY_CONTENT_FLAG_ALL =
CERT_QUERY_CONTENT_FLAG_CERT |
CERT_QUERY_CONTENT_FLAG_CTL |
CERT_QUERY_CONTENT_FLAG_CRL |
CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE |
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL |
CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL |
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED |
CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED |
CERT_QUERY_CONTENT_FLAG_PKCS10 |
CERT_QUERY_CONTENT_FLAG_PFX |
CERT_QUERY_CONTENT_FLAG_CERT_PAIR,
}
[Flags]
internal enum ExpectedFormatTypeFlags : int
{
CERT_QUERY_FORMAT_FLAG_BINARY = 1 << FormatType.CERT_QUERY_FORMAT_BINARY,
CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_BASE64_ENCODED,
CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED,
CERT_QUERY_FORMAT_FLAG_ALL = CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED,
}
internal enum CertEncodingType : int
{
PKCS_7_ASN_ENCODING = 0x10000,
X509_ASN_ENCODING = 0x00001,
All = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING,
}
internal enum ContentType : int
{
//encoded single certificate
CERT_QUERY_CONTENT_CERT = 1,
//encoded single CTL
CERT_QUERY_CONTENT_CTL = 2,
//encoded single CRL
CERT_QUERY_CONTENT_CRL = 3,
//serialized store
CERT_QUERY_CONTENT_SERIALIZED_STORE = 4,
//serialized single certificate
CERT_QUERY_CONTENT_SERIALIZED_CERT = 5,
//serialized single CTL
CERT_QUERY_CONTENT_SERIALIZED_CTL = 6,
//serialized single CRL
CERT_QUERY_CONTENT_SERIALIZED_CRL = 7,
//a PKCS#7 signed message
CERT_QUERY_CONTENT_PKCS7_SIGNED = 8,
//a PKCS#7 message, such as enveloped message. But it is not a signed message,
CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9,
//a PKCS7 signed message embedded in a file
CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10,
//an encoded PKCS#10
CERT_QUERY_CONTENT_PKCS10 = 11,
//an encoded PFX BLOB
CERT_QUERY_CONTENT_PFX = 12,
//an encoded CertificatePair (contains forward and/or reverse cross certs)
CERT_QUERY_CONTENT_CERT_PAIR = 13,
//an encoded PFX BLOB, which was loaded to phCertStore
CERT_QUERY_CONTENT_PFX_AND_LOAD = 14,
}
internal enum FormatType : int
{
CERT_QUERY_FORMAT_BINARY = 1,
CERT_QUERY_FORMAT_BASE64_ENCODED = 2,
CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3,
}
// CRYPTOAPI_BLOB has many typedef aliases in the C++ world (CERT_BLOB, DATA_BLOB, etc.) We'll just stick to one name here.
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CRYPTOAPI_BLOB
{
public CRYPTOAPI_BLOB(int cbData, byte* pbData)
{
this.cbData = cbData;
this.pbData = pbData;
}
public int cbData;
public byte* pbData;
public byte[] ToByteArray()
{
if (cbData == 0)
{
return Array.Empty<byte>();
}
byte[] array = new byte[cbData];
Marshal.Copy((IntPtr)pbData, array, 0, cbData);
return array;
}
}
internal enum CertContextPropId : int
{
CERT_KEY_PROV_INFO_PROP_ID = 2,
CERT_SHA1_HASH_PROP_ID = 3,
CERT_KEY_CONTEXT_PROP_ID = 5,
CERT_FRIENDLY_NAME_PROP_ID = 11,
CERT_ARCHIVED_PROP_ID = 19,
CERT_KEY_IDENTIFIER_PROP_ID = 20,
CERT_PUBKEY_ALG_PARA_PROP_ID = 22,
CERT_NCRYPT_KEY_HANDLE_PROP_ID = 78,
// CERT_DELETE_KEYSET_PROP_ID is not defined by Windows. It's a custom property set by the framework
// as a backchannel message from the portion of X509Certificate2Collection.Import() that loads up the PFX
// to the X509Certificate2..ctor(IntPtr) call that creates the managed wrapper.
CERT_DELETE_KEYSET_PROP_ID = 101,
}
[Flags]
internal enum CertSetPropertyFlags : int
{
CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG = 0x40000000,
None = 0x00000000,
}
internal enum CertNameType : int
{
CERT_NAME_EMAIL_TYPE = 1,
CERT_NAME_RDN_TYPE = 2,
CERT_NAME_ATTR_TYPE = 3,
CERT_NAME_SIMPLE_DISPLAY_TYPE = 4,
CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5,
CERT_NAME_DNS_TYPE = 6,
CERT_NAME_URL_TYPE = 7,
CERT_NAME_UPN_TYPE = 8,
}
[Flags]
internal enum CertNameFlags : int
{
None = 0x00000000,
CERT_NAME_ISSUER_FLAG = 0x00000001,
}
internal enum CertNameStringType : int
{
CERT_X500_NAME_STR = 3,
CERT_NAME_STR_REVERSE_FLAG = 0x02000000,
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_CONTEXT
{
public CertEncodingType dwCertEncodingType;
public byte* pbCertEncoded;
public int cbCertEncoded;
public CERT_INFO* pCertInfo;
public IntPtr hCertStore;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_INFO
{
public int dwVersion;
public CRYPTOAPI_BLOB SerialNumber;
public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm;
public CRYPTOAPI_BLOB Issuer;
public FILETIME NotBefore;
public FILETIME NotAfter;
public CRYPTOAPI_BLOB Subject;
public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo;
public CRYPT_BIT_BLOB IssuerUniqueId;
public CRYPT_BIT_BLOB SubjectUniqueId;
public int cExtension;
public CERT_EXTENSION* rgExtension;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CRYPT_ALGORITHM_IDENTIFIER
{
public IntPtr pszObjId;
public CRYPTOAPI_BLOB Parameters;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_PUBLIC_KEY_INFO
{
public CRYPT_ALGORITHM_IDENTIFIER Algorithm;
public CRYPT_BIT_BLOB PublicKey;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CRYPT_BIT_BLOB
{
public int cbData;
public byte* pbData;
public int cUnusedBits;
public byte[] ToByteArray()
{
if (cbData == 0)
{
return Array.Empty<byte>();
}
byte[] array = new byte[cbData];
Marshal.Copy((IntPtr)pbData, array, 0, cbData);
return array;
}
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_EXTENSION
{
public IntPtr pszObjId;
public int fCritical;
public CRYPTOAPI_BLOB Value;
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILETIME
{
private uint ftTimeLow;
private uint ftTimeHigh;
public DateTime ToDateTime()
{
long fileTime = (((long)ftTimeHigh) << 32) + ftTimeLow;
return DateTime.FromFileTime(fileTime);
}
public static FILETIME FromDateTime(DateTime dt)
{
long fileTime = dt.ToFileTime();
unchecked
{
return new FILETIME()
{
ftTimeLow = (uint)fileTime,
ftTimeHigh = (uint)(fileTime >> 32),
};
}
}
}
internal enum CertStoreProvider : int
{
CERT_STORE_PROV_MEMORY = 2,
CERT_STORE_PROV_SYSTEM_W = 10,
}
[Flags]
internal enum CertStoreFlags : int
{
CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001,
CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002,
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004,
CERT_STORE_DELETE_FLAG = 0x00000010,
CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020,
CERT_STORE_SHARE_STORE_FLAG = 0x00000040,
CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080,
CERT_STORE_MANIFOLD_FLAG = 0x00000100,
CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200,
CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400,
CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800,
CERT_STORE_READONLY_FLAG = 0x00008000,
CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000,
CERT_STORE_CREATE_NEW_FLAG = 0x00002000,
CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000,
CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000,
CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000,
None = 0x00000000,
}
internal enum CertStoreAddDisposition : int
{
CERT_STORE_ADD_NEW = 1,
CERT_STORE_ADD_USE_EXISTING = 2,
CERT_STORE_ADD_REPLACE_EXISTING = 3,
CERT_STORE_ADD_ALWAYS = 4,
CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5,
CERT_STORE_ADD_NEWER = 6,
CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7,
}
[Flags]
internal enum PfxCertStoreFlags : int
{
CRYPT_EXPORTABLE = 0x00000001,
CRYPT_USER_PROTECTED = 0x00000002,
CRYPT_MACHINE_KEYSET = 0x00000020,
CRYPT_USER_KEYSET = 0x00001000,
PKCS12_PREFER_CNG_KSP = 0x00000100,
PKCS12_ALWAYS_CNG_KSP = 0x00000200,
PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000,
PKCS12_NO_PERSIST_KEY = 0x00008000,
PKCS12_INCLUDE_EXTENDED_PROPERTIES = 0x00000010,
None = 0x00000000,
}
internal enum CryptMessageParameterType : int
{
CMSG_SIGNER_COUNT_PARAM = 5,
CMSG_SIGNER_INFO_PARAM = 6,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CMSG_SIGNER_INFO_Partial // This is not the full definition of CMSG_SIGNER_INFO. Only defining the part we use.
{
public int dwVersion;
public CRYPTOAPI_BLOB Issuer;
public CRYPTOAPI_BLOB SerialNumber;
//... more fields follow ...
}
[Flags]
internal enum CertFindFlags : int
{
None = 0x00000000,
}
internal enum CertFindType : int
{
CERT_FIND_SUBJECT_CERT = 0x000b0000,
CERT_FIND_HASH = 0x00010000,
CERT_FIND_SUBJECT_STR = 0x00080007,
CERT_FIND_ISSUER_STR = 0x00080004,
CERT_FIND_EXISTING = 0x000d0000,
CERT_FIND_ANY = 0x00000000,
}
[Flags]
internal enum PFXExportFlags : int
{
REPORT_NO_PRIVATE_KEY = 0x00000001,
REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY = 0x00000002,
EXPORT_PRIVATE_KEYS = 0x00000004,
None = 0x00000000,
}
internal enum KeyContextSpec : uint
{
AT_KEYEXCHANGE = 1,
AT_SIGNATURE = 2,
CERT_NCRYPT_KEY_SPEC = 0xFFFFFFFF,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_KEY_CONTEXT
{
public int cbSize;
public IntPtr hProvOrNcryptKey;
public KeyContextSpec dwKeySpec;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CRYPT_KEY_PROV_INFO
{
public char* pwszContainerName;
public char* pwszProvName;
public int dwProvType;
public CryptAcquireContextFlags dwFlags;
public int cProvParam;
public IntPtr rgProvParam;
public int dwKeySpec;
}
[Flags]
internal enum CryptAcquireContextFlags : int
{
CRYPT_DELETEKEYSET = 0x00000010,
CRYPT_MACHINE_KEYSET = 0x00000020,
None = 0x00000000,
}
[Flags]
internal enum CertNameStrTypeAndFlags : int
{
CERT_SIMPLE_NAME_STR = 1,
CERT_OID_NAME_STR = 2,
CERT_X500_NAME_STR = 3,
CERT_NAME_STR_SEMICOLON_FLAG = 0x40000000,
CERT_NAME_STR_NO_PLUS_FLAG = 0x20000000,
CERT_NAME_STR_NO_QUOTING_FLAG = 0x10000000,
CERT_NAME_STR_CRLF_FLAG = 0x08000000,
CERT_NAME_STR_COMMA_FLAG = 0x04000000,
CERT_NAME_STR_REVERSE_FLAG = 0x02000000,
CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG = 0x00010000,
CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG = 0x00020000,
CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG = 0x00040000,
CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG = 0x00080000,
}
internal enum FormatObjectType : int
{
None = 0,
}
[Flags]
internal enum FormatObjectStringType : int
{
CRYPT_FORMAT_STR_MULTI_LINE = 0x00000001,
CRYPT_FORMAT_STR_NO_HEX = 0x00000010,
None = 0x00000000,
}
internal enum FormatObjectStructType : int
{
X509_NAME = 7,
}
internal static class AlgId
{
public const int CALG_RSA_KEYX = 0xa400;
public const int CALG_RSA_SIGN = 0x2400;
public const int CALG_DSS_SIGN = 0x2200;
public const int CALG_SHA1 = 0x8004;
}
[Flags]
internal enum CryptDecodeObjectFlags : int
{
None = 0x00000000,
}
internal enum CryptDecodeObjectStructType : int
{
CNG_RSA_PUBLIC_KEY_BLOB = 72,
X509_DSS_PUBLICKEY = 38,
X509_DSS_PARAMETERS = 39,
X509_KEY_USAGE = 14,
X509_BASIC_CONSTRAINTS = 13,
X509_BASIC_CONSTRAINTS2 = 15,
X509_ENHANCED_KEY_USAGE = 36,
X509_CERT_POLICIES = 16,
X509_UNICODE_ANY_STRING = 24,
X509_CERTIFICATE_TEMPLATE = 64,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CTL_USAGE
{
public int cUsageIdentifier;
public IntPtr rgpszUsageIdentifier;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_USAGE_MATCH
{
public CertUsageMatchType dwType;
public CTL_USAGE Usage;
}
internal enum CertUsageMatchType : int
{
USAGE_MATCH_TYPE_AND = 0x00000000,
USAGE_MATCH_TYPE_OR = 0x00000001,
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_CHAIN_PARA
{
public int cbSize;
public CERT_USAGE_MATCH RequestedUsage;
public CERT_USAGE_MATCH RequestedIssuancePolicy;
public int dwUrlRetrievalTimeout;
public int fCheckRevocationFreshnessTime;
public int dwRevocationFreshnessTime;
public FILETIME* pftCacheResync;
public int pStrongSignPara;
public int dwStrongSignFlags;
}
[Flags]
internal enum CertChainFlags : int
{
None = 0x00000000,
CERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000,
CERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000,
CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x40000000,
CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY = unchecked((int)0x80000000),
}
internal enum ChainEngine : int
{
HCCE_CURRENT_USER = 0x0,
HCCE_LOCAL_MACHINE = 0x1,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_DSS_PARAMETERS
{
public CRYPTOAPI_BLOB p;
public CRYPTOAPI_BLOB q;
public CRYPTOAPI_BLOB g;
}
internal enum PubKeyMagic : int
{
DSS_MAGIC = 0x31535344,
}
[StructLayout(LayoutKind.Sequential)]
internal struct BLOBHEADER
{
public byte bType;
public byte bVersion;
public short reserved;
public uint aiKeyAlg;
};
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_BASIC_CONSTRAINTS_INFO
{
public CRYPT_BIT_BLOB SubjectType;
public int fPathLenConstraint;
public int dwPathLenConstraint;
public int cSubtreesConstraint;
public CRYPTOAPI_BLOB* rgSubtreesConstraint; // PCERT_NAME_BLOB
// SubjectType.pbData[0] can contain a CERT_CA_SUBJECT_FLAG that when set indicates that the certificate's subject can act as a CA
public const byte CERT_CA_SUBJECT_FLAG = 0x80;
};
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_BASIC_CONSTRAINTS2_INFO
{
public int fCA;
public int fPathLenConstraint;
public int dwPathLenConstraint;
};
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_ENHKEY_USAGE
{
public int cUsageIdentifier;
public IntPtr* rgpszUsageIdentifier; // LPSTR*
}
internal enum CertStoreSaveAs : int
{
CERT_STORE_SAVE_AS_STORE = 1,
CERT_STORE_SAVE_AS_PKCS7 = 2,
}
internal enum CertStoreSaveTo : int
{
CERT_STORE_SAVE_TO_MEMORY = 2,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_POLICY_INFO
{
public IntPtr pszPolicyIdentifier;
public int cPolicyQualifier;
public IntPtr rgPolicyQualifier;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_POLICIES_INFO
{
public int cPolicyInfo;
public CERT_POLICY_INFO* rgPolicyInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_NAME_VALUE
{
public int dwValueType;
public CRYPTOAPI_BLOB Value;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_TEMPLATE_EXT
{
public IntPtr pszObjId;
public int dwMajorVersion;
public int fMinorVersion;
public int dwMinorVersion;
}
[Flags]
internal enum CertControlStoreFlags : int
{
None = 0x00000000,
}
internal enum CertControlStoreType : int
{
CERT_STORE_CTRL_AUTO_RESYNC = 4,
}
[Flags]
internal enum CertTrustErrorStatus : int
{
CERT_TRUST_NO_ERROR = 0x00000000,
CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001,
CERT_TRUST_IS_NOT_TIME_NESTED = 0x00000002,
CERT_TRUST_IS_REVOKED = 0x00000004,
CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008,
CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010,
CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020,
CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040,
CERT_TRUST_IS_CYCLIC = 0x00000080,
CERT_TRUST_INVALID_EXTENSION = 0x00000100,
CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200,
CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400,
CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800,
CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000,
CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000,
CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000,
CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000,
CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000,
CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000,
CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000,
CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000,
CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000,
// These can be applied to chains only
CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000,
CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000,
CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000,
CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000,
}
[Flags]
internal enum CertTrustInfoStatus : int
{
// These can be applied to certificates only
CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001,
CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002,
CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004,
CERT_TRUST_IS_SELF_SIGNED = 0x00000008,
// These can be applied to certificates and chains
CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100,
CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000200,
CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400,
// These can be applied to chains only
CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_TRUST_STATUS
{
public CertTrustErrorStatus dwErrorStatus;
public CertTrustInfoStatus dwInfoStatus;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_CHAIN_ELEMENT
{
public int cbSize;
public CERT_CONTEXT* pCertContext;
public CERT_TRUST_STATUS TrustStatus;
public IntPtr pRevocationInfo;
public IntPtr pIssuanceUsage;
public IntPtr pApplicationUsage;
public IntPtr pwszExtendedErrorInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_SIMPLE_CHAIN
{
public int cbSize;
public CERT_TRUST_STATUS TrustStatus;
public int cElement;
public CERT_CHAIN_ELEMENT** rgpElement;
public IntPtr pTrustListInfo;
// fHasRevocationFreshnessTime is only set if we are able to retrieve
// revocation information for all elements checked for revocation.
// For a CRL its CurrentTime - ThisUpdate.
//
// dwRevocationFreshnessTime is the largest time across all elements
// checked.
public int fHasRevocationFreshnessTime;
public int dwRevocationFreshnessTime; // seconds
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct CERT_CHAIN_CONTEXT
{
public int cbSize;
public CERT_TRUST_STATUS TrustStatus;
public int cChain;
public CERT_SIMPLE_CHAIN** rgpChain;
// Following is returned when CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS
// is set in dwFlags
public int cLowerQualityChainContext;
public CERT_CHAIN_CONTEXT** rgpLowerQualityChainContext;
// fHasRevocationFreshnessTime is only set if we are able to retrieve
// revocation information for all elements checked for revocation.
// For a CRL its CurrentTime - ThisUpdate.
//
// dwRevocationFreshnessTime is the largest time across all elements
// checked.
public int fHasRevocationFreshnessTime;
public int dwRevocationFreshnessTime; // seconds
// Flags passed when created via CertGetCertificateChain
public int dwCreateFlags;
// Following is updated with unique Id when the chain context is logged.
public Guid ChainId;
}
[Flags]
internal enum FormatMessageFlags : int
{
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_CHAIN_POLICY_PARA
{
public int cbSize;
public int dwFlags;
public IntPtr pvExtraPolicyPara;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CERT_CHAIN_POLICY_STATUS
{
public int cbSize;
public int dwError;
public IntPtr lChainIndex;
public IntPtr lElementIndex;
public IntPtr pvExtraPolicyStatus;
}
internal enum ChainPolicy : int
{
// Predefined verify chain policies
CERT_CHAIN_POLICY_BASE = 1,
}
internal enum CryptAcquireFlags : int
{
CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000,
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Discord.WebSocket
{
public partial class BaseSocketClient
{
//Channels
/// <summary> Fired when a channel is created. </summary>
/// <remarks>
/// <para>
/// This event is fired when a generic channel has been created. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter.
/// </para>
/// <para>
/// The newly created channel is passed into the event handler parameter. The given channel type may
/// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category);
/// see the derived classes of <see cref="SocketChannel"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="ChannelCreated"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketChannel, Task> ChannelCreated
{
add { _channelCreatedEvent.Add(value); }
remove { _channelCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelCreatedEvent = new AsyncEvent<Func<SocketChannel, Task>>();
/// <summary> Fired when a channel is destroyed. </summary>
/// <remarks>
/// <para>
/// This event is fired when a generic channel has been destroyed. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketChannel"/> as its parameter.
/// </para>
/// <para>
/// The destroyed channel is passed into the event handler parameter. The given channel type may
/// include, but not limited to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category);
/// see the derived classes of <see cref="SocketChannel"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="ChannelDestroyed"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketChannel, Task> ChannelDestroyed {
add { _channelDestroyedEvent.Add(value); }
remove { _channelDestroyedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketChannel, Task>> _channelDestroyedEvent = new AsyncEvent<Func<SocketChannel, Task>>();
/// <summary> Fired when a channel is updated. </summary>
/// <remarks>
/// <para>
/// This event is fired when a generic channel has been destroyed. The event handler must return a
/// <see cref="Task"/> and accept 2 <see cref="SocketChannel"/> as its parameters.
/// </para>
/// <para>
/// The original (prior to update) channel is passed into the first <see cref="SocketChannel"/>, while
/// the updated channel is passed into the second. The given channel type may include, but not limited
/// to, Private Channels (DM, Group), Guild Channels (Text, Voice, Category); see the derived classes of
/// <see cref="SocketChannel"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="ChannelUpdated"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketChannel, SocketChannel, Task> ChannelUpdated {
add { _channelUpdatedEvent.Add(value); }
remove { _channelUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketChannel, SocketChannel, Task>> _channelUpdatedEvent = new AsyncEvent<Func<SocketChannel, SocketChannel, Task>>();
//Messages
/// <summary> Fired when a message is received. </summary>
/// <remarks>
/// <para>
/// This event is fired when a message is received. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketMessage"/> as its parameter.
/// </para>
/// <para>
/// The message that is sent to the client is passed into the event handler parameter as
/// <see cref="SocketMessage"/>. This message may be a system message (i.e.
/// <see cref="SocketSystemMessage"/>) or a user message (i.e. <see cref="SocketUserMessage"/>. See the
/// derived classes of <see cref="SocketMessage"/> for more details.
/// </para>
/// </remarks>
/// <example>
/// <para>The example below checks if the newly received message contains the target user.</para>
/// <code language="cs" region="MessageReceived"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<SocketMessage, Task> MessageReceived {
add { _messageReceivedEvent.Add(value); }
remove { _messageReceivedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketMessage, Task>> _messageReceivedEvent = new AsyncEvent<Func<SocketMessage, Task>>();
/// <summary> Fired when a message is deleted. </summary>
/// <remarks>
/// <para>
/// This event is fired when a message is deleted. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/> and
/// <see cref="ISocketMessageChannel"/> as its parameters.
/// </para>
/// <para>
/// <note type="important">
/// It is not possible to retrieve the message via
/// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord
/// after the message has been deleted.
/// </note>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The source channel of the removed message will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// </remarks>
/// <example>
/// <code language="cs" region="MessageDeleted"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs" />
/// </example>
public event Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task> MessageDeleted {
add { _messageDeletedEvent.Add(value); }
remove { _messageDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task>> _messageDeletedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, ISocketMessageChannel, Task>>();
/// <summary> Fired when multiple messages are bulk deleted. </summary>
/// <remarks>
/// <note>
/// The <see cref="MessageDeleted"/> event will not be fired for individual messages contained in this event.
/// </note>
/// <para>
/// This event is fired when multiple messages are bulk deleted. The event handler must return a
/// <see cref="Task"/> and accept an <see cref="IReadOnlyCollection{Cacheable}"/> and
/// <see cref="ISocketMessageChannel"/> as its parameters.
/// </para>
/// <para>
/// <note type="important">
/// It is not possible to retrieve the message via
/// <see cref="Cacheable{TEntity,TId}.DownloadAsync"/>; the message cannot be retrieved by Discord
/// after the message has been deleted.
/// </note>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the deleted message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The source channel of the removed message will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// </remarks>
public event Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, ISocketMessageChannel, Task> MessagesBulkDeleted
{
add { _messagesBulkDeletedEvent.Add(value); }
remove { _messagesBulkDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, ISocketMessageChannel, Task>> _messagesBulkDeletedEvent = new AsyncEvent<Func<IReadOnlyCollection<Cacheable<IMessage, ulong>>, ISocketMessageChannel, Task>>();
/// <summary> Fired when a message is updated. </summary>
/// <remarks>
/// <para>
/// This event is fired when a message is updated. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, <see cref="SocketMessage"/>,
/// and <see cref="ISocketMessageChannel"/> as its parameters.
/// </para>
/// <para>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The updated message will be passed into the <see cref="SocketMessage"/> parameter.
/// </para>
/// <para>
/// The source channel of the updated message will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// </remarks>
public event Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task> MessageUpdated {
add { _messageUpdatedEvent.Add(value); }
remove { _messageUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task>> _messageUpdatedEvent = new AsyncEvent<Func<Cacheable<IMessage, ulong>, SocketMessage, ISocketMessageChannel, Task>>();
/// <summary> Fired when a reaction is added to a message. </summary>
/// <remarks>
/// <para>
/// This event is fired when a reaction is added to a user message. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="Cacheable{TEntity,TId}"/>, an
/// <see cref="ISocketMessageChannel"/>, and a <see cref="SocketReaction"/> as its parameter.
/// </para>
/// <para>
/// If caching is enabled via <see cref="DiscordSocketConfig"/>, the
/// <see cref="Cacheable{TEntity,TId}"/> entity will contain the original message; otherwise, in event
/// that the message cannot be retrieved, the snowflake ID of the message is preserved in the
/// <see cref="ulong"/>.
/// </para>
/// <para>
/// The source channel of the reaction addition will be passed into the
/// <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// <para>
/// The reaction that was added will be passed into the <see cref="SocketReaction"/> parameter.
/// </para>
/// <note>
/// When fetching the reaction from this event, a user may not be provided under
/// <see cref="SocketReaction.User"/>. Please see the documentation of the property for more
/// information.
/// </note>
/// </remarks>
/// <example>
/// <code language="cs" region="ReactionAdded"
/// source="..\Discord.Net.Examples\WebSocket\BaseSocketClient.Events.Examples.cs"/>
/// </example>
public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> ReactionAdded {
add { _reactionAddedEvent.Add(value); }
remove { _reactionAddedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>> _reactionAddedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>>();
/// <summary> Fired when a reaction is removed from a message. </summary>
public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> ReactionRemoved {
add { _reactionRemovedEvent.Add(value); }
remove { _reactionRemovedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>> _reactionRemovedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>>();
/// <summary> Fired when all reactions to a message are cleared. </summary>
public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, Task> ReactionsCleared {
add { _reactionsClearedEvent.Add(value); }
remove { _reactionsClearedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, Task>> _reactionsClearedEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, Task>>();
/// <summary>
/// Fired when all reactions to a message with a specific emote are removed.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when all reactions to a message with a specific emote are removed.
/// The event handler must return a <see cref="Task"/> and accept a <see cref="ISocketMessageChannel"/> and
/// a <see cref="IEmote"/> as its parameters.
/// </para>
/// <para>
/// The channel where this message was sent will be passed into the <see cref="ISocketMessageChannel"/> parameter.
/// </para>
/// <para>
/// The emoji that all reactions had and were removed will be passed into the <see cref="IEmote"/> parameter.
/// </para>
/// </remarks>
public event Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, IEmote, Task> ReactionsRemovedForEmote
{
add { _reactionsRemovedForEmoteEvent.Add(value); }
remove { _reactionsRemovedForEmoteEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, IEmote, Task>> _reactionsRemovedForEmoteEvent = new AsyncEvent<Func<Cacheable<IUserMessage, ulong>, ISocketMessageChannel, IEmote, Task>>();
//Roles
/// <summary> Fired when a role is created. </summary>
public event Func<SocketRole, Task> RoleCreated {
add { _roleCreatedEvent.Add(value); }
remove { _roleCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketRole, Task>> _roleCreatedEvent = new AsyncEvent<Func<SocketRole, Task>>();
/// <summary> Fired when a role is deleted. </summary>
public event Func<SocketRole, Task> RoleDeleted {
add { _roleDeletedEvent.Add(value); }
remove { _roleDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketRole, Task>> _roleDeletedEvent = new AsyncEvent<Func<SocketRole, Task>>();
/// <summary> Fired when a role is updated. </summary>
public event Func<SocketRole, SocketRole, Task> RoleUpdated {
add { _roleUpdatedEvent.Add(value); }
remove { _roleUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketRole, SocketRole, Task>> _roleUpdatedEvent = new AsyncEvent<Func<SocketRole, SocketRole, Task>>();
//Guilds
/// <summary> Fired when the connected account joins a guild. </summary>
public event Func<SocketGuild, Task> JoinedGuild {
add { _joinedGuildEvent.Add(value); }
remove { _joinedGuildEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _joinedGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when the connected account leaves a guild. </summary>
public event Func<SocketGuild, Task> LeftGuild {
add { _leftGuildEvent.Add(value); }
remove { _leftGuildEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _leftGuildEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when a guild becomes available. </summary>
public event Func<SocketGuild, Task> GuildAvailable {
add { _guildAvailableEvent.Add(value); }
remove { _guildAvailableEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildAvailableEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when a guild becomes unavailable. </summary>
public event Func<SocketGuild, Task> GuildUnavailable {
add { _guildUnavailableEvent.Add(value); }
remove { _guildUnavailableEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildUnavailableEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when offline guild members are downloaded. </summary>
public event Func<SocketGuild, Task> GuildMembersDownloaded {
add { _guildMembersDownloadedEvent.Add(value); }
remove { _guildMembersDownloadedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, Task>> _guildMembersDownloadedEvent = new AsyncEvent<Func<SocketGuild, Task>>();
/// <summary> Fired when a guild is updated. </summary>
public event Func<SocketGuild, SocketGuild, Task> GuildUpdated {
add { _guildUpdatedEvent.Add(value); }
remove { _guildUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuild, SocketGuild, Task>> _guildUpdatedEvent = new AsyncEvent<Func<SocketGuild, SocketGuild, Task>>();
//Users
/// <summary> Fired when a user joins a guild. </summary>
public event Func<SocketGuildUser, Task> UserJoined {
add { _userJoinedEvent.Add(value); }
remove { _userJoinedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildUser, Task>> _userJoinedEvent = new AsyncEvent<Func<SocketGuildUser, Task>>();
/// <summary> Fired when a user leaves a guild. </summary>
public event Func<SocketGuildUser, Task> UserLeft {
add { _userLeftEvent.Add(value); }
remove { _userLeftEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildUser, Task>> _userLeftEvent = new AsyncEvent<Func<SocketGuildUser, Task>>();
/// <summary> Fired when a user is banned from a guild. </summary>
public event Func<SocketUser, SocketGuild, Task> UserBanned {
add { _userBannedEvent.Add(value); }
remove { _userBannedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userBannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>();
/// <summary> Fired when a user is unbanned from a guild. </summary>
public event Func<SocketUser, SocketGuild, Task> UserUnbanned {
add { _userUnbannedEvent.Add(value); }
remove { _userUnbannedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketGuild, Task>> _userUnbannedEvent = new AsyncEvent<Func<SocketUser, SocketGuild, Task>>();
/// <summary> Fired when a user is updated. </summary>
public event Func<SocketUser, SocketUser, Task> UserUpdated {
add { _userUpdatedEvent.Add(value); }
remove { _userUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketUser, Task>> _userUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketUser, Task>>();
/// <summary> Fired when a guild member is updated, or a member presence is updated. </summary>
public event Func<SocketGuildUser, SocketGuildUser, Task> GuildMemberUpdated {
add { _guildMemberUpdatedEvent.Add(value); }
remove { _guildMemberUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildUser, SocketGuildUser, Task>> _guildMemberUpdatedEvent = new AsyncEvent<Func<SocketGuildUser, SocketGuildUser, Task>>();
/// <summary> Fired when a user joins, leaves, or moves voice channels. </summary>
public event Func<SocketUser, SocketVoiceState, SocketVoiceState, Task> UserVoiceStateUpdated {
add { _userVoiceStateUpdatedEvent.Add(value); }
remove { _userVoiceStateUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>> _userVoiceStateUpdatedEvent = new AsyncEvent<Func<SocketUser, SocketVoiceState, SocketVoiceState, Task>>();
/// <summary> Fired when the bot connects to a Discord voice server. </summary>
public event Func<SocketVoiceServer, Task> VoiceServerUpdated
{
add { _voiceServerUpdatedEvent.Add(value); }
remove { _voiceServerUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketVoiceServer, Task>> _voiceServerUpdatedEvent = new AsyncEvent<Func<SocketVoiceServer, Task>>();
/// <summary> Fired when the connected account is updated. </summary>
public event Func<SocketSelfUser, SocketSelfUser, Task> CurrentUserUpdated {
add { _selfUpdatedEvent.Add(value); }
remove { _selfUpdatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>> _selfUpdatedEvent = new AsyncEvent<Func<SocketSelfUser, SocketSelfUser, Task>>();
/// <summary> Fired when a user starts typing. </summary>
public event Func<SocketUser, ISocketMessageChannel, Task> UserIsTyping {
add { _userIsTypingEvent.Add(value); }
remove { _userIsTypingEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketUser, ISocketMessageChannel, Task>> _userIsTypingEvent = new AsyncEvent<Func<SocketUser, ISocketMessageChannel, Task>>();
/// <summary> Fired when a user joins a group channel. </summary>
public event Func<SocketGroupUser, Task> RecipientAdded {
add { _recipientAddedEvent.Add(value); }
remove { _recipientAddedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientAddedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>();
/// <summary> Fired when a user is removed from a group channel. </summary>
public event Func<SocketGroupUser, Task> RecipientRemoved {
add { _recipientRemovedEvent.Add(value); }
remove { _recipientRemovedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGroupUser, Task>> _recipientRemovedEvent = new AsyncEvent<Func<SocketGroupUser, Task>>();
//Invites
/// <summary>
/// Fired when an invite is created.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an invite is created. The event handler must return a
/// <see cref="Task"/> and accept a <see cref="SocketInvite"/> as its parameter.
/// </para>
/// <para>
/// The invite created will be passed into the <see cref="SocketInvite"/> parameter.
/// </para>
/// </remarks>
public event Func<SocketInvite, Task> InviteCreated
{
add { _inviteCreatedEvent.Add(value); }
remove { _inviteCreatedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketInvite, Task>> _inviteCreatedEvent = new AsyncEvent<Func<SocketInvite, Task>>();
/// <summary>
/// Fired when an invite is deleted.
/// </summary>
/// <remarks>
/// <para>
/// This event is fired when an invite is deleted. The event handler must return
/// a <see cref="Task"/> and accept a <see cref="SocketGuildChannel"/> and
/// <see cref="string"/> as its parameter.
/// </para>
/// <para>
/// The channel where this invite was created will be passed into the <see cref="SocketGuildChannel"/> parameter.
/// </para>
/// <para>
/// The code of the deleted invite will be passed into the <see cref="string"/> parameter.
/// </para>
/// </remarks>
public event Func<SocketGuildChannel, string, Task> InviteDeleted
{
add { _inviteDeletedEvent.Add(value); }
remove { _inviteDeletedEvent.Remove(value); }
}
internal readonly AsyncEvent<Func<SocketGuildChannel, string, Task>> _inviteDeletedEvent = new AsyncEvent<Func<SocketGuildChannel, string, Task>>();
}
}
| |
/*
* Copyright 2006 Jeremias Maerki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.Datamatrix.Encoder
{
/// <summary>
/// Symbol info table for DataMatrix.
/// </summary>
public class SymbolInfo
{
internal static readonly SymbolInfo[] PROD_SYMBOLS = {
new SymbolInfo(false, 3, 5, 8, 8, 1),
new SymbolInfo(false, 5, 7, 10, 10, 1),
/*rect*/new SymbolInfo(true, 5, 7, 16, 6, 1),
new SymbolInfo(false, 8, 10, 12, 12, 1),
/*rect*/new SymbolInfo(true, 10, 11, 14, 6, 2),
new SymbolInfo(false, 12, 12, 14, 14, 1),
/*rect*/new SymbolInfo(true, 16, 14, 24, 10, 1),
new SymbolInfo(false, 18, 14, 16, 16, 1),
new SymbolInfo(false, 22, 18, 18, 18, 1),
/*rect*/new SymbolInfo(true, 22, 18, 16, 10, 2),
new SymbolInfo(false, 30, 20, 20, 20, 1),
/*rect*/new SymbolInfo(true, 32, 24, 16, 14, 2),
new SymbolInfo(false, 36, 24, 22, 22, 1),
new SymbolInfo(false, 44, 28, 24, 24, 1),
/*rect*/new SymbolInfo(true, 49, 28, 22, 14, 2),
new SymbolInfo(false, 62, 36, 14, 14, 4),
new SymbolInfo(false, 86, 42, 16, 16, 4),
new SymbolInfo(false, 114, 48, 18, 18, 4),
new SymbolInfo(false, 144, 56, 20, 20, 4),
new SymbolInfo(false, 174, 68, 22, 22, 4),
new SymbolInfo(false, 204, 84, 24, 24, 4, 102, 42),
new SymbolInfo(false, 280, 112, 14, 14, 16, 140, 56),
new SymbolInfo(false, 368, 144, 16, 16, 16, 92, 36),
new SymbolInfo(false, 456, 192, 18, 18, 16, 114, 48),
new SymbolInfo(false, 576, 224, 20, 20, 16, 144, 56),
new SymbolInfo(false, 696, 272, 22, 22, 16, 174, 68),
new SymbolInfo(false, 816, 336, 24, 24, 16, 136, 56),
new SymbolInfo(false, 1050, 408, 18, 18, 36, 175, 68),
new SymbolInfo(false, 1304, 496, 20, 20, 36, 163, 62),
new DataMatrixSymbolInfo144(),
};
private static SymbolInfo[] symbols = PROD_SYMBOLS;
/**
* Overrides the symbol info set used by this class. Used for testing purposes.
*
* @param override the symbol info set to use
*/
public static void overrideSymbolSet(SymbolInfo[] @override)
{
symbols = @override;
}
private readonly bool rectangular;
internal readonly int dataCapacity;
internal readonly int errorCodewords;
public readonly int matrixWidth;
public readonly int matrixHeight;
private readonly int dataRegions;
private readonly int rsBlockData;
private readonly int rsBlockError;
public SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords,
int matrixWidth, int matrixHeight, int dataRegions)
: this(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions,
dataCapacity, errorCodewords)
{
}
internal SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords,
int matrixWidth, int matrixHeight, int dataRegions,
int rsBlockData, int rsBlockError)
{
this.rectangular = rectangular;
this.dataCapacity = dataCapacity;
this.errorCodewords = errorCodewords;
this.matrixWidth = matrixWidth;
this.matrixHeight = matrixHeight;
this.dataRegions = dataRegions;
this.rsBlockData = rsBlockData;
this.rsBlockError = rsBlockError;
}
public static SymbolInfo lookup(int dataCodewords)
{
return lookup(dataCodewords, SymbolShapeHint.FORCE_NONE, true);
}
public static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape)
{
return lookup(dataCodewords, shape, true);
}
public static SymbolInfo lookup(int dataCodewords, bool allowRectangular, bool fail)
{
SymbolShapeHint shape = allowRectangular
? SymbolShapeHint.FORCE_NONE : SymbolShapeHint.FORCE_SQUARE;
return lookup(dataCodewords, shape, fail);
}
private static SymbolInfo lookup(int dataCodewords, SymbolShapeHint shape, bool fail)
{
return lookup(dataCodewords, shape, null, null, fail);
}
public static SymbolInfo lookup(int dataCodewords,
SymbolShapeHint shape,
Dimension minSize,
Dimension maxSize,
bool fail)
{
foreach (SymbolInfo symbol in symbols)
{
if (shape == SymbolShapeHint.FORCE_SQUARE && symbol.rectangular)
{
continue;
}
if (shape == SymbolShapeHint.FORCE_RECTANGLE && !symbol.rectangular)
{
continue;
}
if (minSize != null
&& (symbol.getSymbolWidth() < minSize.Width
|| symbol.getSymbolHeight() < minSize.Height))
{
continue;
}
if (maxSize != null
&& (symbol.getSymbolWidth() > maxSize.Width
|| symbol.getSymbolHeight() > maxSize.Height))
{
continue;
}
if (dataCodewords <= symbol.dataCapacity)
{
return symbol;
}
}
if (fail)
{
throw new ArgumentException(
"Can't find a symbol arrangement that matches the message. Data codewords: "
+ dataCodewords);
}
return null;
}
int getHorizontalDataRegions()
{
switch (dataRegions)
{
case 1:
return 1;
case 2:
return 2;
case 4:
return 2;
case 16:
return 4;
case 36:
return 6;
default:
throw new InvalidOperationException("Cannot handle this number of data regions");
}
}
int getVerticalDataRegions()
{
switch (dataRegions)
{
case 1:
return 1;
case 2:
return 1;
case 4:
return 2;
case 16:
return 4;
case 36:
return 6;
default:
throw new InvalidOperationException("Cannot handle this number of data regions");
}
}
public int getSymbolDataWidth()
{
return getHorizontalDataRegions() * matrixWidth;
}
public int getSymbolDataHeight()
{
return getVerticalDataRegions() * matrixHeight;
}
public int getSymbolWidth()
{
return getSymbolDataWidth() + (getHorizontalDataRegions() * 2);
}
public int getSymbolHeight()
{
return getSymbolDataHeight() + (getVerticalDataRegions() * 2);
}
public int getCodewordCount()
{
return dataCapacity + errorCodewords;
}
virtual public int getInterleavedBlockCount()
{
return dataCapacity / rsBlockData;
}
virtual public int getDataLengthForInterleavedBlock(int index)
{
return rsBlockData;
}
public int getErrorLengthForInterleavedBlock(int index)
{
return rsBlockError;
}
public override String ToString()
{
var sb = new StringBuilder();
sb.Append(rectangular ? "Rectangular Symbol:" : "Square Symbol:");
sb.Append(" data region ").Append(matrixWidth).Append('x').Append(matrixHeight);
sb.Append(", symbol size ").Append(getSymbolWidth()).Append('x').Append(getSymbolHeight());
sb.Append(", symbol data size ").Append(getSymbolDataWidth()).Append('x').Append(getSymbolDataHeight());
sb.Append(", codewords ").Append(dataCapacity).Append('+').Append(errorCodewords);
return sb.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;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
namespace TestLibrary
{
public static class Generator
{
internal static Random m_rand = new Random();
internal static int? seed = null;
public static int? Seed
{
get
{
if (seed.HasValue)
{
return seed.Value;
}
else
{
return null;
}
}
set
{
if (!(seed.HasValue))
{
seed = value;
if (seed.HasValue)
{
m_rand = new Random(seed.Value);
}
}
}
}
// returns a byte array of random data
public static void GetBytes(int new_seed, byte[] buffer)
{
Seed = new_seed;
GetBytes(buffer);
}
public static void GetBytes(byte[] buffer)
{
m_rand.NextBytes(buffer);
}
// returns a non-negative Int64 between 0 and Int64.MaxValue
public static Int64 GetInt64(Int32 new_seed)
{
Seed = new_seed;
return GetInt64();
}
public static Int64 GetInt64()
{
byte[] buffer = new byte[8];
Int64 iVal;
GetBytes(buffer);
// convert to Int64
iVal = 0;
for (int i = 0; i < buffer.Length; i++)
{
iVal |= ((Int64)buffer[i] << (i * 8));
}
if (0 > iVal) iVal *= -1;
return iVal;
}
// returns a non-negative Int32 between 0 and Int32.MaxValue
public static Int32 GetInt32(Int32 new_seed)
{
Seed = new_seed;
return GetInt32();
}
public static Int32 GetInt32()
{
Int32 i = m_rand.Next();
return i;
}
// returns a non-negative Int16 between 0 and Int16.MaxValue
public static Int16 GetInt16(Int32 new_seed)
{
Seed = new_seed;
return GetInt16();
}
public static Int16 GetInt16()
{
Int16 i = Convert.ToInt16(m_rand.Next() % (1 + Int16.MaxValue));
return i;
}
// returns a non-negative Byte between 0 and Byte.MaxValue
public static Byte GetByte(Int32 new_seed)
{
Seed = new_seed;
return GetByte();
}
public static Byte GetByte()
{
Byte i = Convert.ToByte(m_rand.Next() % (1 + Byte.MaxValue));
return i;
}
// returns a non-negative Double between 0.0 and 1.0
public static Double GetDouble(Int32 new_seed)
{
Seed = new_seed;
return GetDouble();
}
public static Double GetDouble()
{
Double i = m_rand.NextDouble();
return i;
}
// returns a non-negative Single between 0.0 and 1.0
public static Single GetSingle(Int32 new_seed)
{
Seed = new_seed;
return GetSingle();
}
public static Single GetSingle()
{
Single i = Convert.ToSingle(m_rand.NextDouble());
return i;
}
// returns a valid char that is a letter
public static Char GetCharLetter(Int32 new_seed)
{
Seed = new_seed;
return GetCharLetter();
}
public static Char GetCharLetter()
{
return GetCharLetter(true);
}
// returns a valid char that is a letter
// if allowsurrogate is true then surrogates are valid return values
public static Char GetCharLetter(Int32 new_seed, bool allowsurrogate)
{
Seed = new_seed;
return GetCharLetter(allowsurrogate);
}
public static Char GetCharLetter(bool allowsurrogate)
{
return GetCharLetter(allowsurrogate, true);
}
// returns a valid char that is a letter
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight is true, then no-weight characters are valid return values
public static Char GetCharLetter(Int32 new_seed, bool allowsurrogate, bool allownoweight)
{
Seed = new_seed;
return GetCharLetter(allowsurrogate, allownoweight);
}
public static Char GetCharLetter(bool allowsurrogate, bool allownoweight)
{
Int16 iVal;
Char c = 'a';
Int32 counter;
bool loopCondition = true;
// attempt to randomly find a letter
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allownoweight)
{
throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = allowsurrogate ? (!Char.IsLetter(c)) : (!Char.IsLetter(c) || Char.IsSurrogate(c));
}
while (loopCondition && 0 < counter);
if (!Char.IsLetter(c))
{
// we tried and failed to get a letter
// Grab an ASCII letter
c = Convert.ToChar(GetInt16() % 26 + 'A');
}
return c;
}
// returns a valid char that is a number
public static char GetCharNumber(Int32 new_seed)
{
Seed = new_seed;
return GetCharNumber();
}
public static char GetCharNumber()
{
return GetCharNumber(true);
}
// returns a valid char that is a number
// if allownoweight is true, then no-weight characters are valid return values
public static char GetCharNumber(Int32 new_seed, bool allownoweight)
{
Seed = new_seed;
return GetCharNumber(allownoweight);
}
public static char GetCharNumber(bool allownoweight)
{
Char c = '0';
Int32 counter;
Int16 iVal;
bool loopCondition = true;
// attempt to randomly find a number
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allownoweight)
{
throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = !Char.IsNumber(c);
}
while (loopCondition && 0 < counter);
if (!Char.IsNumber(c))
{
// we tried and failed to get a letter
// Grab an ASCII number
c = Convert.ToChar(GetInt16() % 10 + '0');
}
return c;
}
// returns a valid char
public static Char GetChar(Int32 new_seed)
{
Seed = new_seed;
return GetChar();
}
public static Char GetChar()
{
return GetChar(true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
public static Char GetChar(Int32 new_seed, bool allowsurrogate)
{
Seed = new_seed;
return GetChar(allowsurrogate);
}
public static Char GetChar(bool allowsurrogate)
{
return GetChar(allowsurrogate, true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight characters then noweight characters are valid return values
public static Char GetChar(Int32 new_seed, bool allowsurrogate, bool allownoweight)
{
Seed = new_seed;
return GetChar(allowsurrogate, allownoweight);
}
public static Char GetChar(bool allowsurrogate, bool allownoweight)
{
Int16 iVal = GetInt16();
Char c = (char)(iVal);
if (!Char.IsLetter(c))
{
// we tried and failed to get a letter
// Just grab an ASCII letter
c = (char)(GetInt16() % 26 + 'A');
}
return c;
}
// returns a string. If "validPath" is set, only valid path characters
// will be included
public static string GetString(Int32 new_seed, Boolean validPath, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetString(validPath, minLength, maxLength);
}
public static string GetString(Boolean validPath, Int32 minLength, Int32 maxLength)
{
return GetString(validPath, true, true, minLength, maxLength);
}
public static string GetString(Int32 new_seed, Boolean validPath, Boolean allowNulls, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetString(validPath, allowNulls, minLength, maxLength);
}
public static string GetString(Boolean validPath, Boolean allowNulls, Int32 minLength, Int32 maxLength)
{
return GetString(validPath, allowNulls, true, minLength, maxLength);
}
public static string GetString(Int32 new_seed, Boolean validPath, Boolean allowNulls, Boolean allowNoWeight, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength);
}
public static string GetString(Boolean validPath, Boolean allowNulls, Boolean allowNoWeight, Int32 minLength, Int32 maxLength)
{
StringBuilder sVal = new StringBuilder();
Char c;
Int32 length;
if (0 == minLength && 0 == maxLength) return String.Empty;
if (minLength > maxLength) return null;
length = minLength;
if (minLength != maxLength)
{
length = (GetInt32() % (maxLength - minLength)) + minLength;
}
for (int i = 0; length > i; i++)
{
if (validPath)
{
if (0 == (GetByte() % 2))
{
c = GetCharLetter(true, allowNoWeight);
}
else
{
c = GetCharNumber(allowNoWeight);
}
}
else if (!allowNulls)
{
do
{
c = GetChar(true, allowNoWeight);
} while (c == '\u0000');
}
else
{
c = GetChar(true, allowNoWeight);
}
sVal.Append(c);
}
string s = sVal.ToString();
return s;
}
public static string[] GetStrings(Int32 new_seed, Boolean validPath, Int32 minLength, Int32 maxLength)
{
Seed = new_seed;
return GetStrings(validPath, minLength, maxLength);
}
public static string[] GetStrings(Boolean validPath, Int32 minLength, Int32 maxLength)
{
string validString;
const char c_LATIN_A = '\u0100';
const char c_LOWER_A = 'a';
const char c_UPPER_A = 'A';
const char c_ZERO_WEIGHT = '\uFEFF';
const char c_DOUBLE_WIDE_A = '\uFF21';
const string c_SURROGATE_UPPER = "\uD801\uDC00";
const string c_SURROGATE_LOWER = "\uD801\uDC28";
const char c_LOWER_SIGMA1 = (char)0x03C2;
const char c_LOWER_SIGMA2 = (char)0x03C3;
const char c_UPPER_SIGMA = (char)0x03A3;
const char c_SPACE = ' ';
int numConsts = 12;
string[] retStrings;
if (2 >= minLength && 2 >= maxLength || minLength > maxLength) return null;
retStrings = new string[numConsts];
validString = TestLibrary.Generator.GetString(validPath, minLength - 1, maxLength - 1);
retStrings[0] = TestLibrary.Generator.GetString(validPath, minLength, maxLength);
retStrings[1] = validString + c_LATIN_A;
retStrings[2] = validString + c_LOWER_A;
retStrings[3] = validString + c_UPPER_A;
retStrings[4] = validString + c_ZERO_WEIGHT;
retStrings[5] = validString + c_DOUBLE_WIDE_A;
retStrings[6] = TestLibrary.Generator.GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER;
retStrings[7] = TestLibrary.Generator.GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER;
retStrings[8] = validString + c_LOWER_SIGMA1;
retStrings[9] = validString + c_LOWER_SIGMA2;
retStrings[10] = validString + c_UPPER_SIGMA;
retStrings[11] = validString + c_SPACE;
return retStrings;
}
public static object GetType(Type t)
{
return Activator.CreateInstance(t);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Tests
{
public class ToDictionaryTests : EnumerableTests
{
private class CustomComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y) { return EqualityComparer<T>.Default.Equals(x, y); }
public int GetHashCode(T obj) { return EqualityComparer<T>.Default.GetHashCode(obj); }
}
[Fact]
public void ToDictionary_AlwaysCreateACopy()
{
Dictionary<int, int> source = new Dictionary<int, int>() { { 1, 1 }, { 2, 2 }, { 3, 3 } };
Dictionary<int, int> result = source.ToDictionary(key => key.Key, val => val.Value);
Assert.NotSame(source, result);
Assert.Equal(source, result);
}
private void RunToDictionaryOnAllCollectionTypes<T>(T[] items, Action<Dictionary<T, T>> validation)
{
validation(Enumerable.ToDictionary(items, key => key));
validation(Enumerable.ToDictionary(items, key => key, value => value));
validation(Enumerable.ToDictionary(new List<T>(items), key => key));
validation(Enumerable.ToDictionary(new List<T>(items), key => key, value => value));
validation(new TestEnumerable<T>(items).ToDictionary(key => key));
validation(new TestEnumerable<T>(items).ToDictionary(key => key, value => value));
validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key));
validation(new TestReadOnlyCollection<T>(items).ToDictionary(key => key, value => value));
validation(new TestCollection<T>(items).ToDictionary(key => key));
validation(new TestCollection<T>(items).ToDictionary(key => key, value => value));
}
[Fact]
public void ToDictionary_WorkWithEmptyCollection()
{
RunToDictionaryOnAllCollectionTypes(new int[0],
resultDictionary =>
{
Assert.NotNull(resultDictionary);
Assert.Equal(0, resultDictionary.Count);
});
}
[Fact]
public void ToDictionary_ProduceCorrectDictionary()
{
int[] sourceArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
RunToDictionaryOnAllCollectionTypes(sourceArray,
resultDictionary =>
{
Assert.Equal(sourceArray.Length, resultDictionary.Count);
Assert.Equal(sourceArray, resultDictionary.Keys);
Assert.Equal(sourceArray, resultDictionary.Values);
});
string[] sourceStringArray = new string[] { "1", "2", "3", "4", "5", "6", "7", "8" };
RunToDictionaryOnAllCollectionTypes(sourceStringArray,
resultDictionary =>
{
Assert.Equal(sourceStringArray.Length, resultDictionary.Count);
for (int i = 0; i < sourceStringArray.Length; i++)
Assert.Same(sourceStringArray[i], resultDictionary[sourceStringArray[i]]);
});
}
[Fact]
public void RunOnce()
{
Assert.Equal(
new Dictionary<int, string> {{1, "0"}, {2, "1"}, {3, "2"}, {4, "3"}},
Enumerable.Range(0, 4).RunOnce().ToDictionary(i => i + 1, i => i.ToString()));
}
[Fact]
public void ToDictionary_PassCustomComparer()
{
CustomComparer<int> comparer = new CustomComparer<int>();
TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 });
Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer);
Assert.Same(comparer, result1.Comparer);
Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer);
Assert.Same(comparer, result2.Comparer);
}
[Fact]
public void ToDictionary_UseDefaultComparerOnNull()
{
CustomComparer<int> comparer = null;
TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 });
Dictionary<int, int> result1 = collection.ToDictionary(key => key, comparer);
Assert.Same(EqualityComparer<int>.Default, result1.Comparer);
Dictionary<int, int> result2 = collection.ToDictionary(key => key, val => val, comparer);
Assert.Same(EqualityComparer<int>.Default, result2.Comparer);
}
[Fact]
public void ToDictionary_KeyValueSelectorsWork()
{
TestCollection<int> collection = new TestCollection<int>(new int[] { 1, 2, 3, 4, 5, 6 });
Dictionary<int, int> result = collection.ToDictionary(key => key + 10, val => val + 100);
Assert.Equal(collection.Items.Select(o => o + 10), result.Keys);
Assert.Equal(collection.Items.Select(o => o + 100), result.Values);
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNull()
{
int[] source = null;
Assert.Throws<ArgumentNullException>("source", () => source.ToDictionary(key => key));
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNull()
{
int[] source = new int[0];
Func<int, int> keySelector = null;
Assert.Throws<ArgumentNullException>("keySelector", () => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenValueSelectorIsNull()
{
int[] source = new int[0];
Func<int, int> keySelector = key => key;
Func<int, int> valueSelector = null;
Assert.Throws<ArgumentNullException>("elementSelector", () => source.ToDictionary(keySelector, valueSelector));
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenSourceIsNullElementSelector()
{
int[] source = null;
Assert.Throws<ArgumentNullException>("source", () => source.ToDictionary(key => key, e => e));
}
[Fact]
public void ToDictionary_ThrowArgumentNullExceptionWhenKeySelectorIsNullElementSelector()
{
int[] source = new int[0];
Func<int, int> keySelector = null;
Assert.Throws<ArgumentNullException>("keySelector", () => source.ToDictionary(keySelector, e => e));
}
[Fact]
public void ToDictionary_KeySelectorThrowException()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, int> keySelector = key =>
{
if (key == 1)
throw new InvalidOperationException();
return key;
};
Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ThrowWhenKeySelectorReturnNull()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, string> keySelector = key => null;
Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ThrowWhenKeySelectorReturnSameValueTwice()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, int> keySelector = key => 1;
Assert.Throws<ArgumentException>(() => source.ToDictionary(keySelector));
}
[Fact]
public void ToDictionary_ValueSelectorThrowException()
{
int[] source = new int[] { 1, 2, 3 };
Func<int, int> keySelector = key => key;
Func<int, int> valueSelector = value =>
{
if (value == 1)
throw new InvalidOperationException();
return value;
};
Assert.Throws<InvalidOperationException>(() => source.ToDictionary(keySelector, valueSelector));
}
[Fact]
public void ThrowsOnNullKey()
{
var source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = "null", Score = 55 }
};
source.ToDictionary(e => e.Name); // Doesn't throw;
source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = default(string), Score = 55 }
};
Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name));
}
[Fact]
public void ThrowsOnNullKeyCustomComparer()
{
var source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = "null", Score = 55 }
};
source.ToDictionary(e => e.Name, new AnagramEqualityComparer()); // Doesn't throw;
source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = default(string), Score = 55 }
};
Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, new AnagramEqualityComparer()));
}
[Fact]
public void ThrowsOnNullKeyValueSelector()
{
var source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = "null", Score = 55 }
};
source.ToDictionary(e => e.Name, e => e); // Doesn't throw;
source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = default(string), Score = 55 }
};
Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, e => e));
}
[Fact]
public void ThrowsOnNullKeyCustomComparerValueSelector()
{
var source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = "null", Score = 55 }
};
source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer()); // Doesn't throw;
source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = default(string), Score = 55 }
};
Assert.Throws<ArgumentNullException>("key", () => source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer()));
}
[Fact]
public void ThrowsOnDuplicateKeys()
{
var source = new[]
{
new { Name = "Chris", Score = 50 },
new { Name = "Bob", Score = 95 },
new { Name = "Bob", Score = 55 }
};
Assert.Throws<ArgumentException>(() => source.ToDictionary(e => e.Name, e => e, new AnagramEqualityComparer()));
}
private static void AssertMatches<K, E>(IEnumerable<K> keys, IEnumerable<E> values, Dictionary<K, E> dict)
{
Assert.NotNull(dict);
Assert.NotNull(keys);
Assert.NotNull(values);
using (var ke = keys.GetEnumerator())
{
foreach(var value in values)
{
Assert.True(ke.MoveNext());
var key = ke.Current;
E dictValue;
Assert.True(dict.TryGetValue(key, out dictValue));
Assert.Equal(value, dictValue);
dict.Remove(key);
}
Assert.False(ke.MoveNext());
Assert.Equal(0, dict.Count());
}
}
[Fact]
public void EmtpySource()
{
int[] elements = new int[] { };
string[] keys = new string[] { };
var source = keys.Zip(elements, (k, e) => new { Name = k, Score = e });
AssertMatches(keys, elements, source.ToDictionary(e => e.Name, e => e.Score, new AnagramEqualityComparer()));
}
[Fact]
public void OneElementNullComparer()
{
int[] elements = new int[] { 5 };
string[] keys = new string[] { "Bob" };
var source = new [] { new { Name = keys[0], Score = elements[0] } };
AssertMatches(keys, elements, source.ToDictionary(e => e.Name, e => e.Score, null));
}
[Fact]
public void SeveralElementsCustomComparerer()
{
string[] keys = new string[] { "Bob", "Zen", "Prakash", "Chris", "Sachin" };
var source = new []
{
new { Name = "Bbo", Score = 95 },
new { Name = keys[1], Score = 45 },
new { Name = keys[2], Score = 100 },
new { Name = keys[3], Score = 90 },
new { Name = keys[4], Score = 45 }
};
AssertMatches(keys, source, source.ToDictionary(e => e.Name, new AnagramEqualityComparer()));
}
[Fact]
public void NullCoalescedKeySelector()
{
string[] elements = new string[] { null };
string[] keys = new string[] { string.Empty };
string[] source = new string[] { null };
AssertMatches(keys, elements, source.ToDictionary(e => e ?? string.Empty, e => e, EqualityComparer<string>.Default));
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEditor.Experimental.VFX;
using UnityEngine.Experimental.VFX;
using UnityEngine.UIElements;
namespace UnityEditor.VFX.UI
{
class VFXCopyPaste
{
[System.Serializable]
struct DataAnchor
{
public int targetIndex;
public int[] slotPath;
}
[System.Serializable]
struct DataEdge
{
public bool inputContext;
public bool outputParameter;
public int inputBlockIndex;
public int outputParameterIndex;
public int outputParameterNodeIndex;
public DataAnchor input;
public DataAnchor output;
}
[System.Serializable]
struct FlowAnchor
{
public int contextIndex;
public int flowIndex;
}
[System.Serializable]
struct FlowEdge
{
public FlowAnchor input;
public FlowAnchor output;
}
[System.Serializable]
struct DataAndContexts
{
public int dataIndex;
public int[] contextsIndexes;
}
[System.Serializable]
struct Parameter
{
public int originalInstanceID;
[NonSerialized]
public VFXParameter parameter;
[NonSerialized]
public VFXParameter copiedParameter;
public int index;
public int infoIndexOffset;
public VFXParameter.Node[] infos;
[NonSerialized]
public Dictionary<int, int> idMap;
}
[System.Serializable]
class Data
{
public string serializedObjects;
public Rect bounds;
public bool blocksOnly;
[NonSerialized]
public VFXContext[] contexts;
[NonSerialized]
public VFXModel[] slotContainers;
[NonSerialized]
public VFXBlock[] blocks;
public Parameter[] parameters;
public DataAndContexts[] dataAndContexts;
public DataEdge[] dataEdges;
public FlowEdge[] flowEdges;
public void CollectDependencies(HashSet<ScriptableObject> objects)
{
if (contexts != null)
{
foreach (var context in contexts)
{
objects.Add(context);
context.CollectDependencies(objects);
}
}
if (slotContainers != null)
{
foreach (var slotContainer in slotContainers)
{
objects.Add(slotContainer);
slotContainer.CollectDependencies(objects);
}
}
if (blocks != null)
{
foreach (var block in blocks)
{
objects.Add(block);
block.CollectDependencies(objects);
}
}
}
}
static ScriptableObject[] PrepareSerializedObjects(Data copyData, VFXUI optionalUI)
{
var objects = new HashSet<ScriptableObject>();
copyData.CollectDependencies(objects);
if (optionalUI != null)
{
objects.Add(optionalUI);
}
ScriptableObject[] allSerializedObjects = objects.OfType<ScriptableObject>().ToArray();
copyData.serializedObjects = VFXMemorySerializer.StoreObjects(allSerializedObjects);
return allSerializedObjects;
}
static VFXUI CopyGroupNodesAndStickyNotes(IEnumerable<Controller> elements, VFXContext[] copiedContexts, VFXModel[] copiedSlotContainers)
{
VFXGroupNodeController[] groupNodes = elements.OfType<VFXGroupNodeController>().ToArray();
VFXStickyNoteController[] stickyNotes = elements.OfType<VFXStickyNoteController>().ToArray();
VFXUI copiedGroupUI = null;
if (groupNodes.Length > 0 || stickyNotes.Length > 0)
{
copiedGroupUI = ScriptableObject.CreateInstance<VFXUI>();
var stickyNodeIndexToCopiedIndex = new Dictionary<int, int>();
if (stickyNotes.Length > 0)
{
copiedGroupUI.stickyNoteInfos = new VFXUI.StickyNoteInfo[stickyNotes.Length];
for (int i = 0; i < stickyNotes.Length; ++i)
{
VFXStickyNoteController stickyNote = stickyNotes[i];
stickyNodeIndexToCopiedIndex[stickyNote.index] = i;
VFXUI.StickyNoteInfo info = stickyNote.model.stickyNoteInfos[stickyNote.index];
copiedGroupUI.stickyNoteInfos[i] = new VFXUI.StickyNoteInfo(info);
}
}
if (groupNodes.Length > 0)
{
copiedGroupUI.groupInfos = new VFXUI.GroupInfo[groupNodes.Length];
for (int i = 0; i < groupNodes.Length; ++i)
{
VFXGroupNodeController groupNode = groupNodes[i];
VFXUI.GroupInfo info = groupNode.model.groupInfos[groupNode.index];
copiedGroupUI.groupInfos[i] = new VFXUI.GroupInfo(info);
// only keep nodes and sticky notes that are copied because a element can not be in two groups at the same time.
if (info.contents != null)
{
var groupInfo = copiedGroupUI.groupInfos[i];
groupInfo.contents = info.contents.Where(t => copiedContexts.Contains(t.model) || copiedSlotContainers.Contains(t.model) || (t.isStickyNote && stickyNodeIndexToCopiedIndex.ContainsKey(t.id))).ToArray();
for (int j = 0; j < groupInfo.contents.Length; ++j)
{
if (groupInfo.contents[j].isStickyNote)
{
groupInfo.contents[j].id = stickyNodeIndexToCopiedIndex[groupInfo.contents[j].id];
}
}
}
}
}
}
return copiedGroupUI;
}
static void CopyDataEdge(Data copyData, IEnumerable<VFXDataEdgeController> dataEdges, ScriptableObject[] allSerializedObjects)
{
copyData.dataEdges = new DataEdge[dataEdges.Count()];
int cpt = 0;
var orderedEdges = new List<VFXDataEdgeController>();
var edges = new HashSet<VFXDataEdgeController>(dataEdges);
// Ensure that operators that can change shape always all their input edges created before their output edges and in the same order
bool sortFailed = false;
try
{
while (edges.Count > 0)
{
var edgeInputs = edges.GroupBy(t => t.input.sourceNode).ToDictionary(t => t.Key, t => t.Select(u => u));
//Select the edges that have an input node which all its input edges have an output node that have no input edge
// Order them by index
var edgesWithoutParent = edges.Where(t => !edgeInputs[t.input.sourceNode].Any(u => edgeInputs.ContainsKey(u.output.sourceNode))).OrderBy(t => t.input.model.GetMasterSlot().owner.GetSlotIndex(t.input.model.GetMasterSlot())).ToList();
/*foreach(var gen in edgesWithoutParent)
{
int index = gen.input.model.GetMasterSlot().owner.GetSlotIndex(gen.input.model.GetMasterSlot());
Debug.Log("Edge with input:" + gen.input.sourceNode.title + "index"+ index);
}*/
orderedEdges.AddRange(edgesWithoutParent);
int count = edges.Count;
foreach (var e in edgesWithoutParent)
{
edges.Remove(e);
}
if (edges.Count >= count)
{
sortFailed = true;
Debug.LogError("Sorting of data edges failed. Please provide a screenshot of the graph with the selected node to @tristan");
break;
}
//Debug.Log("------------------------------");
}
}
catch (Exception e)
{
Debug.LogError("Sorting of data edges threw. Please provide a screenshot of the graph with the selected node to @tristan" + e.Message);
sortFailed = true;
}
IEnumerable<VFXDataEdgeController> usedEdges = sortFailed ? dataEdges : orderedEdges;
foreach (var edge in usedEdges)
{
DataEdge copyPasteEdge = new DataEdge();
var inputController = edge.input as VFXDataAnchorController;
var outputController = edge.output as VFXDataAnchorController;
copyPasteEdge.input.slotPath = MakeSlotPath(inputController.model, true);
if (inputController.model.owner is VFXContext)
{
VFXContext context = inputController.model.owner as VFXContext;
copyPasteEdge.inputContext = true;
copyPasteEdge.input.targetIndex = System.Array.IndexOf(allSerializedObjects, context);
copyPasteEdge.inputBlockIndex = -1;
}
else if (inputController.model.owner is VFXBlock)
{
VFXBlock block = inputController.model.owner as VFXBlock;
copyPasteEdge.inputContext = true;
copyPasteEdge.input.targetIndex = System.Array.IndexOf(allSerializedObjects, block.GetParent());
copyPasteEdge.inputBlockIndex = block.GetParent().GetIndex(block);
}
else
{
copyPasteEdge.inputContext = false;
copyPasteEdge.input.targetIndex = System.Array.IndexOf(allSerializedObjects, inputController.model.owner as VFXModel);
copyPasteEdge.inputBlockIndex = -1;
}
if (outputController.model.owner is VFXParameter)
{
copyPasteEdge.outputParameter = true;
copyPasteEdge.outputParameterIndex = System.Array.FindIndex(copyData.parameters, t => (IVFXSlotContainer)t.parameter == outputController.model.owner);
copyPasteEdge.outputParameterNodeIndex = System.Array.IndexOf(copyData.parameters[copyPasteEdge.outputParameterIndex].infos, (outputController.sourceNode as VFXParameterNodeController).infos);
}
else
{
copyPasteEdge.outputParameter = false;
}
copyPasteEdge.output.slotPath = MakeSlotPath(outputController.model, false);
copyPasteEdge.output.targetIndex = System.Array.IndexOf(allSerializedObjects, outputController.model.owner as VFXModel);
copyData.dataEdges[cpt++] = copyPasteEdge;
}
// Sort the edge so the one that links the node that have the least links
}
static void CopyFlowEdges(Data copyData, IEnumerable<VFXFlowEdgeController> flowEdges, ScriptableObject[] allSerializedObjects)
{
copyData.flowEdges = new FlowEdge[flowEdges.Count()];
int cpt = 0;
foreach (var edge in flowEdges)
{
FlowEdge copyPasteEdge = new FlowEdge();
var inputController = edge.input as VFXFlowAnchorController;
var outputController = edge.output as VFXFlowAnchorController;
copyPasteEdge.input.contextIndex = System.Array.IndexOf(allSerializedObjects, inputController.owner);
copyPasteEdge.input.flowIndex = inputController.slotIndex;
copyPasteEdge.output.contextIndex = System.Array.IndexOf(allSerializedObjects, outputController.owner);
copyPasteEdge.output.flowIndex = outputController.slotIndex;
copyData.flowEdges[cpt++] = copyPasteEdge;
}
}
static void CopyVFXData(Data copyData, VFXData[] datas, ScriptableObject[] allSerializedObjects, ref VFXContext[] copiedContexts)
{
copyData.dataAndContexts = new DataAndContexts[datas.Length];
for (int i = 0; i < datas.Length; ++i)
{
copyData.dataAndContexts[i].dataIndex = System.Array.IndexOf(allSerializedObjects, datas[i]);
copyData.dataAndContexts[i].contextsIndexes = copiedContexts.Where(t => t.GetData() == datas[i]).Select(t => System.Array.IndexOf(allSerializedObjects, t)).ToArray();
}
}
static void CopyNodes(Data copyData, IEnumerable<Controller> elements, IEnumerable<VFXContextController> contexts, IEnumerable<VFXNodeController> slotContainers, Rect bounds)
{
copyData.bounds = bounds;
IEnumerable<VFXNodeController> dataEdgeTargets = slotContainers.Concat(contexts.Cast<VFXNodeController>()).Concat(contexts.SelectMany(t => t.blockControllers).Cast<VFXNodeController>()).ToArray();
// consider only edges contained in the selection
IEnumerable<VFXDataEdgeController> dataEdges = elements.OfType<VFXDataEdgeController>().Where(t => dataEdgeTargets.Contains((t.input as VFXDataAnchorController).sourceNode as VFXNodeController) && dataEdgeTargets.Contains((t.output as VFXDataAnchorController).sourceNode as VFXNodeController)).ToArray();
IEnumerable<VFXFlowEdgeController> flowEdges = elements.OfType<VFXFlowEdgeController>().Where(t =>
contexts.Contains((t.input as VFXFlowAnchorController).context) &&
contexts.Contains((t.output as VFXFlowAnchorController).context)
).ToArray();
VFXContext[] copiedContexts = contexts.Select(t => t.model).ToArray();
copyData.contexts = copiedContexts;
VFXModel[] copiedSlotContainers = slotContainers.Select(t => t.model).ToArray();
copyData.slotContainers = copiedSlotContainers;
VFXParameterNodeController[] parameters = slotContainers.OfType<VFXParameterNodeController>().ToArray();
copyData.parameters = parameters.GroupBy(t => t.parentController, t => t.infos, (p, i) => new Parameter() { originalInstanceID = p.model.GetInstanceID(), parameter = p.model, infos = i.ToArray() }).ToArray();
VFXData[] datas = copiedContexts.Select(t => t.GetData()).Where(t => t != null).ToArray();
VFXUI copiedGroupUI = CopyGroupNodesAndStickyNotes(elements, copiedContexts, copiedSlotContainers);
ScriptableObject[] allSerializedObjects = PrepareSerializedObjects(copyData, copiedGroupUI);
for (int i = 0; i < copyData.parameters.Length; ++i)
{
copyData.parameters[i].index = System.Array.IndexOf(allSerializedObjects, copyData.parameters[i].parameter);
}
CopyVFXData(copyData, datas, allSerializedObjects, ref copiedContexts);
CopyDataEdge(copyData, dataEdges, allSerializedObjects);
CopyFlowEdges(copyData, flowEdges, allSerializedObjects);
}
public static object CreateCopy(IEnumerable<Controller> elements, Rect bounds)
{
IEnumerable<VFXContextController> contexts = elements.OfType<VFXContextController>();
IEnumerable<VFXNodeController> slotContainers = elements.Where(t => t is VFXOperatorController || t is VFXParameterNodeController).Cast<VFXNodeController>();
IEnumerable<VFXBlockController> blocks = elements.OfType<VFXBlockController>();
Data copyData = new Data();
if (contexts.Count() == 0 && slotContainers.Count() == 0 && blocks.Count() > 0)
{
VFXBlock[] copiedBlocks = blocks.Select(t => t.model).ToArray();
copyData.blocks = copiedBlocks;
PrepareSerializedObjects(copyData, null);
copyData.blocksOnly = true;
}
else
{
CopyNodes(copyData, elements, contexts, slotContainers, bounds);
}
return copyData;
}
public static string SerializeElements(IEnumerable<Controller> elements, Rect bounds)
{
var copyData = CreateCopy(elements, bounds) as Data;
return JsonUtility.ToJson(copyData);
}
static int[] MakeSlotPath(VFXSlot slot, bool input)
{
List<int> slotPath = new List<int>(slot.depth + 1);
while (slot.GetParent() != null)
{
slotPath.Add(slot.GetParent().GetIndex(slot));
slot = slot.GetParent();
}
slotPath.Add((input ? (slot.owner as IVFXSlotContainer).inputSlots : (slot.owner as IVFXSlotContainer).outputSlots).IndexOf(slot));
return slotPath.ToArray();
}
static VFXSlot FetchSlot(IVFXSlotContainer container, int[] slotPath, bool input)
{
int containerSlotIndex = slotPath[slotPath.Length - 1];
VFXSlot slot = null;
if (input)
{
if (container.GetNbInputSlots() > containerSlotIndex)
{
slot = container.GetInputSlot(slotPath[slotPath.Length - 1]);
}
}
else
{
if (container.GetNbOutputSlots() > containerSlotIndex)
{
slot = container.GetOutputSlot(slotPath[slotPath.Length - 1]);
}
}
if (slot == null)
{
return null;
}
for (int i = slotPath.Length - 2; i >= 0; --i)
{
if (slot.GetNbChildren() > slotPath[i])
{
slot = slot[slotPath[i]];
}
else
{
return null;
}
}
return slot;
}
public static void UnserializeAndPasteElements(VFXViewController viewController, Vector2 center, string data, VFXView view = null, VFXGroupNodeController groupNode = null)
{
var copyData = JsonUtility.FromJson<Data>(data);
ScriptableObject[] allSerializedObjects = VFXMemorySerializer.ExtractObjects(copyData.serializedObjects, true);
copyData.contexts = allSerializedObjects.OfType<VFXContext>().ToArray();
copyData.slotContainers = allSerializedObjects.OfType<IVFXSlotContainer>().Cast<VFXModel>().Where(t => !(t is VFXContext)).ToArray();
if (copyData.contexts.Length == 0 && copyData.slotContainers.Length == 0)
{
copyData.contexts = null;
copyData.slotContainers = null;
copyData.blocks = allSerializedObjects.OfType<VFXBlock>().ToArray();
}
PasteCopy(viewController, center, copyData, allSerializedObjects, view, groupNode);
}
public static void PasteCopy(VFXViewController viewController, Vector2 center, object data, ScriptableObject[] allSerializedObjects, VFXView view, VFXGroupNodeController groupNode)
{
Data copyData = (Data)data;
if (copyData.blocksOnly)
{
if (view != null)
{
copyData.blocks = allSerializedObjects.OfType<VFXBlock>().ToArray();
PasteBlocks(view, copyData);
}
}
else
{
PasteNodes(viewController, center, copyData, allSerializedObjects, view, groupNode);
}
}
static readonly GUIContent m_BlockPasteError = EditorGUIUtility.TextContent("To paste blocks, please select one target block or one target context.");
static void PasteBlocks(VFXView view, Data copyData)
{
var selectedContexts = view.selection.OfType<VFXContextUI>();
var selectedBlocks = view.selection.OfType<VFXBlockUI>();
VFXBlockUI targetBlock = null;
VFXContextUI targetContext = null;
if (selectedBlocks.Count() > 0)
{
targetBlock = selectedBlocks.OrderByDescending(t => t.context.controller.model.GetIndex(t.controller.model)).First();
targetContext = targetBlock.context;
}
else if (selectedContexts.Count() == 1)
{
targetContext = selectedContexts.First();
}
else
{
Debug.LogError(m_BlockPasteError.text);
return;
}
VFXContext targetModelContext = targetContext.controller.model;
int targetIndex = -1;
if (targetBlock != null)
{
targetIndex = targetModelContext.GetIndex(targetBlock.controller.model) + 1;
}
var newBlocks = new HashSet<VFXBlock>();
foreach (var block in copyData.blocks)
{
if (targetModelContext.AcceptChild(block, targetIndex))
{
newBlocks.Add(block);
foreach (var slot in block.inputSlots)
{
slot.UnlinkAll(true, false);
}
foreach (var slot in block.outputSlots)
{
slot.UnlinkAll(true, false);
}
targetModelContext.AddChild(block, targetIndex, false); // only notify once after all blocks have been added
}
}
targetModelContext.Invalidate(VFXModel.InvalidationCause.kStructureChanged);
// Create all ui based on model
view.controller.LightApplyChanges();
view.ClearSelection();
foreach (var uiBlock in targetContext.Query().OfType<VFXBlockUI>().Where(t => newBlocks.Contains(t.controller.model)).ToList())
{
view.AddToSelection(uiBlock);
}
}
static void ClearLinks(VFXContext container)
{
ClearLinks(container as IVFXSlotContainer);
foreach (var block in container.children)
{
ClearLinks(block);
}
container.UnlinkAll();
container.SetDefaultData(false);
}
static void ClearLinks(IVFXSlotContainer container)
{
foreach (var slot in container.inputSlots)
{
slot.UnlinkAll(true, false);
}
foreach (var slot in container.outputSlots)
{
slot.UnlinkAll(true, false);
}
}
private static void CopyDataEdges(Data copyData, ScriptableObject[] allSerializedObjects)
{
if (copyData.dataEdges != null)
{
foreach (var dataEdge in copyData.dataEdges)
{
VFXSlot inputSlot = null;
if (dataEdge.inputContext)
{
VFXContext targetContext = allSerializedObjects[dataEdge.input.targetIndex] as VFXContext;
if (dataEdge.inputBlockIndex == -1)
{
inputSlot = FetchSlot(targetContext, dataEdge.input.slotPath, true);
}
else
{
inputSlot = FetchSlot(targetContext[dataEdge.inputBlockIndex], dataEdge.input.slotPath, true);
}
}
else
{
VFXModel model = allSerializedObjects[dataEdge.input.targetIndex] as VFXModel;
inputSlot = FetchSlot(model as IVFXSlotContainer, dataEdge.input.slotPath, true);
}
IVFXSlotContainer outputContainer = null;
if (dataEdge.outputParameter)
{
var parameter = copyData.parameters[dataEdge.outputParameterIndex];
outputContainer = parameter.parameter;
}
else
{
outputContainer = allSerializedObjects[dataEdge.output.targetIndex] as IVFXSlotContainer;
}
VFXSlot outputSlot = FetchSlot(outputContainer, dataEdge.output.slotPath, false);
if (inputSlot != null && outputSlot != null)
{
if (inputSlot.Link(outputSlot) && dataEdge.outputParameter)
{
var parameter = copyData.parameters[dataEdge.outputParameterIndex];
var node = parameter.parameter.nodes[dataEdge.outputParameterNodeIndex + parameter.infoIndexOffset];
if (node.linkedSlots == null)
node.linkedSlots = new List<VFXParameter.NodeLinkedSlot>();
node.linkedSlots.Add(new VFXParameter.NodeLinkedSlot() { inputSlot = inputSlot, outputSlot = outputSlot });
}
}
}
}
}
static void PasteNodes(VFXViewController viewController, Vector2 center, Data copyData, ScriptableObject[] allSerializedObjects, VFXView view, VFXGroupNodeController groupNode)
{
var graph = viewController.graph;
Vector2 pasteOffset = (copyData.bounds.width > 0 && copyData.bounds.height > 0) ? center - copyData.bounds.center : Vector2.zero;
// look if pasting there will result in the first element beeing exactly on top of other
while (true)
{
bool foundSamePosition = false;
if (copyData.contexts != null && copyData.contexts.Length > 0)
{
VFXContext firstContext = copyData.contexts[0];
foreach (var existingContext in viewController.graph.children.OfType<VFXContext>())
{
if ((firstContext.position + pasteOffset - existingContext.position).sqrMagnitude < 1)
{
foundSamePosition = true;
break;
}
}
}
else if (copyData.slotContainers != null && copyData.slotContainers.Length > 0)
{
VFXModel firstContainer = copyData.slotContainers[0];
foreach (var existingSlotContainer in viewController.graph.children.Where(t => t is IVFXSlotContainer))
{
if ((firstContainer.position + pasteOffset - existingSlotContainer.position).sqrMagnitude < 1)
{
foundSamePosition = true;
break;
}
}
}
else
{
VFXUI ui = allSerializedObjects.OfType<VFXUI>().First();
if (ui != null)
{
if (ui.stickyNoteInfos != null && ui.stickyNoteInfos.Length > 0)
{
foreach (var stickyNote in viewController.stickyNotes)
{
if ((ui.stickyNoteInfos[0].position.position + pasteOffset - stickyNote.position.position).sqrMagnitude < 1)
{
foundSamePosition = true;
break;
}
}
}
else if (ui.groupInfos != null && ui.groupInfos.Length > 0)
{
foreach (var gn in viewController.groupNodes)
{
if ((ui.groupInfos[0].position.position + pasteOffset - gn.position.position).sqrMagnitude < 1)
{
foundSamePosition = true;
break;
}
}
}
}
}
if (foundSamePosition)
{
pasteOffset += Vector2.one * 30;
}
else
{
break;
}
}
if (copyData.contexts != null)
{
foreach (var slotContainer in copyData.contexts)
{
var newContext = slotContainer;
newContext.position += pasteOffset;
ClearLinks(newContext);
}
}
if (copyData.slotContainers != null)
{
foreach (var slotContainer in copyData.slotContainers)
{
var newSlotContainer = slotContainer;
newSlotContainer.position += pasteOffset;
ClearLinks(newSlotContainer as IVFXSlotContainer);
}
}
for (int i = 0; i < allSerializedObjects.Length; ++i)
{
ScriptableObject obj = allSerializedObjects[i];
if (obj is VFXContext || obj is VFXOperator)
{
graph.AddChild(obj as VFXModel);
}
else if (obj is VFXParameter)
{
int paramIndex = System.Array.FindIndex(copyData.parameters, t => t.index == i);
VFXParameter existingParameter = graph.children.OfType<VFXParameter>().FirstOrDefault(t => t.GetInstanceID() == copyData.parameters[paramIndex].originalInstanceID);
if (existingParameter != null)
{
// The original parameter is from the current graph, add the nodes to the original
copyData.parameters[paramIndex].parameter = existingParameter;
copyData.parameters[paramIndex].copiedParameter = obj as VFXParameter;
copyData.parameters[paramIndex].infoIndexOffset = existingParameter.nodes.Count;
foreach (var info in copyData.parameters[paramIndex].infos)
{
info.position += pasteOffset;
}
var oldIDs = copyData.parameters[paramIndex].infos.ToDictionary(t => t, t => t.id);
existingParameter.AddNodeRange(copyData.parameters[paramIndex].infos);
//keep track of new ids for groupnodes
copyData.parameters[paramIndex].idMap = copyData.parameters[paramIndex].infos.ToDictionary(t => oldIDs[t], t => t.id);
}
else
{
// The original parameter is from another graph : create the parameter in the other graph, but replace the infos with only the ones copied.
copyData.parameters[paramIndex].parameter = obj as VFXParameter;
copyData.parameters[paramIndex].parameter.SetNodes(copyData.parameters[paramIndex].infos);
graph.AddChild(obj as VFXModel);
}
}
}
VFXUI copiedUI = allSerializedObjects.OfType<VFXUI>().FirstOrDefault();
int firstCopiedGroup = -1;
int firstCopiedStickyNote = -1;
if (copiedUI != null)
{
VFXUI ui = viewController.graph.UIInfos;
firstCopiedStickyNote = ui.stickyNoteInfos != null ? ui.stickyNoteInfos.Length : 0;
if (copiedUI.groupInfos != null && copiedUI.groupInfos.Length > 0)
{
if (ui.groupInfos == null)
{
ui.groupInfos = new VFXUI.GroupInfo[0];
}
firstCopiedGroup = ui.groupInfos.Length;
foreach (var groupInfos in copiedUI.groupInfos)
{
for (int i = 0; i < groupInfos.contents.Length; ++i)
{
// if we link the parameter node to an existing parameter instead of the copied parameter we have to patch the groupnode content to point the that parameter with the correct id.
if (groupInfos.contents[i].model is VFXParameter)
{
VFXParameter parameter = groupInfos.contents[i].model as VFXParameter;
var paramInfo = copyData.parameters.FirstOrDefault(t => t.copiedParameter == parameter);
if (paramInfo.parameter != null) // parameter will not be null unless the struct returned is the default.
{
groupInfos.contents[i].model = paramInfo.parameter;
groupInfos.contents[i].id = paramInfo.idMap[groupInfos.contents[i].id];
}
}
else if (groupInfos.contents[i].isStickyNote)
{
groupInfos.contents[i].id += firstCopiedStickyNote;
}
}
}
ui.groupInfos = ui.groupInfos.Concat(copiedUI.groupInfos.Select(t => new VFXUI.GroupInfo(t) { position = new Rect(t.position.position + pasteOffset, t.position.size) })).ToArray();
}
if (copiedUI.stickyNoteInfos != null && copiedUI.stickyNoteInfos.Length > 0)
{
if (ui.stickyNoteInfos == null)
{
ui.stickyNoteInfos = new VFXUI.StickyNoteInfo[0];
}
ui.stickyNoteInfos = ui.stickyNoteInfos.Concat(copiedUI.stickyNoteInfos.Select(t => new VFXUI.StickyNoteInfo(t) { position = new Rect(t.position.position + pasteOffset, t.position.size) })).ToArray();
}
}
CopyDataEdges(copyData, allSerializedObjects);
if (copyData.flowEdges != null)
{
foreach (var flowEdge in copyData.flowEdges)
{
VFXContext inputContext = allSerializedObjects[flowEdge.input.contextIndex] as VFXContext;
VFXContext outputContext = allSerializedObjects[flowEdge.output.contextIndex] as VFXContext;
inputContext.LinkFrom(outputContext, flowEdge.input.flowIndex, flowEdge.output.flowIndex);
}
}
foreach (var dataAndContexts in copyData.dataAndContexts)
{
VFXData data = allSerializedObjects[dataAndContexts.dataIndex] as VFXData;
foreach (var contextIndex in dataAndContexts.contextsIndexes)
{
VFXContext context = allSerializedObjects[contextIndex] as VFXContext;
data.CopySettings(context.GetData());
}
}
// Create all ui based on model
viewController.LightApplyChanges();
if (view != null)
{
view.ClearSelection();
var elements = view.graphElements.ToList();
List<VFXNodeUI> newSlotContainerUIs = new List<VFXNodeUI>();
List<VFXContextUI> newContextUIs = new List<VFXContextUI>();
foreach (var slotContainer in allSerializedObjects.OfType<VFXContext>())
{
VFXContextUI contextUI = elements.OfType<VFXContextUI>().FirstOrDefault(t => t.controller.model == slotContainer);
if (contextUI != null)
{
newSlotContainerUIs.Add(contextUI);
newSlotContainerUIs.AddRange(contextUI.GetAllBlocks().Cast<VFXNodeUI>());
newContextUIs.Add(contextUI);
view.AddToSelection(contextUI);
}
}
foreach (var slotContainer in allSerializedObjects.OfType<VFXOperator>())
{
VFXOperatorUI slotContainerUI = elements.OfType<VFXOperatorUI>().FirstOrDefault(t => t.controller.model == slotContainer);
if (slotContainerUI != null)
{
newSlotContainerUIs.Add(slotContainerUI);
view.AddToSelection(slotContainerUI);
}
}
foreach (var param in copyData.parameters)
{
foreach (var parameterUI in elements.OfType<VFXParameterUI>().Where(t => t.controller.model == param.parameter && param.parameter.nodes.IndexOf(t.controller.infos) >= param.infoIndexOffset))
{
newSlotContainerUIs.Add(parameterUI);
view.AddToSelection(parameterUI);
}
}
// Simply selected all data edge with the context or slot container, they can be no other than the copied ones
foreach (var dataEdge in elements.OfType<VFXDataEdge>())
{
if (newSlotContainerUIs.Contains(dataEdge.input.GetFirstAncestorOfType<VFXNodeUI>()))
{
view.AddToSelection(dataEdge);
}
}
// Simply selected all data edge with the context or slot container, they can be no other than the copied ones
foreach (var flowEdge in elements.OfType<VFXFlowEdge>())
{
if (newContextUIs.Contains(flowEdge.input.GetFirstAncestorOfType<VFXContextUI>()))
{
view.AddToSelection(flowEdge);
}
}
if (groupNode != null)
{
foreach (var newSlotContainerUI in newSlotContainerUIs)
{
groupNode.AddNode(newSlotContainerUI.controller);
}
}
//Select all groups that are new
if (firstCopiedGroup >= 0)
{
foreach (var gn in elements.OfType<VFXGroupNode>())
{
if (gn.controller.index >= firstCopiedGroup)
{
view.AddToSelection(gn);
}
}
}
//Select all groups that are new
if (firstCopiedStickyNote >= 0)
{
foreach (var gn in elements.OfType<VFXStickyNote>())
{
if (gn.controller.index >= firstCopiedStickyNote)
{
view.AddToSelection(gn);
}
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
namespace System.Globalization
{
public partial class CompareInfo
{
internal unsafe CompareInfo(CultureInfo culture)
{
const uint LCMAP_SORTHANDLE = 0x20000000;
this.m_name = culture.m_name;
this.m_sortName = culture.SortName;
long handle;
int ret = Interop.mincore.LCMapStringEx(m_sortName, LCMAP_SORTHANDLE, null, 0, (IntPtr)(&handle), IntPtr.Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
_sortHandle = ret > 0 ? (IntPtr)handle : IntPtr.Zero;
}
internal static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
return Interop.mincore.FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
}
internal static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
return Interop.mincore.FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int tmpHash = 0;
if (Interop.mincore.LCMapStringEx(m_sortName,
LCMAP_HASH | (uint)GetNativeCompareFlags(options),
source, source.Length,
(IntPtr)(&tmpHash), sizeof(int),
IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) == 0)
{
Environment.FailFast("LCMapStringEx failed!");
}
return tmpHash;
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
// Use the OS to compare and then convert the result to expected value by subtracting 2
return Interop.mincore.CompareStringOrdinal(string1, count1, string2, count2, true) - 2;
}
private int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Contract.Assert(string1 != null);
Contract.Assert(string2 != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
int result = Interop.mincore.CompareStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName,
GetNativeCompareFlags(options),
string1, offset1, length1,
string2, offset2, length2,
_sortHandle);
if (result == 0)
{
Environment.FailFast("CompareStringEx failed");
}
// Map CompareStringEx return value to -1, 0, 1.
return result - 2;
}
private int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false);
}
else
{
int retValue = Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName,
FIND_FROMSTART | (uint)GetNativeCompareFlags(options),
source,
startIndex,
count,
target,
0,
target.Length,
_sortHandle);
if (retValue >= 0)
{
return retValue + startIndex;
}
}
return -1;
}
private int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
return startIndex; // keep Whidbey compatibility
if ((options & CompareOptions.Ordinal) != 0)
{
return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true);
}
else
{
int retValue = Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName,
FIND_FROMEND | (uint)GetNativeCompareFlags(options),
source,
startIndex - count + 1,
count,
target,
0,
target.Length,
_sortHandle);
if (retValue >= 0)
{
return retValue + startIndex - (count - 1);
}
}
return -1;
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(prefix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName,
FIND_STARTSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
prefix,
0,
prefix.Length,
_sortHandle) >= 0;
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(suffix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return Interop.mincore.FindNLSStringEx(_sortHandle != IntPtr.Zero ? null : m_sortName,
FIND_ENDSWITH | (uint)GetNativeCompareFlags(options),
source,
0,
source.Length,
suffix,
0,
suffix.Length,
_sortHandle) >= 0;
}
// PAL ends here
private readonly IntPtr _sortHandle;
private const uint LCMAP_HASH = 0x00040000;
private const int FIND_STARTSWITH = 0x00100000;
private const int FIND_ENDSWITH = 0x00200000;
private const int FIND_FROMSTART = 0x00400000;
private const int FIND_FROMEND = 0x00800000;
private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex)
{
int retValue = -1;
int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
#if !TEST_CODEGEN_OPTIMIZATION
fixed (char* pSource = source, spTarget = target)
{
char* spSubSource = pSource + sourceStartIndex;
#else
String.StringPointer spSubSource = source.GetStringPointer(sourceStartIndex);
String.StringPointer spTarget = target.GetStringPointer();
#endif
if (findLastIndex)
{
int startPattern = (sourceCount - 1) - targetCount + 1;
if (startPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex - sourceCount + 1;
}
}
else
{
int endPattern = (sourceCount - 1) - targetCount + 1;
if (endPattern < 0)
return -1;
char patternChar0 = spTarget[0];
for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++)
{
if (spSubSource[ctrSrc] != patternChar0)
continue;
int ctrPat;
for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
{
if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
break;
}
if (ctrPat == targetCount)
{
retValue = ctrSrc;
break;
}
}
if (retValue >= 0)
{
retValue += startIndex;
}
}
#if !TEST_CODEGEN_OPTIMIZATION
}
return retValue;
#endif // TEST_CODEGEN_OPTIMIZATION
}
private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
private static int GetNativeCompareFlags(CompareOptions options)
{
// Use "linguistic casing" by default (load the culture's casing exception tables)
int nativeCompareFlags = NORM_LINGUISTIC_CASING;
if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
// Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
Contract.Assert(((options & ~(CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreSymbols |
CompareOptions.IgnoreWidth |
CompareOptions.StringSort)) == 0) ||
(options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
return nativeCompareFlags;
}
}
}
| |
using System;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace HostMe.Sdk.Client
{
/// <summary>
/// Represents a set of configuration settings
/// </summary>
public class Configuration
{
/// <summary>
/// Initializes a new instance of the Configuration class with different settings
/// </summary>
/// <param name="apiClient">Api client</param>
/// <param name="defaultHeader">Dictionary of default HTTP header</param>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <param name="accessToken">accessToken</param>
/// <param name="apiKey">Dictionary of API key</param>
/// <param name="apiKeyPrefix">Dictionary of API key prefix</param>
/// <param name="tempFolderPath">Temp folder path</param>
/// <param name="dateTimeFormat">DateTime format string</param>
/// <param name="timeout">HTTP connection timeout (in milliseconds)</param>
/// <param name="userAgent">HTTP user agent</param>
public Configuration(ApiClient apiClient = null,
Dictionary<String, String> defaultHeader = null,
string username = null,
string password = null,
string accessToken = null,
Dictionary<String, String> apiKey = null,
Dictionary<String, String> apiKeyPrefix = null,
string tempFolderPath = null,
string dateTimeFormat = null,
int timeout = 100000,
string userAgent = "Swagger-Codegen/1.0.0/csharp"
)
{
setApiClientUsingDefault(apiClient);
Username = username;
Password = password;
AccessToken = accessToken;
UserAgent = userAgent;
if (defaultHeader != null)
DefaultHeader = defaultHeader;
if (apiKey != null)
ApiKey = apiKey;
if (apiKeyPrefix != null)
ApiKeyPrefix = apiKeyPrefix;
TempFolderPath = tempFolderPath;
DateTimeFormat = dateTimeFormat;
Timeout = timeout;
}
/// <summary>
/// Initializes a new instance of the Configuration class.
/// </summary>
/// <param name="apiClient">Api client.</param>
public Configuration(ApiClient apiClient)
{
setApiClientUsingDefault(apiClient);
}
/// <summary>
/// Version of the package.
/// </summary>
/// <value>Version of the package.</value>
public const string Version = "1.0.0";
/// <summary>
/// Gets or sets the default Configuration.
/// </summary>
/// <value>Configuration.</value>
public static Configuration Default = new Configuration();
/// <summary>
/// Default creation of exceptions for a given method name and response object
/// </summary>
public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) =>
{
int status = (int)response.StatusCode;
if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), response.Content);
if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), response.ErrorMessage);
return null;
};
/// <summary>
/// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds.
/// </summary>
/// <value>Timeout.</value>
public int Timeout
{
get { return ApiClient.RestClient.Timeout; }
set
{
if (ApiClient != null)
ApiClient.RestClient.Timeout = value;
}
}
/// <summary>
/// Gets or sets the default API client for making HTTP calls.
/// </summary>
/// <value>The API client.</value>
public ApiClient ApiClient;
/// <summary>
/// Set the ApiClient using Default or ApiClient instance.
/// </summary>
/// <param name="apiClient">An instance of ApiClient.</param>
/// <returns></returns>
public void setApiClientUsingDefault (ApiClient apiClient = null)
{
if (apiClient == null)
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = new ApiClient();
ApiClient = Default != null ? Default.ApiClient : new ApiClient();
}
else
{
if (Default != null && Default.ApiClient == null)
Default.ApiClient = apiClient;
ApiClient = apiClient;
}
}
private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the default header.
/// </summary>
public Dictionary<String, String> DefaultHeader
{
get { return _defaultHeaderMap; }
set
{
_defaultHeaderMap = value;
}
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
public void AddDefaultHeader(string key, string value)
{
_defaultHeaderMap.Add(key, value);
}
/// <summary>
/// Gets or sets the HTTP user agent.
/// </summary>
/// <value>Http user agent.</value>
public String UserAgent { get; set; }
/// <summary>
/// Gets or sets the username (HTTP basic authentication).
/// </summary>
/// <value>The username.</value>
public String Username { get; set; }
/// <summary>
/// Gets or sets the password (HTTP basic authentication).
/// </summary>
/// <value>The password.</value>
public String Password { get; set; }
/// <summary>
/// Gets or sets the access token for OAuth2 authentication.
/// </summary>
/// <value>The access token.</value>
public String AccessToken { get; set; }
/// <summary>
/// Gets or sets the API key based on the authentication name.
/// </summary>
/// <value>The API key.</value>
public Dictionary<String, String> ApiKey = new Dictionary<String, String>();
/// <summary>
/// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name.
/// </summary>
/// <value>The prefix of the API key.</value>
public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>();
/// <summary>
/// Get the API key with prefix.
/// </summary>
/// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param>
/// <returns>API key with prefix.</returns>
public string GetApiKeyWithPrefix (string apiKeyIdentifier)
{
var apiKeyValue = "";
ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue);
var apiKeyPrefix = "";
if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix))
return apiKeyPrefix + " " + apiKeyValue;
else
return apiKeyValue;
}
private string _tempFolderPath = Path.GetTempPath();
/// <summary>
/// Gets or sets the temporary folder path to store the files downloaded from the server.
/// </summary>
/// <value>Folder path.</value>
public String TempFolderPath
{
get { return _tempFolderPath; }
set
{
if (String.IsNullOrEmpty(value))
{
_tempFolderPath = value;
return;
}
// create the directory if it does not exist
if (!Directory.Exists(value))
Directory.CreateDirectory(value);
// check if the path contains directory separator at the end
if (value[value.Length - 1] == Path.DirectorySeparatorChar)
_tempFolderPath = value;
else
_tempFolderPath = value + Path.DirectorySeparatorChar;
}
}
private const string ISO8601_DATETIME_FORMAT = "o";
private string _dateTimeFormat = ISO8601_DATETIME_FORMAT;
/// <summary>
/// Gets or sets the the date time format used when serializing in the ApiClient
/// By default, it's set to ISO 8601 - "o", for others see:
/// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
/// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
/// No validation is done to ensure that the string you're providing is valid
/// </summary>
/// <value>The DateTimeFormat string</value>
public String DateTimeFormat
{
get
{
return _dateTimeFormat;
}
set
{
if (string.IsNullOrEmpty(value))
{
// Never allow a blank or null string, go back to the default
_dateTimeFormat = ISO8601_DATETIME_FORMAT;
return;
}
// Caution, no validation when you choose date time format other than ISO 8601
// Take a look at the above links
_dateTimeFormat = value;
}
}
/// <summary>
/// Returns a string with essential information for debugging.
/// </summary>
public static String ToDebugReport()
{
String report = "C# SDK (HostMe.Sdk) Debug Report:\n";
report += " OS: " + Environment.OSVersion + "\n";
report += " .NET Framework Version: " + Assembly
.GetExecutingAssembly()
.GetReferencedAssemblies()
.Where(x => x.Name == "System.Core").First().Version.ToString() + "\n";
report += " Version of the API: all\n";
report += " SDK Package Version: 1.0.0\n";
return report;
}
}
}
| |
using System.Collections;
using UnityEditor;
using UnityEngine;
using System.IO;
[InitializeOnLoad]
public class AutoSave
{
public static readonly string manualSaveKey = "autosave@manualSave";
static readonly string lockFilePath = "Library/Backup/Lockfile";
static readonly string editModeScenePath = "Temp/__EditModeScene";
static readonly string backupEditModeScenePath = "Library/Backup/__EditModeScene.unity";
static readonly string backupCurrentScenePath = "Library/Backup/__CurrentScene";
static double nextTime = 0;
static bool isChangedHierarchy = false;
static AutoSave ()
{
IsManualSave = true;
EditorApplication.playmodeStateChanged += () =>
{
if (EditorApplication.isPlayingOrWillChangePlaymode) {
if (EditorApplication.isPlaying) {
if (IsSavePrefab)
EditorApplication.SaveAssets ();
BackupEditSceneFile ();
File.WriteAllText (lockFilePath, EditorApplication.currentScene);
}
}
if (EditorApplication.isPlaying == false) {
File.Delete (lockFilePath);
}
};
nextTime = EditorApplication.timeSinceStartup + Interval;
EditorApplication.update += () =>
{
if (isChangedHierarchy && nextTime < EditorApplication.timeSinceStartup) {
nextTime = EditorApplication.timeSinceStartup + Interval;
IsManualSave = false;
if (IsSaveSceneTimer &&
IsAutoSave &&
!EditorApplication.isPlaying &&
!string.IsNullOrEmpty (EditorApplication.currentScene)) {
if (IsSavePrefab)
EditorApplication.SaveAssets ();
if (IsSaveScene) {
Debug.Log ("save scene " + System.DateTime.Now);
EditorApplication.SaveScene ();
}
}
}
isChangedHierarchy = false;
IsManualSave = true;
};
EditorApplication.hierarchyWindowChanged += () =>
{
if (! EditorApplication.isPlaying)
isChangedHierarchy = true;
};
EditorApplication.update += Init;
}
static void Init ()
{
EditorApplication.update -= Init;
if (EditorApplication.timeSinceStartup > 5)
return;
if (File.Exists (lockFilePath)) {
string sceneFile = File.ReadAllText (lockFilePath);
File.Copy (sceneFile, backupCurrentScenePath, true);
File.Copy (backupEditModeScenePath, sceneFile, true);
File.Delete (lockFilePath);
EditorApplication.OpenScene (sceneFile);
File.Copy (backupCurrentScenePath, sceneFile, true);
}
}
static void BackupEditSceneFile ()
{
Directory.CreateDirectory ("Library/Backup");
File.Copy (editModeScenePath, backupEditModeScenePath, true);
}
public static bool IsManualSave {
get {
return EditorPrefs.GetBool (manualSaveKey);
}
private set {
EditorPrefs.SetBool (manualSaveKey, value);
}
}
private static readonly string autoSave = "auto save";
static bool IsAutoSave {
get {
string value = EditorUserSettings.GetConfigValue (autoSave);
return!string.IsNullOrEmpty (value) && value.Equals ("True");
}
set {
EditorUserSettings.SetConfigValue (autoSave, value.ToString ());
}
}
private static readonly string autoSavePrefab = "auto save prefab";
static bool IsSavePrefab {
get {
string value = EditorUserSettings.GetConfigValue (autoSavePrefab);
return!string.IsNullOrEmpty (value) && value.Equals ("True");
}
set {
EditorUserSettings.SetConfigValue (autoSavePrefab, value.ToString ());
}
}
private static readonly string autoSaveScene = "auto save scene";
static bool IsSaveScene {
get {
string value = EditorUserSettings.GetConfigValue (autoSaveScene);
return!string.IsNullOrEmpty (value) && value.Equals ("True");
}
set {
EditorUserSettings.SetConfigValue (autoSaveScene, value.ToString ());
}
}
private static readonly string autoSaveSceneTimer = "auto save scene timer";
static bool IsSaveSceneTimer {
get {
string value = EditorUserSettings.GetConfigValue (autoSaveSceneTimer);
return!string.IsNullOrEmpty (value) && value.Equals ("True");
}
set {
EditorUserSettings.SetConfigValue (autoSaveSceneTimer, value.ToString ());
}
}
private static readonly string autoSaveInterval = "save scene interval";
static int Interval {
get {
string value = EditorUserSettings.GetConfigValue (autoSaveInterval);
if (value == null) {
value = "60";
}
return int.Parse (value);
}
set {
if (value < 60)
value = 60;
EditorUserSettings.SetConfigValue (autoSaveInterval, value.ToString ());
}
}
[PreferenceItem("Auto Save")]
static void ExampleOnGUI ()
{
bool isAutoSave = EditorGUILayout.BeginToggleGroup ("auto save", IsAutoSave);
IsAutoSave = isAutoSave;
EditorGUILayout.Space ();
IsSavePrefab = EditorGUILayout.ToggleLeft ("save prefab", IsSavePrefab);
IsSaveScene = EditorGUILayout.ToggleLeft ("save scene", IsSaveScene);
IsSaveSceneTimer = EditorGUILayout.BeginToggleGroup ("save scene interval", IsSaveSceneTimer);
Interval = EditorGUILayout.IntField ("interval(sec) min60sec", Interval);
EditorGUILayout.EndToggleGroup ();
EditorGUILayout.EndToggleGroup ();
}
public static void Backup ()
{
if( string.IsNullOrEmpty(EditorApplication.currentScene ))
return;
string expoertPath = "Library/Backup/" + EditorApplication.currentScene;
Directory.CreateDirectory (Path.GetDirectoryName (expoertPath));
if( string.IsNullOrEmpty(EditorApplication.currentScene))
return;
byte[] data = File.ReadAllBytes (EditorApplication.currentScene);
File.WriteAllBytes (expoertPath, data);
}
[MenuItem("File/Backup/Rollback")]
public static void RollBack ()
{
if (string.IsNullOrEmpty (EditorApplication.currentScene))
return;
string expoertPath = "Library/Backup/" + EditorApplication.currentScene;
byte[] data = File.ReadAllBytes (expoertPath);
File.WriteAllBytes (EditorApplication.currentScene, data);
AssetDatabase.Refresh (ImportAssetOptions.Default);
}
}
class SceneBackup : UnityEditor.AssetModificationProcessor
{
static string[] OnWillSaveAssets (string[] paths)
{
bool manualSave = AutoSave.IsManualSave;
if (manualSave) {
AutoSave.Backup ();
}
return paths;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// TagsOperations operations.
/// </summary>
internal partial class TagsOperations : Microsoft.Rest.IServiceOperations<ResourceManagementClient>, ITagsOperations
{
/// <summary>
/// Initializes a new instance of the TagsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal TagsOperations(ResourceManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ResourceManagementClient
/// </summary>
public ResourceManagementClient Client { get; private set; }
/// <summary>
/// Deletes a tag value.
/// </summary>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag to delete.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteValueWithHttpMessagesAsync(string tagName, string tagValue, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (tagName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "tagName");
}
if (tagValue == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "tagValue");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "DeleteValue", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{tagValue}", System.Uri.EscapeDataString(tagValue));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a tag value. The name of the tag must already exist.
/// </summary>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='tagValue'>
/// The value of the tag to create.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<TagValue>> CreateOrUpdateValueWithHttpMessagesAsync(string tagName, string tagValue, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (tagName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "tagName");
}
if (tagValue == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "tagValue");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("tagValue", tagValue);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdateValue", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{tagValue}", System.Uri.EscapeDataString(tagValue));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<TagValue>();
_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<TagValue>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<TagValue>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates a tag in the subscription.
/// </summary>
/// <remarks>
/// The tag name can have a maximum of 512 characters and is case insensitive.
/// Tag names created by Azure have prefixes of microsoft, azure, or windows.
/// You cannot create tags with one of these prefixes.
/// </remarks>
/// <param name='tagName'>
/// The name of the tag to create.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<TagDetails>> CreateOrUpdateWithHttpMessagesAsync(string tagName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (tagName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "tagName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<TagDetails>();
_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<TagDetails>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<TagDetails>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a tag from the subscription.
/// </summary>
/// <remarks>
/// You must remove all values from a resource tag before you can delete it.
/// </remarks>
/// <param name='tagName'>
/// The name of the tag.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string tagName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (tagName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "tagName");
}
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("tagName", tagName);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames/{tagName}").ToString();
_url = _url.Replace("{tagName}", System.Uri.EscapeDataString(tagName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.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)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the names and values of all resource tags that are defined in a
/// subscription.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<TagDetails>>> ListWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.Client.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/tagNames").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<TagDetails>>();
_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<Page<TagDetails>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the names and values of all resource tags that are defined in a
/// subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<TagDetails>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _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 (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<TagDetails>>();
_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<Page<TagDetails>>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
public class SquadManager : MonoBehaviour
{
//Ability is using an action on an ability
public delegate void Ability();
//AbilityUpdate is for the unit to handle the special action when the ability is selected
public delegate void AbilityUpdate();
//Button for ability is first clicked of Ability
public delegate void AbilityInit();
//FLAGS:
private bool dead = false;
public bool retaliation = false; //TODO: Add retaliation?
public bool inCover = false;
public bool behindWall = false;
private bool prevCover = false;
private bool targeted = false;
private bool selected = false;
//Serialization stuff, really useful link:
// http://www.paladinstudios.com/2013/07/10/how-to-create-an-online-multiplayer-game-with-unity/
private float lastSynchronizationTime = 0f;
private float syncDelay = 0f;
private float syncTime = 0f;
private Vector3 syncStartPosition = Vector3.zero;
private Vector3 syncEndPosition = Vector3.zero;
[HideInInspector]
public int size = 0;
public Texture tex;
public Texture selectorGreen;
public Texture selectorRed;
public Texture greenTexture;
public Texture redTexture;
[HideInInspector]
private Color offColor = new Color(103, 0, 0); //Crimson
public Color myColor = Color.red;
private float unitDistanceFromCenter = 1.5f;
public const int MAX_ACTIONS = 2;
private int _numActions = MAX_ACTIONS;
private Vector3 positionAtActionStart;
private bool _midMovement = false;
[HideInInspector]
public float dodgeChance = BalanceConstants.Stats.BASIC_DODGE_CHANCE;
[HideInInspector]
public float hitChance = BalanceConstants.Stats.BASIC_HIT_CHANCE;
public bool midMovement { get { return _midMovement; } }
public int numActions { get { return _numActions; } }
[HideInInspector]
public string squadType;
//Added lights for showing targeted.
private GameObject myLight;
[HideInInspector]
public Light lightPiece;
[HideInInspector]
public Projector moveProj;
[HideInInspector]
public Projector attackProj;
[HideInInspector]
public NetworkView nView;
[HideInInspector]
public float movementDistance;
[HideInInspector]
public float attackDistance;
//TODO: This might need to become a collection of game objects
[HideInInspector]
public Transform[] unitTargets;
[HideInInspector]
public GameObject[] units;
private const float MAX_UNIT_HEIGHT = 0.5f;
private const float FLOOR_DISPACEMENT = 1f;
private Vector3 prevPosition; //used to revert after colliding w/ terrain.
private Rigidbody rb;
public Ability unitAbility;
public Ability squadAbility;
public AbilityUpdate unitAbilityUpdate;
public AbilityUpdate squadAbilityUpdate;
private int myNumber;
public AudioSource walk;
public AudioClip walkSound;
public bool hasCurTime;
private DateTime curTime;
private DateTime firstTime;
private DateTime dTime;
// Use this for initialization
[RPC]
public void init(string squadTag)
{
walk = GetComponent<AudioSource> ();
walkSound = walk.clip;
hasCurTime = false;
myLight = new GameObject();
myLight.transform.position = transform.position;
lightPiece = myLight.AddComponent<Light>();
lightPiece.color = Color.red;
lightPiece.intensity = 8;
tag = squadTag;
attackDistance = 20;
movementDistance = 20;
//offColor = myColor / 2;
moveProj = GameObject.Find("MoveRadius").GetComponent<Projector>();
attackProj = GameObject.Find("AttackRadius").GetComponent<Projector>();
nView = GetComponent<NetworkView>();
lightPiece.enabled = false;
rb = GetComponent<Rigidbody>();
if (rb == null) throw new MissingComponentException("Need Rigidbody");
prevPosition = transform.position;
}
//once every physics step
void FixedUpdate()
{
if (nView != null && nView.isMine)
{
if (_midMovement && rb.velocity.magnitude > 0)
{
TimeSpan seconds;
if(!hasCurTime)
{
firstTime = DateTime.Now;
walk.PlayOneShot(walkSound);
hasCurTime = true;
}
if(hasCurTime)
{
curTime = DateTime.Now;
seconds = curTime - firstTime;
if(seconds.TotalSeconds > 1.1)
hasCurTime = false;
}
float h = Terrain.activeTerrain.SampleHeight(transform.position) + FLOOR_DISPACEMENT;
transform.position = new Vector3(transform.position.x, h, transform.position.z);
if ((positionAtActionStart - transform.position).magnitude >= movementDistance)
{
//endMovement();
transform.position = prevPosition;
}
if (transform.position.x > 62 || transform.position.x < -63 || transform.position.z > 100 || transform.position.z < -97)
transform.position = prevPosition;
}
else
{
if (rb != null){
rb.Sleep();
walk.Stop();
}
}
prevPosition = transform.position;
}
}
// Update is called once per frame
void Update()
{
if (_midMovement) {
Quaternion rot = Camera.main.transform.rotation;
rot.x=rot.z=0;
for (int i = 0; i < units.Length; i++)
{
units[i].transform.rotation = rot;
}
}
if (nView != null && nView.isMine)
{
for (int i = 0; i < units.Length; i++)
{
units[i].transform.position = unitTargets[i].position;
transform.rotation = Quaternion.identity;
//TODO: This should be targetting instead of teleporting
}
//Updates associated light
myLight.transform.position = transform.position;
}
else if (nView != null && !rb.IsSleeping())
{
SyncedMovement();
}
}
public void startMovement()
{
if (numActions > 0)
{
positionAtActionStart = transform.position;
moveProj.transform.position = new Vector3(transform.position.x, 9, transform.position.z);
moveProj.orthographicSize = movementDistance + 3;
moveProj.gameObject.SetActive(true);
attackProj.transform.position = new Vector3(transform.position.x, 9, transform.position.z);
attackProj.orthographicSize = attackDistance;
attackProj.gameObject.SetActive(true);
attackProj.enabled = true;
_midMovement = true;
prevCover = inCover;
inCover = false;
}
else throw new UnityException("Attempted to start an action when squad had none.");
}
public void endMovement()
{
if (_midMovement)
{
_midMovement = false;
_numActions--;
GetComponent<Rigidbody>().velocity = Vector3.zero;
moveProj.gameObject.SetActive(false);
attackProj.gameObject.SetActive(true);
Collider[] hitColliders = Physics.OverlapSphere(transform.position, 2, GameObject.Find("GameLogic").GetComponent<Controller>().detectPartial); //Needs to figure out layers
if (hitColliders.Length > 0)
inCover = true;
}
else throw new UnityException("Attempted to end an actions before starting one.");
}
public void skipAction()
{
if (_numActions > 0)
{
_numActions--;
moveProj.gameObject.SetActive(false);
}
else throw new UnityException("Attempted to skip an action when squad had none.");
}
public void resetActions()
{
if (!dead)
{
_numActions = MAX_ACTIONS;
_midMovement = false;
nView.RPC("activeSquadColor", RPCMode.All, true);
moveProj.gameObject.SetActive(false);
}
}
public void undoMove()
{
if (_midMovement)
{
_midMovement = false;
transform.position = positionAtActionStart;
inCover = prevCover;
moveProj.gameObject.SetActive(false);
}
else throw new UnityException("Attempted to undo a move when squad had not moved");
}
[RPC]
public void takeDamage(int damage, bool killSpecial)
{
lightPiece.enabled = false;
if (damage > 0)
{
int remainingToKill = damage;
Debug.Log("I'm dieing!");
if (killSpecial)
foreach (GameObject unit in units)
{
if (remainingToKill <= 0)
break;
else if (unit.GetComponent<UnitManager>().isSpecial && unit.activeInHierarchy)
{
unit.SetActive(false);
remainingToKill--;
}
}
foreach (GameObject unit in units)
{
if (remainingToKill <= 0)
break;
else if (unit.activeInHierarchy)
{
unit.SetActive(false); //Might not be correct
remainingToKill--;
}
}
if (isDead())
{
//Disable this squad
//Network.RemoveRPCsInGroup(0);
//Network.Destroy(gameObject);
//gameObject.SetActive(false);
gameObject.tag = "Dead";
_numActions = 0;
//lightPiece.enabled = false;
}
}
}
//Checks all units of the squad to see if they are active or not.
public bool isDead()
{
if (!dead)
foreach (GameObject unit in units)
{
if (unit.activeInHierarchy)
{
return false;
}
}
_numActions = 0;
return dead = true;
}
[RPC]
public void enableLight()
{
lightPiece.enabled = true;
}
[RPC]
public void disableLight()
{
lightPiece.enabled = false;
}
public void enableTarget()
{
targeted = true;
}
public void disableTarget()
{
targeted = false;
}
public void enableSelect()
{
selected = true;
}
public void disableSelect()
{
selected = false;
}
public List<GameObject> getActiveUnits()
{
List<GameObject> myUnits = new List<GameObject>();
foreach (GameObject u in units)
{
if (u.activeInHierarchy)
{
myUnits.Add(u);
}
}
return myUnits;
}
public int getActiveUnitsCount()
{
int alive = 0;
foreach (GameObject u in units)
{
if (u.activeInHierarchy)
{
alive++;
}
}
return alive;
}
public int getPower()
{
int sum = 0;
foreach (GameObject u in units)
{
if (u.activeInHierarchy)
{
sum += u.GetComponent<UnitManager>().power;
}
}
return sum;
}
public float getMovementRadius()
{
return movementDistance;
}
public float getAttackRadius()
{
return attackDistance;
}
/// <summary>
/// Used to set the main color of a unit
/// </summary>
/// <param name="c"></param>
public void setColor(Color c)
{
myColor = c;
offColor = myColor / 2;
}
/// <summary>
/// //Called by sub squad scripts once units are intialized
/// </summary>
public void paintColor()
{
foreach (GameObject g in units)
{
foreach (Transform child in g.transform)
{
if (child.name == "UnitBase")
{
child.GetComponent<Renderer>().material.color = myColor;
break;
}
}
}
}
[RPC]
public void activeSquadColor(bool active)
{
foreach (GameObject g in units)
{
if(g.activeInHierarchy)
foreach (Transform child in g.transform)
{
if (child.name == "UnitBase")
{
if (active)
child.GetComponent<Renderer>().material.color = myColor;
else
child.GetComponent<Renderer>().material.color = offColor;
break;
}
}
}
}
void OnGUI()
{
if (dead)
return;
if (tex != null && (inCover || behindWall))
{
float sizeMod = 15;
Vector3 guiPosition = Camera.main.WorldToScreenPoint(transform.position);
float camDistance = Camera.main.GetComponent<CameraController>().distance;
guiPosition.y = Screen.height - guiPosition.y;
Rect rect = new Rect((guiPosition.x - tex.width / (camDistance / sizeMod) / 2.0f), (guiPosition.y - tex.height / (camDistance / sizeMod) / 2.0f), tex.width / (camDistance / sizeMod), tex.height / (camDistance / sizeMod));
GUI.DrawTexture(rect, tex);
}
if (selectorRed != null && targeted)
{
float sizeMod = 15;
Vector3 guiPosition = Camera.main.WorldToScreenPoint(transform.position);
float camDistance = Camera.main.GetComponent<CameraController>().distance;
guiPosition.y = Screen.height - guiPosition.y;
Rect rect = new Rect((guiPosition.x - selectorRed.width / (camDistance / sizeMod) / 2.0f), (guiPosition.y - selectorRed.height / (camDistance / sizeMod) / 2.0f), selectorRed.width / (camDistance / sizeMod), selectorRed.height / (camDistance / sizeMod));
GUI.DrawTexture(rect, selectorRed);
}
if(selectorGreen != null && selected)
{
float sizeMod = 15;
Vector3 guiPosition = Camera.main.WorldToScreenPoint(transform.position);
float camDistance = Camera.main.GetComponent<CameraController>().distance;
guiPosition.y = Screen.height - guiPosition.y;
Rect rect = new Rect((guiPosition.x - selectorGreen.width / (camDistance / sizeMod) / 2.0f), (guiPosition.y - selectorGreen.height / (camDistance / sizeMod) / 2.0f), selectorGreen.width / (camDistance / sizeMod), selectorGreen.height / (camDistance / sizeMod));
GUI.DrawTexture(rect, selectorGreen);
}
}
void OnSerializeNetworkView(BitStream stream, NetworkMessageInfo info)
{
Vector3 syncPosition = Vector3.zero;
Vector3 syncVelocity = Vector3.zero;
bool cover = false;
bool wall = false;
if (stream.isWriting)
{
syncPosition = rb.position;
cover = inCover;
//wall = behindWall;
syncVelocity = rb.velocity;
stream.Serialize(ref syncPosition);
stream.Serialize(ref cover);
//stream.Serialize(ref wall);
stream.Serialize(ref syncVelocity);
}
else
{
stream.Serialize(ref syncPosition);
stream.Serialize(ref cover);
//stream.Serialize(ref wall);
stream.Serialize(ref syncVelocity);
syncTime = 0f;
syncDelay = Time.time - lastSynchronizationTime;
lastSynchronizationTime = Time.time;
syncEndPosition = syncPosition + syncVelocity*syncDelay;
syncStartPosition = rb.position;
//behindWall = wall;
inCover = cover;
}
}
[RPC]
public void setBehindWall(bool val)
{
behindWall = val;
}
private void SyncedMovement()
{
syncTime += Time.deltaTime;
rb.position = Vector3.Lerp(syncStartPosition, syncEndPosition, syncTime / syncDelay);
lightPiece.transform.position = rb.position;
for (int i = 0; i < units.Length; i++)
{
units[i].transform.position = unitTargets[i].position;
transform.rotation = Quaternion.identity;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
namespace SIL.Extensions
{
public static class StringExtensions
{
public const char kObjReplacementChar = '\uFFFC';
public static List<string> SplitTrimmed(this string s, char separator)
{
if (s.Trim() == string.Empty)
return new List<string>();
var x = s.Split(separator);
var r = new List<string>();
foreach (var part in x)
{
var trim = part.Trim();
if (trim != string.Empty)
{
r.Add(trim);
}
}
return r;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets an int array from a comma-delimited string of numbers.
/// </summary>
/// ------------------------------------------------------------------------------------
public static int[] ToIntArray(this string str)
{
List<int> array = new List<int>();
if (str != null)
{
string[] pieces = str.Split(',');
foreach (string piece in pieces)
{
int i;
if (int.TryParse(piece, out i))
array.Add(i);
}
}
return array.ToArray();
}
/// <summary>
/// normal string.format will throw if it can't do the format; this is dangerous if you're, for example
/// just logging stuff that might contain messed up strings (myWorkSafe paths)
/// </summary>
public static string FormatWithErrorStringInsteadOfException(this string format, params object[] args)
{
try
{
if (args.Length == 0)
return format;
else
return string.Format(format, args);
}
catch (Exception e)
{
string argList = "";
foreach (var arg in args)
{
argList = argList + arg + ",";
}
argList = argList.Trim(new char[] {','});
return "FormatWithErrorStringInsteadOfException(" + format + "," + argList + ") Exception: " + e.Message;
}
}
public static string EscapeAnyUnicodeCharactersIllegalInXml(this string text)
{
//we actually want to preserve html markup, just escape the disallowed unicode characters
text = text.Replace("<", "_lt;");
text = text.Replace(">", "_gt;");
text = text.Replace("&", "_amp;");
text = text.Replace("\"", "_quot;");
text = text.Replace("'", "_apos;");
text = EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml(text);
//put it back, now
text = text.Replace("_lt;", "<");
text = text.Replace("_gt;", ">");
text = text.Replace("_amp;", "&");
text = text.Replace("_quot;", "\"");
text = text.Replace("_apos;", "'");
// Also ensure NFC form for XML output.
return text.Normalize(NormalizationForm.FormC);
}
private static object _lockUsedForEscaping = new object();
private static StringBuilder _bldrUsedForEscaping;
private static XmlWriterSettings _settingsUsedForEscaping;
private static XmlWriter _writerUsedForEscaping;
public static string EscapeSoXmlSeesAsPureTextAndEscapeCharactersIllegalInXml(this string text)
{
lock (_lockUsedForEscaping)
{
if (_bldrUsedForEscaping == null)
_bldrUsedForEscaping = new StringBuilder();
else
_bldrUsedForEscaping.Clear();
if (_settingsUsedForEscaping == null)
{
_settingsUsedForEscaping = new XmlWriterSettings();
_settingsUsedForEscaping.NewLineHandling = NewLineHandling.None; // don't fiddle with newlines
_settingsUsedForEscaping.ConformanceLevel = ConformanceLevel.Fragment; // allow just text by itself
_settingsUsedForEscaping.CheckCharacters = false; // allow invalid characters in
}
if (_writerUsedForEscaping == null)
_writerUsedForEscaping = XmlWriter.Create(_bldrUsedForEscaping, _settingsUsedForEscaping);
_writerUsedForEscaping.WriteString(text);
_writerUsedForEscaping.Flush();
return _bldrUsedForEscaping.ToString();
}
}
/// <summary>
/// Similar to Path.Combine, but it combines as may parts as you have into a single, platform-appropriate path.
/// </summary>
/// <example> string path = "my".Combine("stuff", "toys", "ball.txt")</example>
public static string CombineForPath(this string rootPath, params string[] partsOfThePath)
{
string result = rootPath.ToString();
foreach (var s in partsOfThePath)
{
result = Path.Combine(result, s);
}
return result;
}
/// <summary>
/// Finds and replaces invalid characters in a filename
/// </summary>
/// <param name="input">the string to clean</param>
/// <param name="errorChar">the character which replaces bad characters</param>
public static string SanitizeFilename(this string input, char errorChar)
{
var invalidFilenameChars = System.IO.Path.GetInvalidFileNameChars();
Array.Sort(invalidFilenameChars);
return Sanitize(input, invalidFilenameChars, errorChar);
}
/// <summary>
/// Finds and replaces invalid characters in a path
/// </summary>
/// <param name="input">the string to clean</param>
/// <param name="errorChar">the character which replaces bad characters</param>
public static string SanitizePath(this string input, char errorChar)
{
var invalidPathChars = System.IO.Path.GetInvalidPathChars();
Array.Sort(invalidPathChars);
return Sanitize(input, invalidPathChars, errorChar);
}
private static string Sanitize(string input, char[] invalidChars, char errorChar)
{
// null always sanitizes to null
if (input == null)
{
return null;
}
var result = new StringBuilder();
foreach (var characterToTest in input)
{
// we binary search for the character in the invalid set. This should be lightning fast.
if (Array.BinarySearch(invalidChars, characterToTest) >= 0)
{
result.Append(errorChar);
}
else
{
result.Append(characterToTest);
}
}
return result.ToString();
}
/// <summary>
/// Make the first letter of the string upper-case, and the rest lower case. Does not consider words.
/// </summary>
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
var letters = source.ToLowerInvariant().ToCharArray();
letters[0] = char.ToUpperInvariant(letters[0]);
return new string(letters);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Removes the ampersand accerlerator prefix from the specified text.
/// </summary>
/// ------------------------------------------------------------------------------------
public static string RemoveAcceleratorPrefix(this string text)
{
text = text.Replace("&&", kObjReplacementChar.ToString(CultureInfo.InvariantCulture));
text = text.Replace("&", string.Empty);
return text.Replace(kObjReplacementChar.ToString(CultureInfo.InvariantCulture), "&");
}
/// <summary>
/// Trims the string, and returns null if the result is zero length
/// </summary>
/// <param name="value"></param>
/// <param name="trimChars"></param>
/// <returns></returns>
public static string NullTrim(this string value, char[] trimChars)
{
if (string.IsNullOrEmpty(value))
return null;
value = value.Trim(trimChars);
return string.IsNullOrEmpty(value) ? null : value;
}
/// <summary>
/// Trims the string, and returns null if the result is zero length
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string NullTrim(this string value)
{
return value.NullTrim(null);
}
/// <summary>
/// Determines whether the string contains the specified string using the specified comparison.
/// </summary>
public static bool Contains(this String stringToSearch, String stringToFind, StringComparison comparison)
{
int ind = stringToSearch.IndexOf(stringToFind, comparison); //This comparer should be extended to be "-"/"_" insensitive as well.
return ind != -1;
}
/// <summary>
/// Determines whether the list of string contains the specified string using the specified comparison.
/// </summary>
public static bool Contains(this IEnumerable<string> listToSearch, string itemToFind, StringComparison comparison)
{
foreach (string s in listToSearch)
{
if (s.Equals(itemToFind, comparison))
{
return true;
}
}
return false;
}
}
}
| |
/*
* 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
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Apache.Ignite.Core.Common;
using Microsoft.CSharp;
using NUnit.Framework;
/// <summary>
/// Dll loading test.
/// </summary>
public class LoadDllTest
{
/// <summary>
///
/// </summary>
[SetUp]
public void SetUp()
{
TestUtils.KillProcesses();
}
/// <summary>
///
/// </summary>
[TearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
///
/// </summary>
[Test]
public void TestLoadFromGac()
{
Assert.False(IsLoaded("System.Data.Linq"));
var cfg = new IgniteConfiguration
{
SpringConfigUrl = "config\\start-test-grid3.xml",
Assemblies =
new List<string>
{
"System.Data.Linq,Culture=neutral,Version=1.0.0.0,PublicKeyToken=b77a5c561934e089"
},
JvmClasspath = TestUtils.CreateTestClasspath()
};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.True(IsLoaded("System.Data.Linq"));
}
/// <summary>
///
/// </summary>
[Test]
public void TestLoadFromCurrentDir()
{
Assert.False(IsLoaded("testDll"));
GenerateDll("testDll.dll");
var cfg = new IgniteConfiguration
{
SpringConfigUrl = "config\\start-test-grid3.xml",
Assemblies = new List<string> {"testDll.dll"},
JvmClasspath = TestUtils.CreateTestClasspath()
};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.True(IsLoaded("testDll"));
}
/// <summary>
///
/// </summary>
[Test]
public void TestLoadAllDllInDir()
{
var dirInfo = Directory.CreateDirectory(Path.GetTempPath() + "/testDlls");
Assert.False(IsLoaded("dllFromDir1"));
Assert.False(IsLoaded("dllFromDir2"));
GenerateDll(dirInfo.FullName + "/dllFromDir1.dll");
GenerateDll(dirInfo.FullName + "/dllFromDir2.dll");
File.WriteAllText(dirInfo.FullName + "/notADll.txt", "notADll");
var cfg = new IgniteConfiguration
{
SpringConfigUrl = "config\\start-test-grid3.xml",
Assemblies = new List<string> {dirInfo.FullName},
JvmClasspath = TestUtils.CreateTestClasspath()
};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.True(IsLoaded("dllFromDir1"));
Assert.True(IsLoaded("dllFromDir2"));
}
/// <summary>
///
/// </summary>
[Test]
public void TestLoadFromCurrentDirByName()
{
Assert.False(IsLoaded("testDllByName"));
GenerateDll("testDllByName.dll");
var cfg = new IgniteConfiguration
{
SpringConfigUrl = "config\\start-test-grid3.xml",
Assemblies = new List<string> {"testDllByName"},
JvmClasspath = TestUtils.CreateTestClasspath()
};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.True(IsLoaded("testDllByName"));
}
/// <summary>
///
/// </summary>
[Test]
public void TestLoadByAbsoluteUri()
{
var dllPath = Path.GetTempPath() + "/tempDll.dll";
Assert.False(IsLoaded("tempDll"));
GenerateDll(dllPath);
var cfg = new IgniteConfiguration
{
SpringConfigUrl = "config\\start-test-grid3.xml",
Assemblies = new List<string> {dllPath},
JvmClasspath = TestUtils.CreateTestClasspath()
};
var grid = Ignition.Start(cfg);
Assert.IsNotNull(grid);
Assert.True(IsLoaded("tempDll"));
}
/// <summary>
///
/// </summary>
[Test]
public void TestLoadUnexistingLibrary()
{
var cfg = new IgniteConfiguration
{
SpringConfigUrl = "config\\start-test-grid3.xml",
Assemblies = new List<string> {"unexistingAssembly.820482.dll"},
JvmClasspath = TestUtils.CreateTestClasspath()
};
try
{
Ignition.Start(cfg);
Assert.Fail("Grid has been started with broken configuration.");
}
catch (IgniteException)
{
}
}
/// <summary>
///
/// </summary>
/// <param name="outputPath"></param>
private void GenerateDll(string outputPath)
{
var codeProvider = new CSharpCodeProvider();
#pragma warning disable 0618
var icc = codeProvider.CreateCompiler();
#pragma warning restore 0618
var parameters = new CompilerParameters
{
GenerateExecutable = false,
OutputAssembly = outputPath
};
var src = "namespace GridGain.Client.Test { public class Foo {}}";
var results = icc.CompileAssemblyFromSource(parameters, src);
Assert.False(results.Errors.HasErrors);
}
/// <summary>
/// Determines whether the specified assembly is loaded.
/// </summary>
/// <param name="asmName">Name of the assembly.</param>
private static bool IsLoaded(string asmName)
{
return AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == asmName);
}
}
}
| |
using System;
namespace UnityEngine.Rendering.LWRP
{
public struct ShadowSliceData
{
public Matrix4x4 viewMatrix;
public Matrix4x4 projectionMatrix;
public Matrix4x4 shadowTransform;
public int offsetX;
public int offsetY;
public int resolution;
public void Clear()
{
viewMatrix = Matrix4x4.identity;
projectionMatrix = Matrix4x4.identity;
shadowTransform = Matrix4x4.identity;
offsetX = offsetY = 0;
resolution = 1024;
}
}
public static class ShadowUtils
{
private static readonly RenderTextureFormat m_ShadowmapFormat;
private static readonly bool m_ForceShadowPointSampling;
static ShadowUtils()
{
m_ShadowmapFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Shadowmap)
? RenderTextureFormat.Shadowmap
: RenderTextureFormat.Depth;
m_ForceShadowPointSampling = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal &&
GraphicsSettings.HasShaderDefine(Graphics.activeTier, BuiltinShaderDefine.UNITY_METAL_SHADOWS_USE_POINT_FILTERING);
}
public static bool ExtractDirectionalLightMatrix(ref CullingResults cullResults, ref ShadowData shadowData, int shadowLightIndex, int cascadeIndex, int shadowmapWidth, int shadowmapHeight, int shadowResolution, float shadowNearPlane, out Vector4 cascadeSplitDistance, out ShadowSliceData shadowSliceData, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix)
{
ShadowSplitData splitData;
bool success = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(shadowLightIndex,
cascadeIndex, shadowData.mainLightShadowCascadesCount, shadowData.mainLightShadowCascadesSplit, shadowResolution, shadowNearPlane, out viewMatrix, out projMatrix,
out splitData);
cascadeSplitDistance = splitData.cullingSphere;
shadowSliceData.offsetX = (cascadeIndex % 2) * shadowResolution;
shadowSliceData.offsetY = (cascadeIndex / 2) * shadowResolution;
shadowSliceData.resolution = shadowResolution;
shadowSliceData.viewMatrix = viewMatrix;
shadowSliceData.projectionMatrix = projMatrix;
shadowSliceData.shadowTransform = GetShadowTransform(projMatrix, viewMatrix);
// If we have shadow cascades baked into the atlas we bake cascade transform
// in each shadow matrix to save shader ALU and L/S
if (shadowData.mainLightShadowCascadesCount > 1)
ApplySliceTransform(ref shadowSliceData, shadowmapWidth, shadowmapHeight);
return success;
}
public static bool ExtractSpotLightMatrix(ref CullingResults cullResults, ref ShadowData shadowData, int shadowLightIndex, out Matrix4x4 shadowMatrix, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix)
{
ShadowSplitData splitData;
bool success = cullResults.ComputeSpotShadowMatricesAndCullingPrimitives(shadowLightIndex, out viewMatrix, out projMatrix, out splitData);
shadowMatrix = GetShadowTransform(projMatrix, viewMatrix);
return success;
}
public static void RenderShadowSlice(CommandBuffer cmd, ref ScriptableRenderContext context,
ref ShadowSliceData shadowSliceData, ref ShadowDrawingSettings settings,
Matrix4x4 proj, Matrix4x4 view)
{
cmd.SetViewport(new Rect(shadowSliceData.offsetX, shadowSliceData.offsetY, shadowSliceData.resolution, shadowSliceData.resolution));
cmd.EnableScissorRect(new Rect(shadowSliceData.offsetX + 4, shadowSliceData.offsetY + 4, shadowSliceData.resolution - 8, shadowSliceData.resolution - 8));
cmd.SetViewProjectionMatrices(view, proj);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
context.DrawShadows(ref settings);
cmd.DisableScissorRect();
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
}
public static int GetMaxTileResolutionInAtlas(int atlasWidth, int atlasHeight, int tileCount)
{
int resolution = Mathf.Min(atlasWidth, atlasHeight);
int currentTileCount = atlasWidth / resolution * atlasHeight / resolution;
while (currentTileCount < tileCount)
{
resolution = resolution >> 1;
currentTileCount = atlasWidth / resolution * atlasHeight / resolution;
}
return resolution;
}
public static void ApplySliceTransform(ref ShadowSliceData shadowSliceData, int atlasWidth, int atlasHeight)
{
Matrix4x4 sliceTransform = Matrix4x4.identity;
float oneOverAtlasWidth = 1.0f / atlasWidth;
float oneOverAtlasHeight = 1.0f / atlasHeight;
sliceTransform.m00 = shadowSliceData.resolution * oneOverAtlasWidth;
sliceTransform.m11 = shadowSliceData.resolution * oneOverAtlasHeight;
sliceTransform.m03 = shadowSliceData.offsetX * oneOverAtlasWidth;
sliceTransform.m13 = shadowSliceData.offsetY * oneOverAtlasHeight;
// Apply shadow slice scale and offset
shadowSliceData.shadowTransform = sliceTransform * shadowSliceData.shadowTransform;
}
public static Vector4 GetShadowBias(ref VisibleLight shadowLight, int shadowLightIndex, ref ShadowData shadowData, Matrix4x4 lightProjectionMatrix, float shadowResolution)
{
if (shadowLightIndex < 0 || shadowLightIndex >= shadowData.bias.Count)
{
Debug.LogWarning(string.Format("{0} is not a valid light index.", shadowLightIndex));
return Vector4.zero;
}
float frustumSize;
if (shadowLight.lightType == LightType.Directional)
{
// Frustum size is guaranteed to be a cube as we wrap shadow frustum around a sphere
frustumSize = 2.0f / lightProjectionMatrix.m00;
}
else if (shadowLight.lightType == LightType.Spot)
{
// For perspective projections, shadow texel size varies with depth
// It will only work well if done in receiver side in the pixel shader. Currently LWRP
// do bias on caster side in vertex shader. When we add shader quality tiers we can properly
// handle this. For now, as a poor approximation we do a constant bias and compute the size of
// the frustum as if it was orthogonal considering the size at mid point between near and far planes.
// Depending on how big the light range is, it will be good enough with some tweaks in bias
frustumSize = Mathf.Tan(shadowLight.spotAngle * 0.5f * Mathf.Deg2Rad) * shadowLight.range;
}
else
{
Debug.LogWarning("Only spot and directional shadow casters are supported in lightweight pipeline");
frustumSize = 0.0f;
}
// depth and normal bias scale is in shadowmap texel size in world space
float texelSize = frustumSize / shadowResolution;
float depthBias = -shadowData.bias[shadowLightIndex].x * texelSize;
float normalBias = -shadowData.bias[shadowLightIndex].y * texelSize;
if (shadowData.supportsSoftShadows)
{
// TODO: depth and normal bias assume sample is no more than 1 texel away from shadowmap
// This is not true with PCF. Ideally we need to do either
// cone base bias (based on distance to center sample)
// or receiver place bias based on derivatives.
// For now we scale it by the PCF kernel size (5x5)
const float kernelRadius = 2.5f;
depthBias *= kernelRadius;
normalBias *= kernelRadius;
}
return new Vector4(depthBias, normalBias, 0.0f, 0.0f);
}
public static void SetupShadowCasterConstantBuffer(CommandBuffer cmd, ref VisibleLight shadowLight, Vector4 shadowBias)
{
Vector3 lightDirection = -shadowLight.localToWorldMatrix.GetColumn(2);
cmd.SetGlobalVector("_ShadowBias", shadowBias);
cmd.SetGlobalVector("_LightDirection", new Vector4(lightDirection.x, lightDirection.y, lightDirection.z, 0.0f));
}
public static RenderTexture GetTemporaryShadowTexture(int width, int height, int bits)
{
var shadowTexture = RenderTexture.GetTemporary(width, height, bits, m_ShadowmapFormat);
shadowTexture.filterMode = m_ForceShadowPointSampling ? FilterMode.Point : FilterMode.Bilinear;
shadowTexture.wrapMode = TextureWrapMode.Clamp;
return shadowTexture;
}
static Matrix4x4 GetShadowTransform(Matrix4x4 proj, Matrix4x4 view)
{
// Currently CullResults ComputeDirectionalShadowMatricesAndCullingPrimitives doesn't
// apply z reversal to projection matrix. We need to do it manually here.
if (SystemInfo.usesReversedZBuffer)
{
proj.m20 = -proj.m20;
proj.m21 = -proj.m21;
proj.m22 = -proj.m22;
proj.m23 = -proj.m23;
}
Matrix4x4 worldToShadow = proj * view;
var textureScaleAndBias = Matrix4x4.identity;
textureScaleAndBias.m00 = 0.5f;
textureScaleAndBias.m11 = 0.5f;
textureScaleAndBias.m22 = 0.5f;
textureScaleAndBias.m03 = 0.5f;
textureScaleAndBias.m23 = 0.5f;
textureScaleAndBias.m13 = 0.5f;
// Apply texture scale and offset to save a MAD in shader.
return textureScaleAndBias * worldToShadow;
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Dynamic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Cache;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Frapid.Framework;
using Frapid.Framework.Extensions;
namespace Frapid.Config.Api
{
/// <summary>
/// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Filters.
/// </summary>
[RoutePrefix("api/v1.0/config/filter")]
public class FilterController : FrapidApiController
{
/// <summary>
/// The Filter repository.
/// </summary>
private readonly IFilterRepository FilterRepository;
public FilterController()
{
this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>();
this._UserId = AppUsers.GetCurrent().View.UserId.To<int>();
this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>();
this._Catalog = AppUsers.GetCatalog();
this.FilterRepository = new Frapid.Config.DataAccess.Filter
{
_Catalog = this._Catalog,
_LoginId = this._LoginId,
_UserId = this._UserId
};
}
public FilterController(IFilterRepository repository, string catalog, LoginView view)
{
this._LoginId = view.LoginId.To<long>();
this._UserId = view.UserId.To<int>();
this._OfficeId = view.OfficeId.To<int>();
this._Catalog = catalog;
this.FilterRepository = repository;
}
public long _LoginId { get; }
public int _UserId { get; private set; }
public int _OfficeId { get; private set; }
public string _Catalog { get; }
/// <summary>
/// Creates meta information of "filter" entity.
/// </summary>
/// <returns>Returns the "filter" meta information to perform CRUD operation.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("meta")]
[Route("~/api/config/filter/meta")]
[Authorize]
public EntityView GetEntityView()
{
if (this._LoginId == 0)
{
return new EntityView();
}
return new EntityView
{
PrimaryKey = "filter_id",
Columns = new List<EntityColumn>()
{
new EntityColumn { ColumnName = "filter_id", PropertyName = "FilterId", DataType = "long", DbDataType = "int8", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "object_name", PropertyName = "ObjectName", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "filter_name", PropertyName = "FilterName", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "is_default", PropertyName = "IsDefault", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "is_default_admin", PropertyName = "IsDefaultAdmin", DataType = "bool", DbDataType = "bool", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "filter_statement", PropertyName = "FilterStatement", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 12 },
new EntityColumn { ColumnName = "column_name", PropertyName = "ColumnName", DataType = "string", DbDataType = "text", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "filter_condition", PropertyName = "FilterCondition", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "filter_value", PropertyName = "FilterValue", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "filter_and_value", PropertyName = "FilterAndValue", DataType = "string", DbDataType = "text", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 },
new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }
}
};
}
/// <summary>
/// Counts the number of filters.
/// </summary>
/// <returns>Returns the count of the filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count")]
[Route("~/api/config/filter/count")]
[Authorize]
public long Count()
{
try
{
return this.FilterRepository.Count();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns all collection of filter.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("all")]
[Route("~/api/config/filter/all")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Filter> GetAll()
{
try
{
return this.FilterRepository.GetAll();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns collection of filter for export.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("export")]
[Route("~/api/config/filter/export")]
[Authorize]
public IEnumerable<dynamic> Export()
{
try
{
return this.FilterRepository.Export();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns an instance of filter.
/// </summary>
/// <param name="filterId">Enter FilterId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("{filterId}")]
[Route("~/api/config/filter/{filterId}")]
[Authorize]
public Frapid.Config.Entities.Filter Get(long filterId)
{
try
{
return this.FilterRepository.Get(filterId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
[AcceptVerbs("GET", "HEAD")]
[Route("get")]
[Route("~/api/config/filter/get")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Filter> Get([FromUri] long[] filterIds)
{
try
{
return this.FilterRepository.Get(filterIds);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the first instance of filter.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("first")]
[Route("~/api/config/filter/first")]
[Authorize]
public Frapid.Config.Entities.Filter GetFirst()
{
try
{
return this.FilterRepository.GetFirst();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the previous instance of filter.
/// </summary>
/// <param name="filterId">Enter FilterId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("previous/{filterId}")]
[Route("~/api/config/filter/previous/{filterId}")]
[Authorize]
public Frapid.Config.Entities.Filter GetPrevious(long filterId)
{
try
{
return this.FilterRepository.GetPrevious(filterId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the next instance of filter.
/// </summary>
/// <param name="filterId">Enter FilterId to search for.</param>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("next/{filterId}")]
[Route("~/api/config/filter/next/{filterId}")]
[Authorize]
public Frapid.Config.Entities.Filter GetNext(long filterId)
{
try
{
return this.FilterRepository.GetNext(filterId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Returns the last instance of filter.
/// </summary>
/// <returns></returns>
[AcceptVerbs("GET", "HEAD")]
[Route("last")]
[Route("~/api/config/filter/last")]
[Authorize]
public Frapid.Config.Entities.Filter GetLast()
{
try
{
return this.FilterRepository.GetLast();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 filters on each page, sorted by the property FilterId.
/// </summary>
/// <returns>Returns the first page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("")]
[Route("~/api/config/filter")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Filter> GetPaginatedResult()
{
try
{
return this.FilterRepository.GetPaginatedResult();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a paginated collection containing 10 filters on each page, sorted by the property FilterId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset.</param>
/// <returns>Returns the requested page from the collection.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("page/{pageNumber}")]
[Route("~/api/config/filter/page/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Filter> GetPaginatedResult(long pageNumber)
{
try
{
return this.FilterRepository.GetPaginatedResult(pageNumber);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of filters using the supplied filter(s).
/// </summary>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the count of filtered filters.</returns>
[AcceptVerbs("POST")]
[Route("count-where")]
[Route("~/api/config/filter/count-where")]
[Authorize]
public long CountWhere([FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.FilterRepository.CountWhere(f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 filters on each page, sorted by the property FilterId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filters">The list of filter conditions.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("POST")]
[Route("get-where/{pageNumber}")]
[Route("~/api/config/filter/get-where/{pageNumber}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Filter> GetWhere(long pageNumber, [FromBody]JArray filters)
{
try
{
List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer());
return this.FilterRepository.GetWhere(pageNumber, f);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Counts the number of filters using the supplied filter name.
/// </summary>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the count of filtered filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("count-filtered/{filterName}")]
[Route("~/api/config/filter/count-filtered/{filterName}")]
[Authorize]
public long CountFiltered(string filterName)
{
try
{
return this.FilterRepository.CountFiltered(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Creates a filtered and paginated collection containing 10 filters on each page, sorted by the property FilterId.
/// </summary>
/// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param>
/// <param name="filterName">The named filter.</param>
/// <returns>Returns the requested page from the collection using the supplied filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("get-filtered/{pageNumber}/{filterName}")]
[Route("~/api/config/filter/get-filtered/{pageNumber}/{filterName}")]
[Authorize]
public IEnumerable<Frapid.Config.Entities.Filter> GetFiltered(long pageNumber, string filterName)
{
try
{
return this.FilterRepository.GetFiltered(pageNumber, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Displayfield is a lightweight key/value collection of filters.
/// </summary>
/// <returns>Returns an enumerable key/value collection of filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("display-fields")]
[Route("~/api/config/filter/display-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields()
{
try
{
return this.FilterRepository.GetDisplayFields();
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for filters.
/// </summary>
/// <returns>Returns an enumerable custom field collection of filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields")]
[Route("~/api/config/filter/custom-fields")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields()
{
try
{
return this.FilterRepository.GetCustomFields(null);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// A custom field is a user defined field for filters.
/// </summary>
/// <returns>Returns an enumerable custom field collection of filters.</returns>
[AcceptVerbs("GET", "HEAD")]
[Route("custom-fields/{resourceId}")]
[Route("~/api/config/filter/custom-fields/{resourceId}")]
[Authorize]
public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId)
{
try
{
return this.FilterRepository.GetCustomFields(resourceId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds or edits your instance of Filter class.
/// </summary>
/// <param name="filter">Your instance of filters class to add or edit.</param>
[AcceptVerbs("POST")]
[Route("add-or-edit")]
[Route("~/api/config/filter/add-or-edit")]
[Authorize]
public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form)
{
dynamic filter = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer());
List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer());
if (filter == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
return this.FilterRepository.AddOrEdit(filter, customFields);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Adds your instance of Filter class.
/// </summary>
/// <param name="filter">Your instance of filters class to add.</param>
[AcceptVerbs("POST")]
[Route("add/{filter}")]
[Route("~/api/config/filter/add/{filter}")]
[Authorize]
public void Add(Frapid.Config.Entities.Filter filter)
{
if (filter == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.FilterRepository.Add(filter);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Edits existing record with your instance of Filter class.
/// </summary>
/// <param name="filter">Your instance of Filter class to edit.</param>
/// <param name="filterId">Enter the value for FilterId in order to find and edit the existing record.</param>
[AcceptVerbs("PUT")]
[Route("edit/{filterId}")]
[Route("~/api/config/filter/edit/{filterId}")]
[Authorize]
public void Edit(long filterId, [FromBody] Frapid.Config.Entities.Filter filter)
{
if (filter == null)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed));
}
try
{
this.FilterRepository.Update(filter, filterId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
private List<ExpandoObject> ParseCollection(JArray collection)
{
return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
}
/// <summary>
/// Adds or edits multiple instances of Filter class.
/// </summary>
/// <param name="collection">Your collection of Filter class to bulk import.</param>
/// <returns>Returns list of imported filterIds.</returns>
/// <exception cref="DataAccessException">Thrown when your any Filter class in the collection is invalid or malformed.</exception>
[AcceptVerbs("POST")]
[Route("bulk-import")]
[Route("~/api/config/filter/bulk-import")]
[Authorize]
public List<object> BulkImport([FromBody]JArray collection)
{
List<ExpandoObject> filterCollection = this.ParseCollection(collection);
if (filterCollection == null || filterCollection.Count.Equals(0))
{
return null;
}
try
{
return this.FilterRepository.BulkImport(filterCollection);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of Filter class via FilterId.
/// </summary>
/// <param name="filterId">Enter the value for FilterId in order to find and delete the existing record.</param>
[AcceptVerbs("DELETE")]
[Route("delete/{filterId}")]
[Route("~/api/config/filter/delete/{filterId}")]
[Authorize]
public void Delete(long filterId)
{
try
{
this.FilterRepository.Delete(filterId);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
#if !DEBUG
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
#endif
}
/// <summary>
/// Deletes an existing instance of Filter class via FilterName.
/// </summary>
/// <param name="filterName">Enter the value for FilterName in order to find and delete the existing record(s).</param>
[AcceptVerbs("DELETE")]
[Route("delete/by-name/{filterName}")]
[Route("~/api/config/filter/delete/by-name/{filterName}")]
public void Delete(string filterName)
{
try
{
this.FilterRepository.Delete(filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException ex)
{
throw new HttpResponseException(new HttpResponseMessage
{
Content = new StringContent(ex.Message),
StatusCode = HttpStatusCode.InternalServerError
});
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
[AcceptVerbs("PUT")]
[Route("recreate/{objectName}/{filterName}")]
[Route("~/api/config/filter/recreate/{objectName}/{filterName}")]
public void RecreateFilters(string objectName, string filterName, [FromBody]dynamic collection)
{
List<Frapid.Config.Entities.Filter> filters = JsonConvert.DeserializeObject<List<Frapid.Config.Entities.Filter>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings());
try
{
this.FilterRepository.RecreateFilters(objectName, filterName, filters);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException)
{
throw;
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
[AcceptVerbs("PUT")]
[Route("make-default/{objectName}/{filterName}")]
[Route("~/api/config/filter/make-default/{objectName}/{filterName}")]
public void MakeDefault(string objectName, string filterName)
{
try
{
this.FilterRepository.MakeDefault(objectName, filterName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException)
{
throw;
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
[AcceptVerbs("PUT")]
[Route("remove-default/{objectName}")]
[Route("~/api/config/filter/remove-default/{objectName}")]
public void RemoveDefault(string objectName)
{
try
{
this.FilterRepository.RemoveDefault(objectName);
}
catch (UnauthorizedException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
}
catch (DataAccessException)
{
throw;
}
catch
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Runtime.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Xml;
using System.Linq;
using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>;
using System.Security;
//Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved
[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")]
internal class KeyValuePairAdapter<K, T>
{
private K _kvpKey;
private T _kvpValue;
public KeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
_kvpKey = kvPair.Key;
_kvpValue = kvPair.Value;
}
[DataMember(Name = "key")]
public K Key
{
get
{
return _kvpKey;
}
set
{
_kvpKey = value;
}
}
[DataMember(Name = "value")]
public T Value
{
get
{
return _kvpValue;
}
set
{
_kvpValue = value;
}
}
internal KeyValuePair<K, T> GetKeyValuePair()
{
return new KeyValuePair<K, T>(_kvpKey, _kvpValue);
}
internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair)
{
return new KeyValuePairAdapter<K, T>(kvPair);
}
}
[DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
#if USE_REFEMIT
public struct KeyValue<K, V>
#else
internal struct KeyValue<K, V>
#endif
{
private K _key;
private V _value;
internal KeyValue(K key, V value)
{
_key = key;
_value = value;
}
[DataMember(IsRequired = true)]
public K Key
{
get { return _key; }
set { _key = value; }
}
[DataMember(IsRequired = true)]
public V Value
{
get { return _value; }
set { _value = value; }
}
}
#if NET_NATIVE
public enum CollectionKind : byte
#else
internal enum CollectionKind : byte
#endif
{
None,
GenericDictionary,
Dictionary,
GenericList,
GenericCollection,
List,
GenericEnumerable,
Collection,
Enumerable,
Array,
}
#if USE_REFEMIT || NET_NATIVE
public sealed class CollectionDataContract : DataContract
#else
internal sealed class CollectionDataContract : DataContract
#endif
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - XmlDictionaryString representing the XML element name for collection items.
/// statically cached and used from IL generated code.
/// </SecurityNote>
private XmlDictionaryString _collectionItemName;
[SecurityCritical]
/// <SecurityNote>
/// Critical - XmlDictionaryString representing the XML namespace for collection items.
/// statically cached and used from IL generated code.
/// </SecurityNote>
private XmlDictionaryString _childElementNamespace;
[SecurityCritical]
/// <SecurityNote>
/// Critical - internal DataContract representing the contract for collection items.
/// statically cached and used from IL generated code.
/// </SecurityNote>
private DataContract _itemContract;
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization.
/// Static fields are marked SecurityCritical or readonly to prevent
/// data from being modified or leaked to other components in appdomain.
/// </SecurityNote>
private CollectionDataContractCriticalHelper _helper;
[SecuritySafeCritical]
public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind))
{
InitCollectionDataContract(this);
}
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
[SecuritySafeCritical]
internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type))
{
InitCollectionDataContract(this);
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[SecuritySafeCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// Safe - doesn't leak anything
/// </SecurityNote>
private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage))
{
InitCollectionDataContract(GetSharedTypeContract(type));
}
[SecurityCritical]
/// <SecurityNote>
/// Critical - initializes SecurityCritical fields; called from all constructors
/// </SecurityNote>
private void InitCollectionDataContract(DataContract sharedTypeContract)
{
_helper = base.Helper as CollectionDataContractCriticalHelper;
_collectionItemName = _helper.CollectionItemName;
if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary)
{
_itemContract = _helper.ItemContract;
}
_helper.SharedTypeContract = sharedTypeContract;
}
private static Type[] KnownInterfaces
{
/// <SecurityNote>
/// Critical - fetches the critical knownInterfaces property
/// Safe - knownInterfaces only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return CollectionDataContractCriticalHelper.KnownInterfaces; }
}
internal CollectionKind Kind
{
/// <SecurityNote>
/// Critical - fetches the critical kind property
/// Safe - kind only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Kind; }
}
public Type ItemType
{
/// <SecurityNote>
/// Critical - fetches the critical itemType property
/// Safe - itemType only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.ItemType; }
set { _helper.ItemType = value; }
}
public DataContract ItemContract
{
/// <SecurityNote>
/// Critical - fetches the critical itemContract property
/// Safe - itemContract only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{
return _itemContract ?? _helper.ItemContract;
}
/// <SecurityNote>
/// Critical - sets the critical itemContract property
/// </SecurityNote>
[SecurityCritical]
set
{
_itemContract = value;
_helper.ItemContract = value;
}
}
internal DataContract SharedTypeContract
{
/// <SecurityNote>
/// Critical - fetches the critical sharedTypeContract property
/// Safe - sharedTypeContract only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.SharedTypeContract; }
}
public string ItemName
{
/// <SecurityNote>
/// Critical - fetches the critical itemName property
/// Safe - itemName only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.ItemName; }
/// <SecurityNote>
/// Critical - sets the critical itemName property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.ItemName = value; }
}
public XmlDictionaryString CollectionItemName
{
/// <SecurityNote>
/// Critical - fetches the critical collectionItemName property
/// Safe - collectionItemName only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _collectionItemName; }
set { _collectionItemName = value; }
}
public string KeyName
{
/// <SecurityNote>
/// Critical - fetches the critical keyName property
/// Safe - keyName only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KeyName; }
/// <SecurityNote>
/// Critical - sets the critical keyName property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.KeyName = value; }
}
public string ValueName
{
/// <SecurityNote>
/// Critical - fetches the critical valueName property
/// Safe - valueName only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.ValueName; }
/// <SecurityNote>
/// Critical - sets the critical valueName property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.ValueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
/// <SecurityNote>
/// Critical - fetches the critical childElementNamespace property
/// Safe - childElementNamespace only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_childElementNamespace == null)
{
lock (this)
{
if (_childElementNamespace == null)
{
if (_helper.ChildElementNamespace == null && !IsDictionary)
{
XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary());
Interlocked.MemoryBarrier();
_helper.ChildElementNamespace = tempChildElementNamespace;
}
_childElementNamespace = _helper.ChildElementNamespace;
}
}
}
return _childElementNamespace;
}
}
internal bool IsConstructorCheckRequired
{
/// <SecurityNote>
/// Critical - fetches the critical isConstructorCheckRequired property
/// Safe - isConstructorCheckRequired only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.IsConstructorCheckRequired; }
/// <SecurityNote>
/// Critical - sets the critical isConstructorCheckRequired property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.IsConstructorCheckRequired = value; }
}
internal MethodInfo GetEnumeratorMethod
{
/// <SecurityNote>
/// Critical - fetches the critical getEnumeratorMethod property
/// Safe - getEnumeratorMethod only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.GetEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
/// <SecurityNote>
/// Critical - fetches the critical addMethod property
/// Safe - addMethod only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.AddMethod; }
}
internal ConstructorInfo Constructor
{
/// <SecurityNote>
/// Critical - fetches the critical constructor property
/// Safe - constructor only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.Constructor; }
}
public override DataContractDictionary KnownDataContracts
{
/// <SecurityNote>
/// Critical - fetches the critical knownDataContracts property
/// Safe - knownDataContracts only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.KnownDataContracts; }
/// <SecurityNote>
/// Critical - sets the critical knownDataContracts property
/// </SecurityNote>
[SecurityCritical]
set
{ _helper.KnownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
/// <SecurityNote>
/// Critical - fetches the critical invalidCollectionInSharedContractMessage property
/// Safe - invalidCollectionInSharedContractMessage only needs to be protected for write
/// </SecurityNote>
[SecuritySafeCritical]
get
{ return _helper.InvalidCollectionInSharedContractMessage; }
}
#if !NET_NATIVE
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatWriterDelegate property
/// Safe - xmlFormatWriterDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatWriterDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatWriterDelegate == null)
{
XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatWriterDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatWriterDelegate;
}
}
#else
public XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { get; set; }
#endif
#if !NET_NATIVE
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatReaderDelegate property
/// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatReaderDelegate == null)
{
XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatReaderDelegate;
}
}
#else
public XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { get; set; }
#endif
#if !NET_NATIVE
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
/// <SecurityNote>
/// Critical - fetches the critical xmlFormatReaderDelegate property
/// Safe - xmlFormatReaderDelegate only needs to be protected for write; initialized in getter if null
/// </SecurityNote>
[SecuritySafeCritical]
get
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
lock (this)
{
if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null)
{
if (UnderlyingType.GetTypeInfo().IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType))));
}
Debug.Assert(AddMethod != null || Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property");
XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this);
Interlocked.MemoryBarrier();
_helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate;
}
}
}
return _helper.XmlFormatGetOnlyCollectionReaderDelegate;
}
}
#else
public XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { get; set; }
#endif
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds all state used for (de)serializing collections.
/// since the data is cached statically, we lock down access to it.
/// </SecurityNote>
private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper
{
private static Type[] s_knownInterfaces;
private Type _itemType;
private CollectionKind _kind;
private readonly MethodInfo _getEnumeratorMethod, _addMethod;
private readonly ConstructorInfo _constructor;
private DataContract _itemContract;
private DataContract _sharedTypeContract;
private DataContractDictionary _knownDataContracts;
private bool _isKnownTypeAttributeChecked;
private string _itemName;
private bool _itemNameSetExplicit;
private XmlDictionaryString _collectionItemName;
private string _keyName;
private string _valueName;
private XmlDictionaryString _childElementNamespace;
private string _invalidCollectionInSharedContractMessage;
private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate;
private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate;
private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate;
private bool _isConstructorCheckRequired = false;
internal static Type[] KnownInterfaces
{
get
{
if (s_knownInterfaces == null)
{
// Listed in priority order
s_knownInterfaces = new Type[]
{
Globals.TypeOfIDictionaryGeneric,
Globals.TypeOfIDictionary,
Globals.TypeOfIListGeneric,
Globals.TypeOfICollectionGeneric,
Globals.TypeOfIList,
Globals.TypeOfIEnumerableGeneric,
Globals.TypeOfICollection,
Globals.TypeOfIEnumerable
};
}
return s_knownInterfaces;
}
}
private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute)
{
_kind = kind;
if (itemType != null)
{
_itemType = itemType;
bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary);
string itemName = null, keyName = null, valueName = null;
if (collectionContractAttribute != null)
{
if (collectionContractAttribute.IsItemNameSetExplicitly)
{
if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType))));
itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName);
_itemNameSetExplicit = true;
}
if (collectionContractAttribute.IsKeyNameSetExplicitly)
{
if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName)));
keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName);
}
if (collectionContractAttribute.IsValueNameSetExplicitly)
{
if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType))));
if (!isDictionary)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName)));
valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName);
}
}
XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3);
this.Name = dictionary.Add(this.StableName.Name);
this.Namespace = dictionary.Add(this.StableName.Namespace);
_itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name;
_collectionItemName = dictionary.Add(_itemName);
if (isDictionary)
{
_keyName = keyName ?? Globals.KeyLocalName;
_valueName = valueName ?? Globals.ValueLocalName;
}
}
if (collectionContractAttribute != null)
{
this.IsReference = collectionContractAttribute.IsReference;
}
}
internal CollectionDataContractCriticalHelper(CollectionKind kind)
: base()
{
Init(kind, null, null);
}
// array
internal CollectionDataContractCriticalHelper(Type type) : base(type)
{
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent)));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type)
{
if (getEnumeratorMethod == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type))));
if (addMethod == null && !type.GetTypeInfo().IsInterface)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type))));
if (itemType == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type))));
CollectionDataContractAttribute collectionContractAttribute;
this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute);
Init(kind, itemType, collectionContractAttribute);
_getEnumeratorMethod = getEnumeratorMethod;
_addMethod = addMethod;
_constructor = constructor;
}
// collection
internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired)
: this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)
{
_isConstructorCheckRequired = isConstructorCheckRequired;
}
internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type)
{
Init(CollectionKind.Collection, null /*itemType*/, null);
_invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage;
}
internal CollectionKind Kind
{
get { return _kind; }
}
internal Type ItemType
{
get { return _itemType; }
set { _itemType = value; }
}
internal DataContract ItemContract
{
get
{
if (_itemContract == null && UnderlyingType != null)
{
if (IsDictionary)
{
if (String.CompareOrdinal(KeyName, ValueName) == 0)
{
DataContract.ThrowInvalidDataContractException(
SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName),
UnderlyingType);
}
_itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName });
// Ensure that DataContract gets added to the static DataContract cache for dictionary items
DataContract.GetDataContract(ItemType);
}
else
{
#if NET_NATIVE
_itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType);
#else
_itemContract = DataContract.GetDataContract(ItemType);
#endif
}
}
return _itemContract;
}
set
{
_itemContract = value;
}
}
internal DataContract SharedTypeContract
{
get { return _sharedTypeContract; }
set { _sharedTypeContract = value; }
}
internal string ItemName
{
get { return _itemName; }
set { _itemName = value; }
}
internal bool IsConstructorCheckRequired
{
get { return _isConstructorCheckRequired; }
set { _isConstructorCheckRequired = value; }
}
public XmlDictionaryString CollectionItemName
{
get { return _collectionItemName; }
}
internal string KeyName
{
get { return _keyName; }
set { _keyName = value; }
}
internal string ValueName
{
get { return _valueName; }
set { _valueName = value; }
}
internal bool IsDictionary
{
get { return KeyName != null; }
}
public XmlDictionaryString ChildElementNamespace
{
get { return _childElementNamespace; }
set { _childElementNamespace = value; }
}
internal MethodInfo GetEnumeratorMethod
{
get { return _getEnumeratorMethod; }
}
internal MethodInfo AddMethod
{
get { return _addMethod; }
}
internal ConstructorInfo Constructor
{
get { return _constructor; }
}
internal override DataContractDictionary KnownDataContracts
{
[SecurityCritical]
get
{
if (!_isKnownTypeAttributeChecked && UnderlyingType != null)
{
lock (this)
{
if (!_isKnownTypeAttributeChecked)
{
_knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType);
Interlocked.MemoryBarrier();
_isKnownTypeAttributeChecked = true;
}
}
}
return _knownDataContracts;
}
[SecurityCritical]
set
{ _knownDataContracts = value; }
}
internal string InvalidCollectionInSharedContractMessage
{
get { return _invalidCollectionInSharedContractMessage; }
}
internal bool ItemNameSetExplicit
{
get { return _itemNameSetExplicit; }
}
internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate
{
get { return _xmlFormatWriterDelegate; }
set { _xmlFormatWriterDelegate = value; }
}
internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate
{
get { return _xmlFormatReaderDelegate; }
set { _xmlFormatReaderDelegate = value; }
}
internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate
{
get { return _xmlFormatGetOnlyCollectionReaderDelegate; }
set { _xmlFormatGetOnlyCollectionReaderDelegate = value; }
}
}
private DataContract GetSharedTypeContract(Type type)
{
if (type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false))
{
return this;
}
if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return new ClassDataContract(type);
}
return null;
}
internal static bool IsCollectionInterface(Type type)
{
if (type.GetTypeInfo().IsGenericType)
type = type.GetGenericTypeDefinition();
return ((IList<Type>)KnownInterfaces).Contains(type);
}
internal static bool IsCollection(Type type)
{
Type itemType;
return IsCollection(type, out itemType);
}
internal static bool IsCollection(Type type, out Type itemType)
{
return IsCollectionHelper(type, out itemType, true /*constructorRequired*/);
}
internal static bool IsCollection(Type type, bool constructorRequired)
{
Type itemType;
return IsCollectionHelper(type, out itemType, constructorRequired);
}
private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired)
{
if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null)
{
itemType = type.GetElementType();
return true;
}
DataContract dataContract;
return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired);
}
internal static bool TryCreate(Type type, out DataContract dataContract)
{
Type itemType;
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/);
}
internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
}
internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract)
{
#if !NET_NATIVE
Type itemType;
if (type.IsArray)
{
dataContract = new CollectionDataContract(type);
return true;
}
else
{
return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/);
}
#else
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
if (dataContract is CollectionDataContract)
{
return true;
}
else
{
dataContract = null;
return false;
}
#endif
}
internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
if (t == null)
return null;
return t.GetMethod(name);
}
private static bool IsArraySegment(Type t)
{
return t.GetTypeInfo().IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>));
}
private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired)
{
dataContract = null;
itemType = Globals.TypeOfObject;
if (DataContract.GetBuiltInDataContract(type) != null)
{
return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/,
SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract);
}
MethodInfo addMethod, getEnumeratorMethod;
bool hasCollectionDataContract = IsCollectionDataContract(type);
Type baseType = type.GetTypeInfo().BaseType;
bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject
&& baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false;
if (type.GetTypeInfo().IsDefined(Globals.TypeOfDataContractAttribute, false))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeCannotHaveDataContract, null, ref dataContract);
}
if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type))
{
return false;
}
if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type))
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (type.GetTypeInfo().IsInterface)
{
Type interfaceTypeToCheck = type.GetTypeInfo().IsGenericType ? type.GetGenericTypeDefinition() : type;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
addMethod = null;
if (type.GetTypeInfo().IsGenericType)
{
Type[] genericArgs = type.GetGenericArguments();
if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric)
{
itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs);
addMethod = type.GetMethod(Globals.AddMethodName);
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName);
}
else
{
itemType = genericArgs[0];
// ICollection<T> has AddMethod
var collectionType = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType);
if (collectionType.IsAssignableFrom(type))
{
addMethod = collectionType.GetMethod(Globals.AddMethodName);
}
getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName);
}
}
else
{
if (interfaceTypeToCheck == Globals.TypeOfIDictionary)
{
itemType = typeof(KeyValue<object, object>);
addMethod = type.GetMethod(Globals.AddMethodName);
}
else
{
itemType = Globals.TypeOfObject;
// IList has AddMethod
if (interfaceTypeToCheck == Globals.TypeOfIList)
{
addMethod = type.GetMethod(Globals.AddMethodName);
}
}
getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/);
return true;
}
}
}
ConstructorInfo defaultCtor = null;
if (!type.GetTypeInfo().IsValueType)
{
defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>());
if (defaultCtor == null && constructorRequired)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract);
}
}
Type knownInterfaceType = null;
CollectionKind kind = CollectionKind.None;
bool multipleDefinitions = false;
Type[] interfaceTypes = type.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
Type interfaceTypeToCheck = interfaceType.GetTypeInfo().IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType;
Type[] knownInterfaces = KnownInterfaces;
for (int i = 0; i < knownInterfaces.Length; i++)
{
if (knownInterfaces[i] == interfaceTypeToCheck)
{
CollectionKind currentKind = (CollectionKind)(i + 1);
if (kind == CollectionKind.None || currentKind < kind)
{
kind = currentKind;
knownInterfaceType = interfaceType;
multipleDefinitions = false;
}
else if ((kind & currentKind) == currentKind)
multipleDefinitions = true;
break;
}
}
}
if (kind == CollectionKind.None)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection,
SR.CollectionTypeIsNotIEnumerable, null, ref dataContract);
}
if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable)
{
if (multipleDefinitions)
knownInterfaceType = Globals.TypeOfIEnumerable;
itemType = knownInterfaceType.GetTypeInfo().IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject;
GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType },
false /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
if (addMethod == null)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract);
}
if (tryCreate)
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
}
else
{
if (multipleDefinitions)
{
return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/,
SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract);
}
Type[] addMethodTypeArray = null;
switch (kind)
{
case CollectionKind.GenericDictionary:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
bool isOpenGeneric = knownInterfaceType.GetTypeInfo().IsGenericTypeDefinition
|| (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter);
itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.Dictionary:
addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray);
break;
case CollectionKind.GenericList:
case CollectionKind.GenericCollection:
addMethodTypeArray = knownInterfaceType.GetGenericArguments();
itemType = addMethodTypeArray[0];
break;
case CollectionKind.List:
itemType = Globals.TypeOfObject;
addMethodTypeArray = new Type[] { itemType };
break;
}
if (tryCreate)
{
GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray,
true /*addMethodOnInterface*/,
out getEnumeratorMethod, out addMethod);
#if !NET_NATIVE
dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired);
#else
dataContract = DataContract.GetDataContractFromGeneratedAssembly(type);
#endif
}
}
return true;
}
internal static bool IsCollectionDataContract(Type type)
{
return type.GetTypeInfo().IsDefined(Globals.TypeOfCollectionDataContractAttribute, false);
}
private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract)
{
if (hasCollectionDataContract)
{
if (tryCreate)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param)));
return true;
}
if (createContractWithException)
{
if (tryCreate)
dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param));
return true;
}
return false;
}
private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param)
{
return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param);
}
private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod)
{
Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault();
if (t != null)
{
addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod;
getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod;
}
}
private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod)
{
addMethod = getEnumeratorMethod = null;
if (addMethodOnInterface)
{
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray);
if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0])
{
FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
Type[] parentInterfaceTypes = interfaceType.GetInterfaces();
foreach (Type parentInterfaceType in parentInterfaceTypes)
{
if (IsKnownInterface(parentInterfaceType))
{
FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod);
if (addMethod == null)
{
break;
}
}
}
}
}
}
else
{
// GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain
addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray);
if (addMethod == null)
return;
}
if (getEnumeratorMethod == null)
{
getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType))
{
Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault();
if (ienumerableInterface == null)
ienumerableInterface = Globals.TypeOfIEnumerable;
getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface);
}
}
}
private static bool IsKnownInterface(Type type)
{
Type typeToCheck = type.GetTypeInfo().IsGenericType ? type.GetGenericTypeDefinition() : type;
foreach (Type knownInterfaceType in KnownInterfaces)
{
if (typeToCheck == knownInterfaceType)
{
return true;
}
}
return false;
}
internal override DataContract GetValidContract(SerializationMode mode)
{
if (InvalidCollectionInSharedContractMessage != null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage));
return this;
}
internal override DataContract GetValidContract()
{
if (this.IsConstructorCheckRequired)
{
CheckConstructor();
}
return this;
}
/// <SecurityNote>
/// Critical - sets the critical IsConstructorCheckRequired property on CollectionDataContract
/// </SecurityNote>
[SecuritySafeCritical]
private void CheckConstructor()
{
if (this.Constructor == null)
{
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType))));
}
else
{
this.IsConstructorCheckRequired = false;
}
}
internal override bool IsValidContract(SerializationMode mode)
{
return (InvalidCollectionInSharedContractMessage == null);
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for deserialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForRead(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
if (ConstructorRequiresMemberAccess(Constructor))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractNoPublicConstructor,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (MethodRequiresMemberAccess(this.AddMethod))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractAddMethodNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType),
this.AddMethod.Name),
securityException));
}
return true;
}
return false;
}
/// <SecurityNote>
/// Review - calculates whether this collection requires MemberAccessPermission for serialization.
/// since this information is used to determine whether to give the generated code access
/// permissions to private members, any changes to the logic should be reviewed.
/// </SecurityNote>
internal bool RequiresMemberAccessForWrite(SecurityException securityException)
{
if (!IsTypeVisible(UnderlyingType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(UnderlyingType)),
securityException));
}
return true;
}
if (ItemType != null && !IsTypeVisible(ItemType))
{
if (securityException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new SecurityException(SR.Format(
SR.PartialTrustCollectionContractTypeNotPublic,
DataContract.GetClrTypeFullName(ItemType)),
securityException));
}
return true;
}
return false;
}
public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
XmlFormatWriterDelegate(xmlWriter, obj, context, this);
}
public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context)
{
xmlReader.Read();
object o = null;
if (context.IsGetOnlyCollection)
{
// IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset.
context.IsGetOnlyCollection = false;
#if NET_NATIVE
if (XmlFormatGetOnlyCollectionReaderDelegate == null)
{
throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString()));
}
#endif
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
else
{
o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
}
xmlReader.ReadEndElement();
return o;
}
internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>>
{
private IDictionaryEnumerator _enumerator;
public DictionaryEnumerator(IDictionaryEnumerator enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<object, object> Current
{
get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); }
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>>
{
private IEnumerator<KeyValuePair<K, V>> _enumerator;
public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator)
{
_enumerator = enumerator;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public KeyValue<K, V> Current
{
get
{
KeyValuePair<K, V> current = _enumerator.Current;
return new KeyValue<K, V>(current.Key, current.Value);
}
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public void Reset()
{
_enumerator.Reset();
}
}
}
}
| |
//
// Copyright (c) 2009-2010 Krueger Systems, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using MonoTouch.UIKit;
using System.Collections.Generic;
namespace OData.Touch
{
public class DataViewController : DialogViewController
{
public UserFeed Feed { get; private set; }
public UserQuery Query { get; private set; }
public string Url { get; private set; }
public int NumEntitiesPerRequest { get; set; }
public bool PagingEnabled { get; set; }
int _numGets = 0;
DialogSection _moreSection;
DialogSection _loadSection;
LoadingElement _loadElement;
int _index;
public DataViewController (UserQuery query, string url) : base(UITableViewStyle.Grouped)
{
try {
Query = query;
Url = url;
Title = Query.Name;
PagingEnabled = true;
NumEntitiesPerRequest = 20;
_index = 0;
_loadSection = new DialogSection ();
_loadElement = new LoadingElement ();
_loadSection.Add (_loadElement);
_loadElement.Start ();
Sections.Add (_loadSection);
_moreSection = new DialogSection ();
_moreSection.Add (new ActionElement ("More", GetMore));
if (PagingEnabled) {
Sections.Add (_moreSection);
}
using (var repo = new Repo ()) {
Feed = repo.GetFeed (query.FeedId);
}
if (Query.Id > 0) {
NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Edit, HandleEdit);
}
GetMore ();
} catch (Exception error) {
Log.Error (error);
}
}
void HandleEdit (object sender, EventArgs e)
{
try {
UserService service = null;
using (var repo = new Repo()) {
service = repo.GetService(Query.ServiceId);
}
var editC = new QueryController (service, Query);
var navC = new UINavigationController (editC);
editC.Done += delegate {
editC.DismissModalViewControllerAnimated (true);
Query.Filter = editC.Filter;
Query.FeedId = editC.Feed.Id;
Query.Name = editC.Name;
Query.OrderBy = editC.OrderBy;
using (var repo = new Repo ()) {
repo.Save (Query);
}
_numGets = 0;
_index = 0;
Sections.Clear ();
_loadSection = new DialogSection ();
_loadSection.Add (_loadElement);
_loadElement.Start ();
Sections.Add (_loadSection);
GetMore ();
};
NavigationController.PresentModalViewController (navC, true);
} catch (Exception error) {
Log.Error (error);
}
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
return true;
}
void AddToQuery (Dictionary<string, object> q)
{
if (!string.IsNullOrEmpty (Query.Filter)) {
q["$filter"] = Query.Filter;
}
if (!string.IsNullOrEmpty (Query.OrderBy)) {
q["$orderby"] = Query.OrderBy;
}
}
NetErrorAlert _netError = new NetErrorAlert ();
void GetMore ()
{
if (!PagingEnabled && _numGets > 0) {
return;
}
if (PagingEnabled) {
Sections.Remove (_moreSection);
TableView.ReloadData ();
}
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true;
App.RunInBackground (delegate {
var atom = "";
try {
var q = new Dictionary<string, object> ();
AddToQuery (q);
if (PagingEnabled) {
q["$skip"] = _index;
q["$top"] = NumEntitiesPerRequest;
}
try {
atom = Http.Get (Url + "?" + Http.MakeQueryString (q));
} catch (System.Net.WebException nex) {
var hr = nex.Response as System.Net.HttpWebResponse;
if (hr.StatusDescription.ToLowerInvariant ().IndexOf ("not implemented") >= 0 && PagingEnabled) {
//
// Try without paging
//
q.Remove ("$skip");
q.Remove ("$top");
atom = Http.Get (Url + "?" + Http.MakeQueryString (q));
PagingEnabled = false;
}
}
_numGets++;
if (PagingEnabled) {
_index += NumEntitiesPerRequest;
}
} catch (Exception netError) {
Console.WriteLine (netError);
App.RunInForeground (delegate { _netError.ShowError (netError); });
return;
}
var ents = EntitySet.LoadFromAtom (atom);
App.RunInForeground (delegate {
UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false;
if (_loadSection != null) {
_loadElement.Stop ();
Sections.Remove (_loadSection);
}
foreach (var e in ents) {
var sec = new DialogSection (e.Title, e.Author);
foreach (var prop in e.Properties) {
sec.Add (new PropertyElement (e, prop));
}
foreach (var link in e.Links) {
if (link.Rel == "edit")
continue;
sec.Add (new LinkElement (Feed, link));
}
Sections.Add (sec);
}
if (PagingEnabled && ents.Count >= NumEntitiesPerRequest) {
Sections.Add (_moreSection);
}
TableView.ReloadData ();
});
});
}
class PropertyElement : StaticElement
{
public Entity Entity { get; private set; }
public EntityProperty Property { get; private set; }
public PropertyElement (Entity e, EntityProperty prop) : base(prop.Name)
{
Entity = e;
CellStyle = UITableViewCellStyle.Value2;
Property = prop;
}
protected override float GetHeight (float width)
{
return 22.0f;
}
bool LongText {
get { return !Property.IsDateTime && Property.ValueText.Length > 24; }
}
public override void RefreshCell (UITableViewCell cell)
{
base.RefreshCell (cell);
var more = (LongText || Property.LooksLikeHtml || Property.LooksLikeLink || (Entity.HasLocation && Entity.IsLocationProperty (Property)));
cell.Accessory = more ? UITableViewCellAccessory.DisclosureIndicator : UITableViewCellAccessory.None;
cell.SelectionStyle = more ? UITableViewCellSelectionStyle.Blue : UITableViewCellSelectionStyle.None;
cell.DetailTextLabel.Text = Property.DisplayText;
}
public override void OnSelected (DialogViewController sender, MonoTouch.Foundation.NSIndexPath indexPath)
{
if (Property.LooksLikeLink) {
var c = new BrowserController (Property.ValueText);
sender.NavigationController.PushViewController (c, true);
} else if (Property.LooksLikeHtml) {
var c = new BrowserController (Property.Name, Property.ValueText);
sender.NavigationController.PushViewController (c, true);
} else if (Entity.IsLocationProperty (Property)) {
var c = new MapController (Entity);
sender.NavigationController.PushViewController (c, true);
} else if (LongText) {
var html = Html.Encode (Property.ValueText);
var c = new BrowserController (Property.Name, html);
sender.NavigationController.PushViewController (c, true);
}
base.OnSelected (sender, indexPath);
}
}
class LinkElement : StaticElement
{
public UserFeed Feed { get; private set; }
public Entity.Link Link { get; private set; }
public LinkElement (UserFeed feed, Entity.Link link) : base(link.Name)
{
Feed = feed;
Link = link;
}
protected override float GetHeight (float width)
{
return 33.0f;
}
public override void RefreshCell (UITableViewCell cell)
{
base.RefreshCell (cell);
cell.Accessory = Link.IsSingleEntity ? UITableViewCellAccessory.DetailDisclosureButton : UITableViewCellAccessory.DisclosureIndicator;
}
public override void OnSelected (DialogViewController sender, MonoTouch.Foundation.NSIndexPath indexPath)
{
var newData = new DataViewController (new UserQuery {
FeedId = Feed.Id,
Name = Link.Href,
ServiceId = Feed.ServiceId
}, Feed.GetUrl (Link.Href));
newData.PagingEnabled = !Link.IsSingleEntity;
sender.NavigationController.PushViewController (newData, true);
}
}
}
}
| |
//
// NtlmUtils.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2022 .NET Foundation and Contributors
//
// 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.
//
// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nlmp/b38c36ed-2804-4868-a9ff-8dd3182128e4
using System;
using System.Text;
using System.Security.Cryptography;
using SSCMD5 = System.Security.Cryptography.MD5;
namespace MailKit.Security.Ntlm {
static class NtlmUtils
{
//static readonly byte[] ClientSealMagic = Encoding.ASCII.GetBytes ("session key to client-to-server sealing key magic constant");
//static readonly byte[] ServerSealMagic = Encoding.ASCII.GetBytes ("session key to server-to-client sealing key magic constant");
//static readonly byte[] ClientSignMagic = Encoding.ASCII.GetBytes ("session key to client-to-server signing key magic constant");
//static readonly byte[] ServerSignMagic = Encoding.ASCII.GetBytes ("session key to server-to-client signing key magic constant");
//static readonly byte[] SealKeySuffix40 = new byte[] { 0xe5, 0x38, 0xb0 };
//static readonly byte[] SealKeySuffix56 = new byte[] { 0xa0 };
static readonly byte[] Responserversion = new byte[] { 1 };
static readonly byte[] HiResponserversion = new byte[] { 1 };
static readonly byte[] Z24 = new byte[24];
static readonly byte[] Z6 = new byte[6];
static readonly byte[] Z4 = new byte[4];
static readonly byte[] Z1 = new byte[1];
public static byte[] ConcatenationOf (params string[] values)
{
var concatenatedValue = string.Concat (values);
return Encoding.Unicode.GetBytes (concatenatedValue);
}
public static byte[] ConcatenationOf (params byte[][] values)
{
int index = 0, length = 0;
for (int i = 0; i < values.Length; i++)
length += values[i].Length;
var concatenated = new byte[length];
for (int i = 0; i < values.Length; i++) {
length = values[i].Length;
Buffer.BlockCopy (values[i], 0, concatenated, index, length);
index += length;
}
return concatenated;
}
static byte[] MD4 (byte[] buffer)
{
using (var md4 = new MD4 ()) {
var hash = md4.ComputeHash (buffer);
Array.Clear (buffer, 0, buffer.Length);
return hash;
}
}
static byte[] MD4 (string password)
{
return MD4 (Encoding.Unicode.GetBytes (password));
}
public static byte[] MD5 (byte[] buffer)
{
using (var md5 = SSCMD5.Create ()) {
var hash = md5.ComputeHash (buffer);
Array.Clear (buffer, 0, buffer.Length);
return hash;
}
}
public static byte[] HMACMD5 (byte[] key, params byte[][] values)
{
using (var md5 = new HMACMD5 (key)) {
int i;
for (i = 0; i < values.Length - 1; i++)
md5.TransformBlock (values[i], 0, values[i].Length, null, 0);
md5.TransformFinalBlock (values[i], 0, values[i].Length);
return md5.Hash;
}
}
public static byte[] NONCE (int size)
{
var nonce = new byte[size];
using (var rng = RandomNumberGenerator.Create ())
rng.GetBytes (nonce);
return nonce;
}
public static byte[] RC4K (byte[] key, byte[] message)
{
try {
using (var rc4 = new RC4 ()) {
rc4.Key = key;
return rc4.TransformFinalBlock (message, 0, message.Length);
}
} finally {
Array.Clear (key, 0, key.Length);
}
}
#if false
public static byte[] SEALKEY (NtlmFlags flags, byte[] exportedSessionKey, bool client = true)
{
if ((flags & NtlmFlags.NegotiateExtendedSessionSecurity) != 0) {
byte[] subkey;
if ((flags & NtlmFlags.Negotiate128) != 0) {
subkey = exportedSessionKey;
} else if ((flags & NtlmFlags.Negotiate56) != 0) {
subkey = new byte[7];
Buffer.BlockCopy (exportedSessionKey, 0, subkey, 0, subkey.Length);
} else {
subkey = new byte[5];
Buffer.BlockCopy (exportedSessionKey, 0, subkey, 0, subkey.Length);
}
var magic = client ? ClientSealMagic : ServerSealMagic;
var sealKey = MD5 (ConcatenationOf (subkey, magic));
if (subkey != exportedSessionKey)
Array.Clear (subkey, 0, subkey.Length);
return sealKey;
} else if ((flags & NtlmFlags.NegotiateLanManagerKey) != 0) {
byte[] suffix;
int length;
if ((flags & NtlmFlags.Negotiate56) != 0) {
suffix = SealKeySuffix56;
length = 7;
} else {
suffix = SealKeySuffix40;
length = 5;
}
var sealKey = new byte[length + suffix.Length];
Buffer.BlockCopy (exportedSessionKey, 0, sealKey, 0, length);
Buffer.BlockCopy (suffix, 0, sealKey, length, suffix.Length);
return sealKey;
} else {
return exportedSessionKey;
}
}
#endif
#if false
public static byte[] SIGNKEY (NtlmFlags flags, byte[] exportedSessionKey, bool client = true)
{
if ((flags & NtlmFlags.NegotiateExtendedSessionSecurity) != 0) {
var magic = client ? ClientSignMagic : ServerSignMagic;
return MD5 (ConcatenationOf (exportedSessionKey, magic));
} else {
return null;
}
}
#endif
static byte[] NTOWFv2 (string domain, string userName, string password)
{
var hash = MD4 (password);
byte[] responseKey;
using (var md5 = new HMACMD5 (hash)) {
var userDom = ConcatenationOf (userName.ToUpperInvariant (), domain);
responseKey = md5.ComputeHash (userDom);
}
Array.Clear (hash, 0, hash.Length);
return responseKey;
}
public static void ComputeNtlmV2 (NtlmChallengeMessage type2, string domain, string userName, string password, byte[] targetInfo, byte[] clientChallenge, long? time, out byte[] ntChallengeResponse, out byte[] lmChallengeResponse, out byte[] sessionBaseKey)
{
if (userName.Length == 0 && password.Length == 0) {
// Special case for anonymous authentication
ntChallengeResponse = null;
lmChallengeResponse = Z1;
sessionBaseKey = null;
return;
}
var timestamp = (time ?? DateTime.UtcNow.Ticks) - 504911232000000000;
var responseKey = NTOWFv2 (domain, userName, password);
// Note: If NTLM v2 authentication is used, the client SHOULD send the timestamp in the CHALLENGE_MESSAGE.
if (type2.TargetInfo?.Timestamp != null)
timestamp = type2.TargetInfo.Timestamp.Value;
var temp = ConcatenationOf (Responserversion, HiResponserversion, Z6, BitConverterLE.GetBytes (timestamp), clientChallenge, Z4, targetInfo, Z4);
var proof = HMACMD5 (responseKey, type2.ServerChallenge, temp);
sessionBaseKey = HMACMD5 (responseKey, proof);
ntChallengeResponse = ConcatenationOf (proof, temp);
Array.Clear (proof, 0, proof.Length);
Array.Clear (temp, 0, temp.Length);
var hash = HMACMD5 (responseKey, type2.ServerChallenge, clientChallenge);
Array.Clear (responseKey, 0, responseKey.Length);
// Note: If NTLM v2 authentication is used and the CHALLENGE_MESSAGE TargetInfo field (section 2.2.1.2) has an
// MsvAvTimestamp present, the client SHOULD NOT send the LmChallengeResponse and SHOULD send Z(24) instead.
if (type2.TargetInfo?.Timestamp == null)
lmChallengeResponse = ConcatenationOf (hash, clientChallenge);
else
lmChallengeResponse = Z24;
Array.Clear (hash, 0, hash.Length);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function LeapToy::createBuilderLevel( %this )
{
// Create background.
%this.createBackground();
// Create the ground.
%this.createGround();
// Create the pyramid.
%this.createPyramid();
// Create circle gesture visual.
%this.createCircleSprite();
// Create circle gesture visual.
%this.createBuilderFingers();
// Set the gravity.
SandboxScene.setGravity( 0, -9.8 );
// Set the manipulation mode.
Sandbox.useManipulation( off );
// Create the help text scene
%helpText = new SimSet();
%helpText.add(new ScriptObject() { Text = "Press TAB to toggle between Cursor and Finger control."; });
%helpText.add(new ScriptObject() { Text = " "; });
%helpText.add(new ScriptObject() { Text = "Finger Control: "; });
%helpText.add(new ScriptObject() { Text = " Reach in to enable finger collision."; });
%helpText.add(new ScriptObject() { Text = " Fingers will turn yellow when collision is enabled."; });
%helpText.add(new ScriptObject() { Text = " "; });
%helpText.add(new ScriptObject() { Text = "Cursor Control: "; });
%helpText.add(new ScriptObject() { Text = " Key tap creates a new block."; });
%helpText.add(new ScriptObject() { Text = " Circle Gesture selects blocks within the circle."; });
%helpText.add(new ScriptObject() { Text = " Screen Tap deletes the selected blocks."; });
%helpText.add(new ScriptObject() { Text = " "; });
%helpText.add(new ScriptObject() { Text = "Press H to return to the demo."; });
%this.createHelpTextScene(%helpText);
%helpText.delete();
%this.CenterZ = 125;
// Swap action maps
FingerMap.pop();
BreakoutMap.pop();
GestureMap.pop();
// Enable builder map
BuilderMap.push();
}
function LeapToy::createBuilderBlock(%this, %position)
{
// Set the block size.
%blockSize = LeapToy.BlockSize;
%blockFrames = "0 2 4 6";
%randomNumber = getRandom(0, 4);
// Create the sprite.
%obj = new Sprite()
{
class = "Block";
flipped = false;
};
%obj.setSceneLayer(3);
%obj.setPosition( %position.x, %position.y );
%obj.setSize( %blockSize );
%obj.setImage( "LeapToy:objectsBlocks" );
%obj.setImageFrame( getWord(%blockFrames, %randomNumber) );
%obj.setDefaultFriction( 1.0 );
%obj.createPolygonBoxCollisionShape( %blockSize, %blockSize );
// Add to the scene.
SandboxScene.add( %obj );
}
//-----------------------------------------------------------------------------
// Called when the user makes a circle with their finger(s)
//
// %id - Finger ID, based on the order the finger was added to the tracking
// %progress - How much of the circle has been completed
// %radius - Radius of the circle created by the user's motion
// %isClockwise - Toggle based on the direction the user made the circle
// %state - State of the gesture progress: 1: Started, 2: Updated, 3: Stopped
function LeapToy::reactToCircleBuilder(%this, %id, %progress, %radius, %isClockwise, %state)
{
if (!%this.enableCircleGesture)
return;
if (isLeapCursorControlled())
{
if (%progress > 0 && %state == 3)
{
%this.grabObjectsInCircle();
%this.schedule(300, "hideCircleSprite");
}
else if (%progress > 0 && %state != 3)
{
%this.showCircleSprite(%radius/5, %isClockwise);
}
}
}
//-----------------------------------------------------------------------------
// Called when the user makes a swipe with their finger(s)
//
// %id - Finger ID, based on the order the finger was added to the tracking
// %state - State of the gesture progress: 1: Started, 2: Updated, 3: Stopped
// %direction - 3 point vector based on the direction the finger swiped
// %speed - How fast the user's finger moved. Values will be quite large
function LeapToy::reactToSwipeBuilder(%this, %id, %state, %direction, %speed)
{
if (!%this.enableSwipeGesture)
return;
}
//-----------------------------------------------------------------------------
// Called when the user makes a screen tap gesture with their finger(s)
//
// %id - Finger ID, based on the order the finger was added to the tracking
// %position - 3 point vector based on where the finger was located in "Leap Space"
// %direction - 3 point vector based on the direction the finger motion
function LeapToy::reactToScreenTapBuilder(%this, %id, %position, %direction)
{
if (!%this.enableScreenTapGesture)
return;
%this.deleteSelectedObjects();
}
//-----------------------------------------------------------------------------
// Called when the user makes a key tap gesture with their finger(s)
//
// %id - Finger ID, based on the order the finger was added to the tracking
// %position - 3 point vector based on where the finger was located in "Leap Space"
// %direction - 3 point vector based on the direction the finger tap
function LeapToy::reactToKeyTapBuilder(%this, %id, %position, %direction)
{
if (!%this.enableKeyTapGesture)
return;
if (isLeapCursorControlled())
{
%worldPosition = SandboxWindow.getWorldPoint(Canvas.getCursorPos());
%this.createBuilderBlock(%worldPosition);
}
}
//-----------------------------------------------------------------------------
// Constantly polling callback based on the finger position on a hand
// %id - Ordered hand ID based on when it was added to the tracking device
// %position - 3 point vector based on where the finger is located in "Leap Space"
function LeapToy::trackFingerPosBuilder(%this, %ids, %fingersX, %fingersY, %fingersZ)
{
if (!%this.enableFingerTracking)
return;
for(%i = 0; %i < getWordCount(%ids); %i++)
{
%id = getWord(%ids, %i);
// The next two lines of code use projection. To use intersection
// comment out both lines, then uncomment the getPointFromIntersection call.
%position = getWord(%fingersX, %i) SPC getWord(%fingersY, %i) SPC getWord(%fingersZ, %i);
%screenPosition = getPointFromProjection(%position);
// This uses intersection
//%screenPosition = getPointFromIntersection(%id);
%worldPosition = SandboxWindow.getWorldPoint(%screenPosition);
%this.showFingerBuilder(%id, %worldPosition, %position.z);
}
}
//-----------------------------------------------------------------------------
function LeapToy::showFingerBuilder(%this, %id, %worldPosition, %zpos)
{
echo("Finger " SPC %id SPC ":" SPC %worldPosition);
%finger = %this.fingers[%id];
if (!isObject(%finger))
return;
if (!%finger.visible)
{
%finger.visible = true;
%finger.setPosition(%worldPosition);
%this.movePosition[%id] = %worldPosition;
}
else
{
%distance = VectorSub(%finger.getPosition(), %worldPosition);
%finger.moveTo(%worldPosition, VectorLen(%distance) * 10, true, false);
%this.movePosition[%id] = %worldPosition;
}
%size = 2;
if( %zpos > LeapToy.CenterZ )
{
%finger.setCollisionSuppress(true);
// set the size to be bigger to give the illusion it is in front of the play area
%size = (%zpos/LeapToy.CenterZ) * 2;
%finger.setBlendColor(1.0, 1.0, 1.0, 0.5);
}
else
{
%finger.setCollisionSuppress(false);
%finger.setBlendColor("Yellow");
}
%finger.setSize(%size, %size);
%this.schedule(200, "checkFingerBuilder", %id, %worldPosition);
}
//-----------------------------------------------------------------------------
function LeapToy::checkFingerBuilder(%this, %id, %worldPosition)
{
%finger = %this.fingers[%id];
// Likely no activity, since the device is sensitive
if (%this.movePosition[%id] $= %worldPosition)
{
%finger.visible = false;
%finger.setCollisionSuppress(true);
}
}
//-----------------------------------------------------------------------------
function LeapToy::createBuilderFingers(%this)
{
for (%i = 0; %i < 10; %i++)
{
%name = "Finger" @ %i;
// Create the circle.
%finger = new Sprite();
%finger.setName(%name);
%finger.Position = "-10 5";
%finger.Size = 2;
%finger.Image = "LeapToy:circleThree";
%finger.Visible = false;
%finger.createCircleCollisionShape(1.0, "0 0");
%finger.FixedAngle = true;
%finger.setDefaultFriction(1.0, true);
%finger.CollisionSuppress = true;
%finger.setSceneLayer(0);
%finger.setCollisionLayers("1 2 3 4 5");
%this.fingers[%i] = %finger;
// Add to the scene.
SandboxScene.add( %finger );
}
}
| |
using System;
/*
* $Id: InfCodes.cs,v 1.2 2008-05-10 09:35:40 bouncy Exp $
*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
namespace Org.BouncyCastle.Utilities.Zlib
{
public enum InflateCodeMode
{
/// <summary>
/// x: set up for InflateCodeMode.LEN
/// </summary>
START = 0,
/// <summary>
/// i: get length/literal/eob next
/// </summary>
LEN = 1,
/// <summary>
/// i: getting length extra (have base)
/// </summary>
LENEXT = 2,
/// <summary>
/// i: get distance next
/// </summary>
DIST = 3,
/// <summary>
/// : getting distance extra
/// </summary>
DISTEXT = 4,
/// <summary>
/// o: copying bytes in window, waiting for space
/// </summary>
COPY = 5,
/// <summary>
/// o: got literal, waiting for output space
/// </summary>
LIT = 6,
/// <summary>
/// o: got eob, possibly still output waiting
/// </summary>
WASH = 7,
/// <summary>
/// x: got eob and all data flushed
/// </summary>
END = 8,
/// <summary>
/// x: got error
/// </summary>
BADCODE = 9
}
internal abstract class InflateCodes// : ZStream
{
private static readonly int[] inflate_mask = {
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f,
0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff,
0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff,
0x00007fff, 0x0000ffff
};
InflateCodeMode mode; // current inflate_codes mode
// mode dependent information
int len;
int[] tree; // pointer into tree
int tree_index = 0;
int need; // bits needed
int lit;
// if EXT or COPY, where and how much
int get; // bits to get for extra
int dist; // distance back to copy from
byte lbits; // ltree bits decoded per branch
byte dbits; // dtree bits decoder per branch
int[] ltree; // literal/length/eob tree
int ltree_index; // literal/length/eob tree
int[] dtree; // distance tree
int dtree_index; // distance tree
internal InflateCodes()
{
}
internal void codesinit(int bl, int bd,
int[] tl, int tl_index,
int[] td, int td_index)
{
mode = InflateCodeMode.START;
lbits = (byte)bl;
dbits = (byte)bd;
ltree = tl;
ltree_index = tl_index;
dtree = td;
dtree_index = td_index;
tree = null;
}
internal ZLibStatus codesproc(InflateBlocks s, ICompressor z, ZLibStatus r)
{
int j; // temporary storage
int tindex; // temporary pointer
int e; // extra bits or operation
int b = 0; // bit buffer
int k = 0; // bits in bit buffer
int p = 0; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int f; // pointer to copy strings from
// copy input/output information to locals (UPDATE macro restores)
p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk;
q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q;
// process input and output based on current state
while (true)
{
switch (mode)
{
// waiting for "i:"=input, "o:"=output, "x:"=nothing
case InflateCodeMode.START: // x: set up for LEN
if (m >= 258 && n >= 10)
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
r = inflate_fast(lbits, dbits,
ltree, ltree_index,
dtree, dtree_index,
s, z);
p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk;
q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q;
if (r != ZLibStatus.Z_OK)
{
mode = r == ZLibStatus.Z_STREAM_END ? InflateCodeMode.WASH : InflateCodeMode.BADCODE;
break;
}
}
need = lbits;
tree = ltree;
tree_index = ltree_index;
mode = InflateCodeMode.LEN;
goto case InflateCodeMode.LEN;
case InflateCodeMode.LEN: // i: get length/literal/eob next
j = need;
while (k < (j))
{
if (n != 0) r = ZLibStatus.Z_OK;
else
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
tindex = (tree_index + (b & inflate_mask[j])) * 3;
b >>= (tree[tindex + 1]);
k -= (tree[tindex + 1]);
e = tree[tindex];
if (e == 0)
{ // literal
lit = tree[tindex + 2];
mode = InflateCodeMode.LIT;
break;
}
if ((e & 16) != 0)
{ // length
get = e & 15;
len = tree[tindex + 2];
mode = InflateCodeMode.LENEXT;
break;
}
if ((e & 64) == 0)
{ // next table
need = e;
tree_index = tindex / 3 + tree[tindex + 2];
break;
}
if ((e & 32) != 0)
{ // end of block
mode = InflateCodeMode.WASH;
break;
}
mode = InflateCodeMode.BADCODE; // invalid code
z.msg = "invalid literal/length code";
r = ZLibStatus.Z_DATA_ERROR;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
case InflateCodeMode.LENEXT: // i: getting length extra (have base)
j = get;
while (k < (j))
{
if (n != 0) r = ZLibStatus.Z_OK;
else
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--; b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
len += (b & inflate_mask[j]);
b >>= j;
k -= j;
need = dbits;
tree = dtree;
tree_index = dtree_index;
mode = InflateCodeMode.DIST;
goto case InflateCodeMode.DIST;
case InflateCodeMode.DIST: // i: get distance next
j = need;
while (k < (j))
{
if (n != 0) r = ZLibStatus.Z_OK;
else
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--; b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
tindex = (tree_index + (b & inflate_mask[j])) * 3;
b >>= tree[tindex + 1];
k -= tree[tindex + 1];
e = (tree[tindex]);
if ((e & 16) != 0)
{ // distance
get = e & 15;
dist = tree[tindex + 2];
mode = InflateCodeMode.DISTEXT;
break;
}
if ((e & 64) == 0)
{ // next table
need = e;
tree_index = tindex / 3 + tree[tindex + 2];
break;
}
mode = InflateCodeMode.BADCODE; // invalid code
z.msg = "invalid distance code";
r = ZLibStatus.Z_DATA_ERROR;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
case InflateCodeMode.DISTEXT: // i: getting distance extra
j = get;
while (k < (j))
{
if (n != 0) r = ZLibStatus.Z_OK;
else
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--; b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
dist += (b & inflate_mask[j]);
b >>= j;
k -= j;
mode = InflateCodeMode.COPY;
goto case InflateCodeMode.COPY;
case InflateCodeMode.COPY: // o: copying bytes in window, waiting for space
f = q - dist;
while (f < 0)
{ // modulo window size-"while" instead
f += s.end; // of "if" handles invalid distances
}
while (len != 0)
{
if (m == 0)
{
if (q == s.end && s.read != 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; }
if (m == 0)
{
s.write = q; r = s.inflate_flush(z, r);
q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q;
if (q == s.end && s.read != 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; }
if (m == 0)
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
}
}
s.window[q++] = s.window[f++]; m--;
if (f == s.end)
f = 0;
len--;
}
mode = InflateCodeMode.START;
break;
case InflateCodeMode.LIT: // o: got literal, waiting for output space
if (m == 0)
{
if (q == s.end && s.read != 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; }
if (m == 0)
{
s.write = q; r = s.inflate_flush(z, r);
q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q;
if (q == s.end && s.read != 0) { q = 0; m = q < s.read ? s.read - q - 1 : s.end - q; }
if (m == 0)
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
}
}
r = ZLibStatus.Z_OK;
s.window[q++] = (byte)lit; m--;
mode = InflateCodeMode.START;
break;
case InflateCodeMode.WASH: // o: got eob, possibly more output
if (k > 7)
{ // return unused byte, if any
k -= 8;
n++;
p--; // can always return one
}
s.write = q; r = s.inflate_flush(z, r);
q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q;
if (s.read != s.write)
{
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
mode = InflateCodeMode.END;
goto case InflateCodeMode.END;
case InflateCodeMode.END:
r = ZLibStatus.Z_STREAM_END;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
case InflateCodeMode.BADCODE: // x: got error
r = ZLibStatus.Z_DATA_ERROR;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
default:
r = ZLibStatus.Z_STREAM_ERROR;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
}
}
// Called with number of bytes left to write in window at least 258
// (the maximum string length) and number of input bytes available
// at least ten. The ten bytes are six bytes for the longest length/
// distance pair plus four bytes for overloading the bit buffer.
internal ZLibStatus inflate_fast(int bl, int bd,
int[] tl, int tl_index,
int[] td, int td_index,
InflateBlocks s, ICompressor z)
{
int t; // temporary pointer
int[] tp; // temporary pointer
int tp_index; // temporary pointer
int e; // extra bits or operation
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int ml; // mask for literal/length tree
int md; // mask for distance tree
int c; // bytes to copy
int d; // distance back to copy from
int r; // copy source pointer
int tp_index_t_3; // (tp_index+t)*3
// load input, output, bit values
p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk;
q = s.write; m = q < s.read ? s.read - q - 1 : s.end - q;
// initialize masks
ml = inflate_mask[bl];
md = inflate_mask[bd];
// do until not enough input or output space for fast loop
do
{ // assume called with m >= 258 && n >= 10
// get literal/length code
while (k < (20))
{ // max bits for literal/length code
n--;
b |= (z.next_in[p++] & 0xff) << k; k += 8;
}
t = b & ml;
tp = tl;
tp_index = tl_index;
tp_index_t_3 = (tp_index + t) * 3;
if ((e = tp[tp_index_t_3]) == 0)
{
b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]);
s.window[q++] = (byte)tp[tp_index_t_3 + 2];
m--;
continue;
}
do
{
b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]);
if ((e & 16) != 0)
{
e &= 15;
c = tp[tp_index_t_3 + 2] + ((int)b & inflate_mask[e]);
b >>= e; k -= e;
// decode distance base of block to copy
while (k < (15))
{ // max bits for distance code
n--;
b |= (z.next_in[p++] & 0xff) << k; k += 8;
}
t = b & md;
tp = td;
tp_index = td_index;
tp_index_t_3 = (tp_index + t) * 3;
e = tp[tp_index_t_3];
do
{
b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]);
if ((e & 16) != 0)
{
// get extra bits to add to distance base
e &= 15;
while (k < (e))
{ // get extra bits (up to 13)
n--;
b |= (z.next_in[p++] & 0xff) << k; k += 8;
}
d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);
b >>= (e); k -= (e);
// do the copy
m -= c;
if (q >= d)
{ // offset before dest
// just copy
r = q - d;
if (q - r > 0 && 2 > (q - r))
{
s.window[q++] = s.window[r++]; // minimum count is three,
s.window[q++] = s.window[r++]; // so unroll loop a little
c -= 2;
}
else
{
System.Array.Copy(s.window, r, s.window, q, 2);
q += 2; r += 2; c -= 2;
}
}
else
{ // else offset after destination
r = q - d;
do
{
r += s.end; // force pointer in window
} while (r < 0); // covers invalid distances
e = s.end - r;
if (c > e)
{ // if source crosses,
c -= e; // wrapped copy
if (q - r > 0 && e > (q - r))
{
do { s.window[q++] = s.window[r++]; }
while (--e != 0);
}
else
{
System.Array.Copy(s.window, r, s.window, q, e);
q += e; r += e; e = 0;
}
r = 0; // copy rest from start of window
}
}
// copy all or what's left
if (q - r > 0 && c > (q - r))
{
do { s.window[q++] = s.window[r++]; }
while (--c != 0);
}
else
{
System.Array.Copy(s.window, r, s.window, q, c);
q += c; r += c; c = 0;
}
break;
}
else if ((e & 64) == 0)
{
t += tp[tp_index_t_3 + 2];
t += (b & inflate_mask[e]);
tp_index_t_3 = (tp_index + t) * 3;
e = tp[tp_index_t_3];
}
else
{
z.msg = "invalid distance code";
c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return ZLibStatus.Z_DATA_ERROR;
}
}
while (true);
break;
}
if ((e & 64) == 0)
{
t += tp[tp_index_t_3 + 2];
t += (b & inflate_mask[e]);
tp_index_t_3 = (tp_index + t) * 3;
if ((e = tp[tp_index_t_3]) == 0)
{
b >>= (tp[tp_index_t_3 + 1]); k -= (tp[tp_index_t_3 + 1]);
s.window[q++] = (byte)tp[tp_index_t_3 + 2];
m--;
break;
}
}
else if ((e & 32) != 0)
{
c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return ZLibStatus.Z_STREAM_END;
}
else
{
z.msg = "invalid literal/length code";
c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return ZLibStatus.Z_DATA_ERROR;
}
}
while (true);
}
while (m >= 258 && n >= 10);
// not enough input or output--restore pointers and return
c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= c << 3;
s.bitb = b; s.bitk = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
s.write = q;
return ZLibStatus.Z_OK;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.IMAP.Server
{
#region usings
using System;
using System.IO;
#endregion
/// <summary>
/// Provides data to event GetMessageItems.
/// </summary>
public class IMAP_eArgs_MessageItems
{
#region Members
private readonly IMAP_MessageItems_enum m_MessageItems = IMAP_MessageItems_enum.Message;
private readonly IMAP_Message m_pMessageInfo;
private readonly IMAP_Session m_pSession;
private string m_BodyStructure;
private bool m_CloseMessageStream = true;
private string m_Envelope;
private byte[] m_Header;
private bool m_MessageExists = true;
private long m_MessageStartOffset;
private Stream m_MessageStream;
#endregion
#region Properties
/// <summary>
/// Gets reference to current IMAP session.
/// </summary>
public IMAP_Session Session
{
get { return m_pSession; }
}
/// <summary>
/// Gets message info what message items to get.
/// </summary>
public IMAP_Message MessageInfo
{
get { return m_pMessageInfo; }
}
/// <summary>
/// Gets what message items must be filled.
/// </summary>
public IMAP_MessageItems_enum MessageItems
{
get { return m_MessageItems; }
}
/// <summary>
/// Gets or sets if message stream is closed automatically if all actions on it are completed.
/// Default value is true.
/// </summary>
public bool CloseMessageStream
{
get { return m_CloseMessageStream; }
set { m_CloseMessageStream = value; }
}
/// <summary>
/// Gets or sets message stream. When setting this property Stream position must be where message begins.
/// Fill this property only if IMAP_MessageItems_enum.Message flag is specified.
/// </summary>
public Stream MessageStream
{
get
{
if (m_MessageStream != null)
{
m_MessageStream.Position = m_MessageStartOffset;
}
return m_MessageStream;
}
set
{
if (value == null)
{
throw new ArgumentNullException("Property MessageStream value can't be null !");
}
if (!value.CanSeek)
{
throw new Exception("Stream must support seeking !");
}
m_MessageStream = value;
m_MessageStartOffset = m_MessageStream.Position;
}
}
/// <summary>
/// Gets message size in bytes.
/// </summary>
public long MessageSize
{
get
{
if (m_MessageStream == null)
{
throw new Exception("You must set MessageStream property first to use this property !");
}
else
{
return m_MessageStream.Length - m_MessageStream.Position;
}
}
}
/// <summary>
/// Gets or sets message main header.
/// Fill this property only if IMAP_MessageItems_enum.Header flag is specified.
/// </summary>
public byte[] Header
{
get { return m_Header; }
set
{
if (value == null)
{
throw new ArgumentNullException("Property Header value can't be null !");
}
m_Header = value;
}
}
/// <summary>
/// Gets or sets IMAP ENVELOPE string.
/// Fill this property only if IMAP_MessageItems_enum.Envelope flag is specified.
/// </summary>
public string Envelope
{
get { return m_Envelope; }
set
{
if (value == null)
{
throw new ArgumentNullException("Property Envelope value can't be null !");
}
m_Envelope = value;
}
}
/// <summary>
/// Gets or sets IMAP BODYSTRUCTURE string.
/// Fill this property only if IMAP_MessageItems_enum.BodyStructure flag is specified.
/// </summary>
public string BodyStructure
{
get { return m_BodyStructure; }
set
{
if (value == null)
{
throw new ArgumentNullException("Property BodyStructure value can't be null !");
}
m_BodyStructure = value;
}
}
/// <summary>
/// Gets or sets if message exists. Set this false, if message actually doesn't exist any more.
/// </summary>
public bool MessageExists
{
get { return m_MessageExists; }
set { m_MessageExists = value; }
}
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="session">Reference to current IMAP session.</param>
/// <param name="messageInfo">Message info what message items to get.</param>
/// <param name="messageItems">Specifies message items what must be filled.</param>
public IMAP_eArgs_MessageItems(IMAP_Session session,
IMAP_Message messageInfo,
IMAP_MessageItems_enum messageItems)
{
m_pSession = session;
m_pMessageInfo = messageInfo;
m_MessageItems = messageItems;
}
#endregion
#region Methods
/// <summary>
/// Clean up any resources being used.
/// </summary>
public void Dispose()
{
if (m_CloseMessageStream && m_MessageStream != null)
{
m_MessageStream.Dispose();
m_MessageStream = null;
}
}
#endregion
#region Overrides
/// <summary>
/// Default deconstructor.
/// </summary>
~IMAP_eArgs_MessageItems()
{
Dispose();
}
#endregion
#region Internal methods
/// <summary>
/// Checks that all required data items are provided, if not throws exception.
/// </summary>
internal void Validate()
{
if ((m_MessageItems & IMAP_MessageItems_enum.BodyStructure) != 0 && m_BodyStructure == null)
{
throw new Exception(
"IMAP BODYSTRUCTURE is required, but not provided to IMAP server component !");
}
if ((m_MessageItems & IMAP_MessageItems_enum.Envelope) != 0 && m_Envelope == null)
{
throw new Exception("IMAP ENVELOPE is required, but not provided to IMAP server component !");
}
if ((m_MessageItems & IMAP_MessageItems_enum.Header) != 0 && m_Header == null)
{
throw new Exception("Message header is required, but not provided to IMAP server component !");
}
if ((m_MessageItems & IMAP_MessageItems_enum.Message) != 0 && m_MessageStream == null)
{
throw new Exception("Full message is required, but not provided to IMAP server component !");
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace MigAz.Azure.UserControls
{
partial class AzureLoginContextViewer
{
/// <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.groupSubscription = new System.Windows.Forms.GroupBox();
this.lblTenantName = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.lblSourceSubscriptionId = new System.Windows.Forms.Label();
this.lblSourceSubscriptionName = new System.Windows.Forms.Label();
this.lblSourceUser = new System.Windows.Forms.Label();
this.lblSourceEnvironment = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnAzureContext = new System.Windows.Forms.Button();
this.groupSubscription.SuspendLayout();
this.SuspendLayout();
//
// groupSubscription
//
this.groupSubscription.Controls.Add(this.lblTenantName);
this.groupSubscription.Controls.Add(this.label6);
this.groupSubscription.Controls.Add(this.lblSourceSubscriptionId);
this.groupSubscription.Controls.Add(this.lblSourceSubscriptionName);
this.groupSubscription.Controls.Add(this.lblSourceUser);
this.groupSubscription.Controls.Add(this.lblSourceEnvironment);
this.groupSubscription.Controls.Add(this.label4);
this.groupSubscription.Controls.Add(this.label3);
this.groupSubscription.Controls.Add(this.label2);
this.groupSubscription.Controls.Add(this.label1);
this.groupSubscription.Controls.Add(this.btnAzureContext);
this.groupSubscription.Location = new System.Drawing.Point(2, 2);
this.groupSubscription.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.groupSubscription.Name = "groupSubscription";
this.groupSubscription.Padding = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.groupSubscription.Size = new System.Drawing.Size(662, 152);
this.groupSubscription.TabIndex = 1;
this.groupSubscription.TabStop = false;
this.groupSubscription.Text = "Azure Subscription";
//
// lblTenantName
//
this.lblTenantName.AutoSize = true;
this.lblTenantName.Location = new System.Drawing.Point(168, 74);
this.lblTenantName.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblTenantName.Name = "lblTenantName";
this.lblTenantName.Size = new System.Drawing.Size(14, 20);
this.lblTenantName.TabIndex = 10;
this.lblTenantName.Text = "-";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(16, 74);
this.label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(63, 20);
this.label6.TabIndex = 9;
this.label6.Text = "Tenant:";
//
// lblSourceSubscriptionId
//
this.lblSourceSubscriptionId.AutoSize = true;
this.lblSourceSubscriptionId.Location = new System.Drawing.Point(168, 117);
this.lblSourceSubscriptionId.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblSourceSubscriptionId.Name = "lblSourceSubscriptionId";
this.lblSourceSubscriptionId.Size = new System.Drawing.Size(14, 20);
this.lblSourceSubscriptionId.TabIndex = 8;
this.lblSourceSubscriptionId.Text = "-";
//
// lblSourceSubscriptionName
//
this.lblSourceSubscriptionName.AutoSize = true;
this.lblSourceSubscriptionName.Location = new System.Drawing.Point(168, 95);
this.lblSourceSubscriptionName.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblSourceSubscriptionName.Name = "lblSourceSubscriptionName";
this.lblSourceSubscriptionName.Size = new System.Drawing.Size(14, 20);
this.lblSourceSubscriptionName.TabIndex = 7;
this.lblSourceSubscriptionName.Text = "-";
//
// lblSourceUser
//
this.lblSourceUser.AutoSize = true;
this.lblSourceUser.Location = new System.Drawing.Point(168, 52);
this.lblSourceUser.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblSourceUser.Name = "lblSourceUser";
this.lblSourceUser.Size = new System.Drawing.Size(14, 20);
this.lblSourceUser.TabIndex = 6;
this.lblSourceUser.Text = "-";
//
// lblSourceEnvironment
//
this.lblSourceEnvironment.AutoSize = true;
this.lblSourceEnvironment.Location = new System.Drawing.Point(168, 30);
this.lblSourceEnvironment.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblSourceEnvironment.Name = "lblSourceEnvironment";
this.lblSourceEnvironment.Size = new System.Drawing.Size(14, 20);
this.lblSourceEnvironment.TabIndex = 5;
this.lblSourceEnvironment.Text = "-";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(16, 117);
this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(119, 20);
this.label4.TabIndex = 4;
this.label4.Text = "Subscription Id:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(16, 95);
this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(147, 20);
this.label3.TabIndex = 3;
this.label3.Text = "Subscription Name:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(16, 52);
this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(47, 20);
this.label2.TabIndex = 2;
this.label2.Text = "User:";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(16, 30);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(102, 20);
this.label1.TabIndex = 1;
this.label1.Text = "Environment:";
//
// btnAzureContext
//
this.btnAzureContext.Location = new System.Drawing.Point(552, 18);
this.btnAzureContext.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.btnAzureContext.Name = "btnAzureContext";
this.btnAzureContext.Size = new System.Drawing.Size(106, 32);
this.btnAzureContext.TabIndex = 0;
this.btnAzureContext.Text = "Change";
this.btnAzureContext.UseVisualStyleBackColor = true;
this.btnAzureContext.Click += new System.EventHandler(this.btnAzureContext_Click);
//
// AzureLoginContextViewer
//
this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.groupSubscription);
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Name = "AzureLoginContextViewer";
this.Size = new System.Drawing.Size(670, 169);
this.EnabledChanged += new System.EventHandler(this.AzureLoginContextViewer_EnabledChanged);
this.Resize += new System.EventHandler(this.AzureLoginContextViewer_Resize);
this.groupSubscription.ResumeLayout(false);
this.groupSubscription.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupSubscription;
private System.Windows.Forms.Label lblSourceSubscriptionId;
private System.Windows.Forms.Label lblSourceSubscriptionName;
private System.Windows.Forms.Label lblSourceUser;
private System.Windows.Forms.Label lblSourceEnvironment;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnAzureContext;
private System.Windows.Forms.Label lblTenantName;
private System.Windows.Forms.Label label6;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Timers;
using Timer=System.Timers.Timer;
using Nini.Config;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.CoreModules.World.Serialiser;
using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using OpenSim.Tests.Common.Setup;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Scene presence tests
/// </summary>
[TestFixture]
public class ScenePresenceTests
{
public Scene scene, scene2, scene3;
public UUID agent1, agent2, agent3;
public static Random random;
public ulong region1,region2,region3;
public AgentCircuitData acd1;
public SceneObjectGroup sog1, sog2, sog3;
public TestClient testclient;
[TestFixtureSetUp]
public void Init()
{
scene = SceneSetupHelpers.SetupScene("Neighbour x", UUID.Random(), 1000, 1000);
scene2 = SceneSetupHelpers.SetupScene("Neighbour x+1", UUID.Random(), 1001, 1000);
scene3 = SceneSetupHelpers.SetupScene("Neighbour x-1", UUID.Random(), 999, 1000);
ISharedRegionModule interregionComms = new LocalSimulationConnectorModule();
interregionComms.Initialise(new IniConfigSource());
interregionComms.PostInitialise();
SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), interregionComms);
SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), interregionComms);
SceneSetupHelpers.SetupSceneModules(scene3, new IniConfigSource(), interregionComms);
agent1 = UUID.Random();
agent2 = UUID.Random();
agent3 = UUID.Random();
random = new Random();
sog1 = NewSOG(UUID.Random(), scene, agent1);
sog2 = NewSOG(UUID.Random(), scene, agent1);
sog3 = NewSOG(UUID.Random(), scene, agent1);
//ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
region1 = scene.RegionInfo.RegionHandle;
region2 = scene2.RegionInfo.RegionHandle;
region3 = scene3.RegionInfo.RegionHandle;
}
/// <summary>
/// Test adding a root agent to a scene. Doesn't yet actually complete crossing the agent into the scene.
/// </summary>
[Test]
public void T010_TestAddRootAgent()
{
TestHelper.InMethod();
string firstName = "testfirstname";
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = agent1;
agent.firstname = firstName;
agent.lastname = "testlastname";
agent.SessionID = UUID.Random();
agent.SecureSessionID = UUID.Random();
agent.circuitcode = 123;
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = Vector3.Zero;
agent.CapsPath = GetRandomCapsObjectPath();
agent.ChildrenCapSeeds = new Dictionary<ulong, string>();
agent.child = true;
if (scene.PresenceService == null)
Console.WriteLine("Presence Service is null");
scene.PresenceService.LoginAgent(agent.AgentID.ToString(), agent.SessionID, agent.SecureSessionID);
string reason;
scene.NewUserConnection(agent, (uint)TeleportFlags.ViaLogin, out reason);
testclient = new TestClient(agent, scene);
scene.AddNewClient(testclient);
ScenePresence presence = scene.GetScenePresence(agent1);
Assert.That(presence, Is.Not.Null, "presence is null");
Assert.That(presence.Firstname, Is.EqualTo(firstName), "First name not same");
acd1 = agent;
}
/// <summary>
/// Test removing an uncrossed root agent from a scene.
/// </summary>
[Test]
public void T011_TestRemoveRootAgent()
{
TestHelper.InMethod();
scene.RemoveClient(agent1);
ScenePresence presence = scene.GetScenePresence(agent1);
Assert.That(presence, Is.Null, "presence is not null");
}
[Test]
public void T012_TestAddNeighbourRegion()
{
TestHelper.InMethod();
string reason;
if (acd1 == null)
fixNullPresence();
scene.NewUserConnection(acd1, 0, out reason);
if (testclient == null)
testclient = new TestClient(acd1, scene);
scene.AddNewClient(testclient);
ScenePresence presence = scene.GetScenePresence(agent1);
presence.MakeRootAgent(new Vector3(90,90,90),false);
string cap = presence.ControllingClient.RequestClientInfo().CapsPath;
presence.AddNeighbourRegion(region2, cap);
presence.AddNeighbourRegion(region3, cap);
List<ulong> neighbours = presence.GetKnownRegionList();
Assert.That(neighbours.Count, Is.EqualTo(2));
}
public void fixNullPresence()
{
string firstName = "testfirstname";
AgentCircuitData agent = new AgentCircuitData();
agent.AgentID = agent1;
agent.firstname = firstName;
agent.lastname = "testlastname";
agent.SessionID = UUID.Zero;
agent.SecureSessionID = UUID.Zero;
agent.circuitcode = 123;
agent.BaseFolder = UUID.Zero;
agent.InventoryFolder = UUID.Zero;
agent.startpos = Vector3.Zero;
agent.CapsPath = GetRandomCapsObjectPath();
acd1 = agent;
}
[Test]
public void T013_TestRemoveNeighbourRegion()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
presence.RemoveNeighbourRegion(region3);
List<ulong> neighbours = presence.GetKnownRegionList();
Assert.That(neighbours.Count,Is.EqualTo(1));
/*
presence.MakeChildAgent;
presence.MakeRootAgent;
CompleteAvatarMovement
*/
}
// I'm commenting this test, because this is not supposed to happen here
//[Test]
public void T020_TestMakeRootAgent()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
Assert.That(presence.IsChildAgent, Is.False, "Starts out as a root agent");
presence.MakeChildAgent();
Assert.That(presence.IsChildAgent, Is.True, "Did not change to child agent after MakeChildAgent");
// Accepts 0 but rejects Constants.RegionSize
Vector3 pos = new Vector3(0,unchecked(Constants.RegionSize-1),0);
presence.MakeRootAgent(pos,true);
Assert.That(presence.IsChildAgent, Is.False, "Did not go back to root agent");
Assert.That(presence.AbsolutePosition, Is.EqualTo(pos), "Position is not the same one entered");
}
// I'm commenting this test because it does not represent
// crossings. The Thread.Sleep's in here are not meaningful mocks,
// and they sometimes fail in panda.
// We need to talk in order to develop a test
// that really tests region crossings. There are 3 async components,
// but things are synchronous among them. So there should be
// 3 threads in here.
//[Test]
public void T021_TestCrossToNewRegion()
{
TestHelper.InMethod();
scene.RegisterRegionWithGrid();
scene2.RegisterRegionWithGrid();
// Adding child agent to region 1001
string reason;
scene2.NewUserConnection(acd1,0, out reason);
scene2.AddNewClient(testclient);
ScenePresence presence = scene.GetScenePresence(agent1);
presence.MakeRootAgent(new Vector3(0,unchecked(Constants.RegionSize-1),0), true);
ScenePresence presence2 = scene2.GetScenePresence(agent1);
// Adding neighbour region caps info to presence2
string cap = presence.ControllingClient.RequestClientInfo().CapsPath;
presence2.AddNeighbourRegion(region1, cap);
Assert.That(presence.IsChildAgent, Is.False, "Did not start root in origin region.");
Assert.That(presence2.IsChildAgent, Is.True, "Is not a child on destination region.");
// Cross to x+1
presence.AbsolutePosition = new Vector3(Constants.RegionSize+1,3,100);
presence.Update();
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
// Mimicking communication between client and server, by waiting OK from client
// sent by TestClient.CrossRegion call. Originally, this is network comm.
if (!wh.WaitOne(5000,false))
{
presence.Update();
if (!wh.WaitOne(8000,false))
throw new ArgumentException("1 - Timeout waiting for signal/variable.");
}
// This is a TestClient specific method that fires OnCompleteMovementToRegion event, which
// would normally be fired after receiving the reply packet from comm. done on the last line.
testclient.CompleteMovement();
// Crossings are asynchronous
int timer = 10;
// Make sure cross hasn't already finished
if (!presence.IsInTransit && !presence.IsChildAgent)
{
// If not and not in transit yet, give it some more time
Thread.Sleep(5000);
}
// Enough time, should at least be in transit by now.
while (presence.IsInTransit && timer > 0)
{
Thread.Sleep(1000);
timer-=1;
}
Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 2->1.");
Assert.That(presence.IsChildAgent, Is.True, "Did not complete region cross as expected.");
Assert.That(presence2.IsChildAgent, Is.False, "Did not receive root status after receiving agent.");
// Cross Back
presence2.AbsolutePosition = new Vector3(-10, 3, 100);
presence2.Update();
if (!wh.WaitOne(5000,false))
{
presence2.Update();
if (!wh.WaitOne(8000,false))
throw new ArgumentException("2 - Timeout waiting for signal/variable.");
}
testclient.CompleteMovement();
if (!presence2.IsInTransit && !presence2.IsChildAgent)
{
// If not and not in transit yet, give it some more time
Thread.Sleep(5000);
}
// Enough time, should at least be in transit by now.
while (presence2.IsInTransit && timer > 0)
{
Thread.Sleep(1000);
timer-=1;
}
Assert.That(timer,Is.GreaterThan(0),"Timed out waiting to cross 1->2.");
Assert.That(presence2.IsChildAgent, Is.True, "Did not return from region as expected.");
Assert.That(presence.IsChildAgent, Is.False, "Presence was not made root in old region again.");
}
[Test]
public void T030_TestAddAttachments()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
presence.AddAttachment(sog1);
presence.AddAttachment(sog2);
presence.AddAttachment(sog3);
Assert.That(presence.HasAttachments(), Is.True);
Assert.That(presence.ValidateAttachments(), Is.True);
}
[Test]
public void T031_RemoveAttachments()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
presence.RemoveAttachment(sog1);
presence.RemoveAttachment(sog2);
presence.RemoveAttachment(sog3);
Assert.That(presence.HasAttachments(), Is.False);
}
// I'm commenting this test because scene setup NEEDS InventoryService to
// be non-null
//[Test]
public void T032_CrossAttachments()
{
TestHelper.InMethod();
ScenePresence presence = scene.GetScenePresence(agent1);
ScenePresence presence2 = scene2.GetScenePresence(agent1);
presence2.AddAttachment(sog1);
presence2.AddAttachment(sog2);
ISharedRegionModule serialiser = new SerialiserModule();
SceneSetupHelpers.SetupSceneModules(scene, new IniConfigSource(), serialiser);
SceneSetupHelpers.SetupSceneModules(scene2, new IniConfigSource(), serialiser);
Assert.That(presence.HasAttachments(), Is.False, "Presence has attachments before cross");
//Assert.That(presence2.CrossAttachmentsIntoNewRegion(region1, true), Is.True, "Cross was not successful");
Assert.That(presence2.HasAttachments(), Is.False, "Presence2 objects were not deleted");
Assert.That(presence.HasAttachments(), Is.True, "Presence has not received new objects");
}
[TearDown]
public void TearDown()
{
if (MainServer.Instance != null) MainServer.Instance.Stop();
}
public static string GetRandomCapsObjectPath()
{
UUID caps = UUID.Random();
string capsPath = caps.ToString();
capsPath = capsPath.Remove(capsPath.Length - 4, 4);
return capsPath;
}
private SceneObjectGroup NewSOG(UUID uuid, Scene scene, UUID agent)
{
SceneObjectPart sop = new SceneObjectPart();
sop.Name = RandomName();
sop.Description = RandomName();
sop.Text = RandomName();
sop.SitName = RandomName();
sop.TouchName = RandomName();
sop.UUID = uuid;
sop.Shape = PrimitiveBaseShape.Default;
sop.Shape.State = 1;
sop.OwnerID = agent;
SceneObjectGroup sog = new SceneObjectGroup(sop);
sog.SetScene(scene);
return sog;
}
private static string RandomName()
{
StringBuilder name = new StringBuilder();
int size = random.Next(5,12);
char ch ;
for (int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
name.Append(ch);
}
return name.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////////
// JitHelpers
// Low-level Jit Helpers
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading;
using System.Runtime;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Runtime.CompilerServices {
// Wrapper for address of a string variable on stack
internal struct StringHandleOnStack
{
private IntPtr m_ptr;
internal StringHandleOnStack(IntPtr pString)
{
m_ptr = pString;
}
}
// Wrapper for address of a object variable on stack
internal struct ObjectHandleOnStack
{
private IntPtr m_ptr;
internal ObjectHandleOnStack(IntPtr pObject)
{
m_ptr = pObject;
}
}
// Wrapper for StackCrawlMark
internal struct StackCrawlMarkHandle
{
private IntPtr m_ptr;
internal StackCrawlMarkHandle(IntPtr stackMark)
{
m_ptr = stackMark;
}
}
// Helper class to assist with unsafe pinning of arbitrary objects. The typical usage pattern is:
// fixed (byte * pData = &JitHelpers.GetPinningHelper(value).m_data)
// {
// ... pData is what Object::GetData() returns in VM ...
// }
internal class PinningHelper
{
public byte m_data;
}
[FriendAccessAllowed]
internal static class JitHelpers
{
// The special dll name to be used for DllImport of QCalls
internal const string QCall = "QCall";
// Wraps object variable into a handle. Used to return managed strings from QCalls.
// s has to be a local variable on the stack.
[SecurityCritical]
static internal StringHandleOnStack GetStringHandleOnStack(ref string s)
{
return new StringHandleOnStack(UnsafeCastToStackPointer(ref s));
}
// Wraps object variable into a handle. Used to pass managed object references in and out of QCalls.
// o has to be a local variable on the stack.
[SecurityCritical]
static internal ObjectHandleOnStack GetObjectHandleOnStack<T>(ref T o) where T : class
{
return new ObjectHandleOnStack(UnsafeCastToStackPointer(ref o));
}
// Wraps StackCrawlMark into a handle. Used to pass StackCrawlMark to QCalls.
// stackMark has to be a local variable on the stack.
[SecurityCritical]
static internal StackCrawlMarkHandle GetStackCrawlMarkHandle(ref StackCrawlMark stackMark)
{
return new StackCrawlMarkHandle(UnsafeCastToStackPointer(ref stackMark));
}
#if _DEBUG
[SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
T ret = UnsafeCastInternal<T>(o);
Contract.Assert(ret == (o as T), "Invalid use of JitHelpers.UnsafeCast!");
return ret;
}
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
[SecurityCritical]
static private T UnsafeCastInternal<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
Contract.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(short)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ushort)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(byte)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(sbyte)),
"Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!");
return UnsafeEnumCastInternal<T>(val);
}
static private int UnsafeEnumCastInternal<T>(T val) where T : struct // Actually T must be 4 (or less) byte enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
Contract.Assert(typeof(T).IsEnum
&& (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
"Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
return UnsafeEnumCastLongInternal<T>(val);
}
static private long UnsafeEnumCastLongInternal<T>(T val) where T : struct // Actually T must be 8 byte enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
// Internal method for getting a raw pointer for handles in JitHelpers.
// The reference has to point into a local stack variable in order so it can not be moved by the GC.
[SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
IntPtr p = UnsafeCastToStackPointerInternal<T>(ref val);
Contract.Assert(IsAddressInStack(p), "Pointer not in the stack!");
return p;
}
[SecurityCritical]
static private IntPtr UnsafeCastToStackPointerInternal<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns val!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
#else // _DEBUG
// The IL body of this method is not critical, but its body will be replaced with unsafe code, so
// this method is effectively critical
[SecurityCritical]
[FriendAccessAllowed]
static internal T UnsafeCast<T>(Object o) where T : class
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
// should be return (int) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
// should be return (long) val; but C# does not allow, runtime does this magically
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
[SecurityCritical]
static internal IntPtr UnsafeCastToStackPointer<T>(ref T val)
{
// The body of this function will be replaced by the EE with unsafe code that just returns o!!!
// See getILIntrinsicImplementation for how this happens.
throw new InvalidOperationException();
}
#endif // _DEBUG
// Set the given element in the array without any type or range checks
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static internal void UnsafeSetArrayElement(Object[] target, int index, Object element);
// Used for unsafe pinning of arbitrary objects.
[System.Security.SecurityCritical] // auto-generated
static internal PinningHelper GetPinningHelper(Object o)
{
// This cast is really unsafe - call the private version that does not assert in debug
#if _DEBUG
return UnsafeCastInternal<PinningHelper>(o);
#else
return UnsafeCast<PinningHelper>(o);
#endif
}
#if _DEBUG
[SecurityCritical]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static bool IsAddressInStack(IntPtr ptr);
#endif
}
}
| |
//
// CubanoVisualizer.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009 Aaron Bockover
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using Cairo;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Cubano.NowPlaying
{
public class CubanoVisualizer : IDisposable
{
public class RenderRequestArgs : EventArgs
{
private Gdk.Rectangle damage;
public Gdk.Rectangle Damage {
get { return damage; }
set { damage = value; }
}
}
private Queue<float []> points = new Queue<float []> ();
private Gdk.Rectangle render_damage;
public EventHandler<RenderRequestArgs> RenderRequest;
private object render_points_mutex = new object ();
public object RenderPointsMutex {
get { return render_points_mutex; }
}
private float [] render_points;
public float [] RenderPoints {
get { return render_points; }
}
private float render_loudness;
public float RenderLoudness {
get { return render_loudness; }
}
private int smoothing_passes = 5;
public int SmoothingPasses {
get { return smoothing_passes; }
set { smoothing_passes = value; }
}
private int sample_points = 25;
public int SamplePoints {
get { return sample_points; }
set { sample_points = value; }
}
private int height = 80;
public int Height {
get { return height; }
set { height = value; }
}
private int width = 160;
public int Width {
get { return width; }
set { width = value; }
}
private Color color = new Color (0.2, 0.2, 0.2);
public Color Color {
get { return color; }
set { color = value; }
}
public CubanoVisualizer ()
{
ServiceManager.PlayerEngine.EngineAfterInitialize += engine => ConnectOrDisconnect (engine, true);
Connect ();
}
private void ConnectOrDisconnect (PlayerEngine engine, bool connect)
{
var vis_engine = engine as IVisualizationDataSource;
if (vis_engine != null) {
if (connect) {
vis_engine.DataAvailable += OnVisualizationDataAvailable;
} else {
vis_engine.DataAvailable -= OnVisualizationDataAvailable;
}
}
}
public void Connect ()
{
foreach (var engine in ServiceManager.PlayerEngine.Engines) {
if (engine.IsInitialized) {
ConnectOrDisconnect (engine, true);
}
}
RequestRender ();
}
public void Disconnect ()
{
foreach (var engine in ServiceManager.PlayerEngine.Engines) {
ConnectOrDisconnect (engine, false);
}
RequestRender ();
}
public void Dispose ()
{
Disconnect ();
}
protected virtual void OnRenderRequest ()
{
var handler = RenderRequest;
if (handler != null) {
handler (this, new RenderRequestArgs () { Damage = render_damage });
}
}
private void RequestRender ()
{
Banshee.Base.ThreadAssist.ProxyToMain (delegate {
OnRenderRequest ();
});
}
private DateTime last_render = DateTime.MinValue;
private TimeSpan max_framerate = TimeSpan.FromSeconds (1.0 / 20.0);
private void OnVisualizationDataAvailable (float [][] pcm, float [][] spectrum)
{
if (spectrum == null || DateTime.Now - last_render < max_framerate) {
return;
}
lock (render_points_mutex) {
UpdatePoints (spectrum[0]);
}
RequestRender ();
last_render = DateTime.Now;
}
private float [] AnalyzeSpectrum (float [] spectrum, int sampleCount)
{
int sample_idx = 0;
var samples = new float[sampleCount * 2];
// Sample the spectrum to produce 2 * sampleCount points, creating
// a smoothed mirrored audio frame spectrum for averaging with
// previous AnalyzeSpectrum passes or suitable for direct rendering
for (int i = 0, n = spectrum.Length; i < n; i++) {
sample_idx = (int)Math.Round ((i / (double)n) * (sampleCount - 1));
int sample_idx_ofs = sampleCount - sample_idx - 1;
samples[sample_idx_ofs] += spectrum[i] / (n / (sampleCount - 1));
samples[sample_idx + sampleCount] = samples[sample_idx_ofs];
}
// Find the maximum point in the computed points
float max = 0;
for (int i = 0; i < samples.Length; i++) {
max = Math.Max (max, samples[i]);
}
// Fudge the mid point to be the max
samples[(int)Math.Floor (samples.Length / 2.0)] = max;
samples[(int)Math.Ceiling (samples.Length / 2.0)] = max;
// Scale the set by the maximum point
for (int i = 0; i < samples.Length; i++) {
samples[i] /= (float)(1.0f - Math.Sqrt (max));
}
return samples;
}
private void UpdatePoints (float [] spectrum)
{
// Add the current analyzed audio frame and dequeue any expired frame
points.Enqueue (AnalyzeSpectrum (spectrum, SamplePoints));
if (points.Count > SmoothingPasses) {
points.Dequeue ();
}
render_points = null;
render_loudness = 0;
// Average all the queued frames into a frame suitable for direct rendering,
// creating very smooth visualization data; the higher SmoothingPasses is
// the smoother the data, but the more static (less motion)
foreach (var iter in points) {
if (render_points == null) {
render_points = new float[iter.Length];
}
for (int i = 0, n = Math.Min (iter.Length, render_points.Length); i < n; i++) {
render_points[i] += iter[i] / (float)points.Count;
}
}
for (int i = 0; i < render_points.Length / 2; i++) {
render_loudness = (float)Math.Max (render_loudness, render_points[i]);
}
}
private void RenderDebug (Context cr)
{
double x = 320;
for (int i = 0, n = render_points.Length; i < n; i++) {
cr.Color = new Color (0, 1, 0);
cr.Rectangle (x, Height - Height * render_points[i], 10, Height * render_points[i]);
cr.Fill ();
cr.Color = new Color (0, 0, 0, 0.3);
cr.LineWidth = 1;
cr.Rectangle (x + 0.5, 0.5, 10 - 1, Height - 1);
cr.Stroke ();
x += 12;
}
}
private Cairo.ImageSurface surface;
public void Render (Context cr)
{
if (surface == null) {
return;
}
cr.SetSource (surface);
cr.Paint ();
}
private void InnerRender ()
{
lock (render_points_mutex) {
if (render_points == null) {
return;
}
if (surface == null || surface.Width != Width || surface.Height != Height) {
surface = new ImageSurface (Format.Argb32, Width, Height);
}
using (var cr = new Context (surface)) {
cr.Save ();
cr.Operator = Operator.Clear;
cr.Paint ();
cr.Restore ();
RenderGoo (cr);
}
// RenderDebug (cr);
}
}
private void RenderGoo (Context cr)
{
double max_r = Height / 2;
double x_ofs = Width / RenderPoints.Length;
double xc = 0, yc = Height;
double r;
double min_x = Width, max_x = 0, min_y = Height, max_y = yc;
for (int i = 0, n = RenderPoints.Length; i < n; i++) {
xc += x_ofs;
r = Height * RenderPoints[i];
cr.MoveTo (xc, yc);
cr.Arc (xc, yc, r, 0, 2 * Math.PI);
if (r > 0) {
min_x = Math.Min (min_x, xc - r);
max_x = Math.Max (max_x, xc + r);
min_y = Math.Min (min_y, yc - r);
}
}
render_damage = new Gdk.Rectangle (
(int)Math.Floor (min_x),
(int)Math.Floor (min_y),
(int)Math.Ceiling (max_x - min_x),
(int)Math.Ceiling (max_y - min_y)
);
cr.ClosePath ();
var grad = new LinearGradient (0, 0, 0, Height);
Color c = Color;
c.A = 0;
grad.AddColorStop (0, c);
c.A = RenderLoudness / 2;
grad.AddColorStop (1, c);
cr.Pattern = grad;
cr.Fill ();
grad.Destroy ();
}
}
}
| |
// 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.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
#if !SRM
using Microsoft.CodeAnalysis.CodeGen;
#endif
#if SRM
namespace System.Reflection.Metadata.Ecma335.Blobs
#else
namespace Roslyn.Reflection.Metadata.Ecma335.Blobs
#endif
{
#if SRM
public
#endif
struct InstructionEncoder
{
public BlobBuilder Builder { get; }
private readonly BranchBuilder _branchBuilderOpt;
public InstructionEncoder(BlobBuilder builder, BranchBuilder branchBuilder = null)
{
Builder = builder;
_branchBuilderOpt = branchBuilder;
}
public int Offset => Builder.Count;
public void OpCode(ILOpCode code)
{
if (unchecked((byte)code) == (ushort)code)
{
Builder.WriteByte((byte)code);
}
else
{
// IL opcodes that occupy two bytes are written to
// the byte stream with the high-order byte first,
// in contrast to the little-endian format of the
// numeric arguments and tokens.
Builder.WriteUInt16BE((ushort)code);
}
}
public void Token(EntityHandle handle)
{
Token(MetadataTokens.GetToken(handle));
}
public void Token(int token)
{
Builder.WriteInt32(token);
}
public void LongBranchTarget(int ilOffset)
{
Builder.WriteInt32(ilOffset);
}
public void ShortBranchTarget(byte ilOffset)
{
Builder.WriteByte(ilOffset);
}
public void LoadString(UserStringHandle handle)
{
OpCode(ILOpCode.Ldstr);
Token(MetadataTokens.GetToken(handle));
}
public void Call(EntityHandle methodHandle)
{
OpCode(ILOpCode.Call);
Token(methodHandle);
}
public void CallIndirect(StandaloneSignatureHandle signature)
{
OpCode(ILOpCode.Calli);
Token(signature);
}
public void LoadConstantI4(int value)
{
ILOpCode code;
switch (value)
{
case -1: code = ILOpCode.Ldc_i4_m1; break;
case 0: code = ILOpCode.Ldc_i4_0; break;
case 1: code = ILOpCode.Ldc_i4_1; break;
case 2: code = ILOpCode.Ldc_i4_2; break;
case 3: code = ILOpCode.Ldc_i4_3; break;
case 4: code = ILOpCode.Ldc_i4_4; break;
case 5: code = ILOpCode.Ldc_i4_5; break;
case 6: code = ILOpCode.Ldc_i4_6; break;
case 7: code = ILOpCode.Ldc_i4_7; break;
case 8: code = ILOpCode.Ldc_i4_8; break;
default:
if (unchecked((sbyte)value == value))
{
OpCode(ILOpCode.Ldc_i4_s);
Builder.WriteSByte(unchecked((sbyte)value));
}
else
{
OpCode(ILOpCode.Ldc_i4);
Builder.WriteInt32(value);
}
return;
}
OpCode(code);
}
public void LoadConstantI8(long value)
{
OpCode(ILOpCode.Ldc_i8);
Builder.WriteInt64(value);
}
public void LoadConstantR4(float value)
{
OpCode(ILOpCode.Ldc_r4);
Builder.WriteSingle(value);
}
public void LoadConstantR8(double value)
{
OpCode(ILOpCode.Ldc_r8);
Builder.WriteDouble(value);
}
public void LoadLocal(int slotIndex)
{
switch (slotIndex)
{
case 0: OpCode(ILOpCode.Ldloc_0); break;
case 1: OpCode(ILOpCode.Ldloc_1); break;
case 2: OpCode(ILOpCode.Ldloc_2); break;
case 3: OpCode(ILOpCode.Ldloc_3); break;
default:
if (slotIndex < 0xFF)
{
OpCode(ILOpCode.Ldloc_s);
Builder.WriteByte(unchecked((byte)slotIndex));
}
else
{
OpCode(ILOpCode.Ldloc);
Builder.WriteInt32(slotIndex);
}
break;
}
}
public void StoreLocal(int slotIndex)
{
switch (slotIndex)
{
case 0: OpCode(ILOpCode.Stloc_0); break;
case 1: OpCode(ILOpCode.Stloc_1); break;
case 2: OpCode(ILOpCode.Stloc_2); break;
case 3: OpCode(ILOpCode.Stloc_3); break;
default:
if (slotIndex < 0xFF)
{
OpCode(ILOpCode.Stloc_s);
Builder.WriteByte(unchecked((byte)slotIndex));
}
else
{
OpCode(ILOpCode.Stloc);
Builder.WriteInt32(slotIndex);
}
break;
}
}
public void LoadLocalAddress(int slotIndex)
{
if (slotIndex < 0xFF)
{
OpCode(ILOpCode.Ldloca_s);
Builder.WriteByte(unchecked((byte)slotIndex));
}
else
{
OpCode(ILOpCode.Ldloca);
Builder.WriteInt32(slotIndex);
}
}
public void LoadArgument(int argumentIndex)
{
switch (argumentIndex)
{
case 0: OpCode(ILOpCode.Ldarg_0); break;
case 1: OpCode(ILOpCode.Ldarg_1); break;
case 2: OpCode(ILOpCode.Ldarg_2); break;
case 3: OpCode(ILOpCode.Ldarg_3); break;
default:
if (argumentIndex < 0xFF)
{
OpCode(ILOpCode.Ldarg_s);
Builder.WriteByte(unchecked((byte)argumentIndex));
}
else
{
OpCode(ILOpCode.Ldarg);
Builder.WriteInt32(argumentIndex);
}
break;
}
}
public void LoadArgumentAddress(int argumentIndex)
{
if (argumentIndex < 0xFF)
{
OpCode(ILOpCode.Ldarga_s);
Builder.WriteByte(unchecked((byte)argumentIndex));
}
else
{
OpCode(ILOpCode.Ldarga);
Builder.WriteInt32(argumentIndex);
}
}
public void StoreArgument(int argumentIndex)
{
if (argumentIndex < 0xFF)
{
OpCode(ILOpCode.Starg_s);
Builder.WriteByte(unchecked((byte)argumentIndex));
}
else
{
OpCode(ILOpCode.Starg);
Builder.WriteInt32(argumentIndex);
}
}
public LabelHandle DefineLabel()
{
return GetBranchBuilder().AddLabel();
}
public void Branch(ILOpCode code, LabelHandle label)
{
// throws if code is not a branch:
ILOpCode shortCode = code.GetShortBranch();
GetBranchBuilder().AddBranch(Offset, label, (byte)shortCode);
OpCode(shortCode);
// -1 points in the middle of the branch instruction and is thus invalid.
// We want to produce invalid IL so that if the caller doesn't patch the branches
// the branch instructions will be invalid in an obvious way.
Builder.WriteSByte(-1);
}
public void MarkLabel(LabelHandle label)
{
GetBranchBuilder().MarkLabel(Offset, label);
}
private BranchBuilder GetBranchBuilder()
{
if (_branchBuilderOpt == null)
{
// TODO: localize
throw new InvalidOperationException(nameof(InstructionEncoder) + " created without a branch builder");
}
return _branchBuilderOpt;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.SNATTranslationAddressBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBSNATTranslationAddressSNATTranslationAddressStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonULong64))]
public partial class LocalLBSNATTranslationAddress : iControlInterface {
public LocalLBSNATTranslationAddress() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void create(
string [] translation_addresses,
long [] unit_ids
) {
this.Invoke("create", new object [] {
translation_addresses,
unit_ids});
}
public System.IAsyncResult Begincreate(string [] translation_addresses,long [] unit_ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
translation_addresses,
unit_ids}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_translation_addresses
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void delete_all_translation_addresses(
) {
this.Invoke("delete_all_translation_addresses", new object [0]);
}
public System.IAsyncResult Begindelete_all_translation_addresses(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_translation_addresses", new object[0], callback, asyncState);
}
public void Enddelete_all_translation_addresses(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_translation_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void delete_translation_address(
string [] translation_addresses
) {
this.Invoke("delete_translation_address", new object [] {
translation_addresses});
}
public System.IAsyncResult Begindelete_translation_address(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_translation_address", new object[] {
translation_addresses}, callback, asyncState);
}
public void Enddelete_translation_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBSNATTranslationAddressSNATTranslationAddressStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBSNATTranslationAddressSNATTranslationAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBSNATTranslationAddressSNATTranslationAddressStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBSNATTranslationAddressSNATTranslationAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_arp_state(
string [] translation_addresses
) {
object [] results = this.Invoke("get_arp_state", new object [] {
translation_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_arp_state(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_arp_state", new object[] {
translation_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonULong64 [] get_connection_limit(
string [] translation_addresses
) {
object [] results = this.Invoke("get_connection_limit", new object [] {
translation_addresses});
return ((CommonULong64 [])(results[0]));
}
public System.IAsyncResult Beginget_connection_limit(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_limit", new object[] {
translation_addresses}, callback, asyncState);
}
public CommonULong64 [] Endget_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonULong64 [])(results[0]));
}
//-----------------------------------------------------------------------
// get_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_enabled_state(
string [] translation_addresses
) {
object [] results = this.Invoke("get_enabled_state", new object [] {
translation_addresses});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_enabled_state(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_enabled_state", new object[] {
translation_addresses}, callback, asyncState);
}
public CommonEnabledState [] Endget_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ip_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_ip_timeout(
string [] translation_addresses
) {
object [] results = this.Invoke("get_ip_timeout", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_ip_timeout(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ip_timeout", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_ip_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBSNATTranslationAddressSNATTranslationAddressStatistics get_statistics(
string [] translation_addresses
) {
object [] results = this.Invoke("get_statistics", new object [] {
translation_addresses});
return ((LocalLBSNATTranslationAddressSNATTranslationAddressStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
translation_addresses}, callback, asyncState);
}
public LocalLBSNATTranslationAddressSNATTranslationAddressStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBSNATTranslationAddressSNATTranslationAddressStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_tcp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_tcp_timeout(
string [] translation_addresses
) {
object [] results = this.Invoke("get_tcp_timeout", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_tcp_timeout(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_tcp_timeout", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_tcp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_udp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_udp_timeout(
string [] translation_addresses
) {
object [] results = this.Invoke("get_udp_timeout", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_udp_timeout(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_udp_timeout", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_udp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_unit_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_unit_id(
string [] translation_addresses
) {
object [] results = this.Invoke("get_unit_id", new object [] {
translation_addresses});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_unit_id(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_unit_id", new object[] {
translation_addresses}, callback, asyncState);
}
public long [] Endget_unit_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void reset_statistics(
string [] translation_addresses
) {
this.Invoke("reset_statistics", new object [] {
translation_addresses});
}
public System.IAsyncResult Beginreset_statistics(string [] translation_addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
translation_addresses}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_arp_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_arp_state(
string [] translation_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_arp_state", new object [] {
translation_addresses,
states});
}
public System.IAsyncResult Beginset_arp_state(string [] translation_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_arp_state", new object[] {
translation_addresses,
states}, callback, asyncState);
}
public void Endset_arp_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_connection_limit(
string [] translation_addresses,
CommonULong64 [] limits
) {
this.Invoke("set_connection_limit", new object [] {
translation_addresses,
limits});
}
public System.IAsyncResult Beginset_connection_limit(string [] translation_addresses,CommonULong64 [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_limit", new object[] {
translation_addresses,
limits}, callback, asyncState);
}
public void Endset_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_enabled_state(
string [] translation_addresses,
CommonEnabledState [] states
) {
this.Invoke("set_enabled_state", new object [] {
translation_addresses,
states});
}
public System.IAsyncResult Beginset_enabled_state(string [] translation_addresses,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_enabled_state", new object[] {
translation_addresses,
states}, callback, asyncState);
}
public void Endset_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ip_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_ip_timeout(
string [] translation_addresses,
long [] timeouts
) {
this.Invoke("set_ip_timeout", new object [] {
translation_addresses,
timeouts});
}
public System.IAsyncResult Beginset_ip_timeout(string [] translation_addresses,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ip_timeout", new object[] {
translation_addresses,
timeouts}, callback, asyncState);
}
public void Endset_ip_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_tcp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_tcp_timeout(
string [] translation_addresses,
long [] timeouts
) {
this.Invoke("set_tcp_timeout", new object [] {
translation_addresses,
timeouts});
}
public System.IAsyncResult Beginset_tcp_timeout(string [] translation_addresses,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_tcp_timeout", new object[] {
translation_addresses,
timeouts}, callback, asyncState);
}
public void Endset_tcp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_udp_timeout
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_udp_timeout(
string [] translation_addresses,
long [] timeouts
) {
this.Invoke("set_udp_timeout", new object [] {
translation_addresses,
timeouts});
}
public System.IAsyncResult Beginset_udp_timeout(string [] translation_addresses,long [] timeouts, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_udp_timeout", new object[] {
translation_addresses,
timeouts}, callback, asyncState);
}
public void Endset_udp_timeout(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_unit_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/SNATTranslationAddress",
RequestNamespace="urn:iControl:LocalLB/SNATTranslationAddress", ResponseNamespace="urn:iControl:LocalLB/SNATTranslationAddress")]
public void set_unit_id(
string [] translation_addresses,
long [] unit_ids
) {
this.Invoke("set_unit_id", new object [] {
translation_addresses,
unit_ids});
}
public System.IAsyncResult Beginset_unit_id(string [] translation_addresses,long [] unit_ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_unit_id", new object[] {
translation_addresses,
unit_ids}, callback, asyncState);
}
public void Endset_unit_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.SNATTranslationAddress.SNATTranslationAddressStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBSNATTranslationAddressSNATTranslationAddressStatisticEntry
{
private string translation_addressField;
public string translation_address
{
get { return this.translation_addressField; }
set { this.translation_addressField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.SNATTranslationAddress.SNATTranslationAddressStatistics", Namespace = "urn:iControl")]
public partial class LocalLBSNATTranslationAddressSNATTranslationAddressStatistics
{
private LocalLBSNATTranslationAddressSNATTranslationAddressStatisticEntry [] statisticsField;
public LocalLBSNATTranslationAddressSNATTranslationAddressStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor.SpriteCollectionEditor
{
public class TextureEditor
{
public enum Mode
{
None,
Texture,
Anchor,
Collider
}
int textureBorderPixels = 16;
Mode mode = Mode.Texture;
Vector2 textureScrollPos = new Vector2(0.0f, 0.0f);
bool drawColliderNormals = false;
float editorDisplayScale
{
get { return SpriteCollection.editorDisplayScale; }
set { SpriteCollection.editorDisplayScale = value; }
}
Color[] _handleInactiveColors = new Color[] {
new Color32(127, 201, 122, 255), // default
new Color32(180, 0, 0, 255), // red
new Color32(255, 255, 255, 255), // white
new Color32(32, 32, 32, 255), // black
};
Color[] _handleActiveColors = new Color[] {
new Color32(228, 226, 60, 255),
new Color32(255, 0, 0, 255),
new Color32(255, 0, 0, 255),
new Color32(96, 0, 0, 255),
};
tk2dSpriteCollectionDefinition.ColliderColor currentColliderColor = tk2dSpriteCollectionDefinition.ColliderColor.Default;
Color handleInactiveColor { get { return _handleInactiveColors[(int)currentColliderColor]; } }
Color handleActiveColor { get { return _handleActiveColors[(int)currentColliderColor]; } }
IEditorHost host;
public TextureEditor(IEditorHost host)
{
this.host = host;
}
SpriteCollectionProxy SpriteCollection { get { return host.SpriteCollection; } }
public void SetMode(Mode mode)
{
if (this.mode != mode)
{
this.mode = mode;
HandleUtility.Repaint();
}
}
Vector2 ClosestPointOnLine(Vector2 p, Vector2 p1, Vector2 p2)
{
float magSq = (p2 - p1).sqrMagnitude;
if (magSq < float.Epsilon)
return p1;
float u = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / magSq;
if (u < 0.0f || u > 1.0f)
return p1;
return p1 + (p2 - p1) * u;
}
void DrawPolygonColliderEditor(Rect r, ref tk2dSpriteColliderIsland[] islands, Texture2D tex, bool forceClosed)
{
Vector2 origin = new Vector2(r.x, r.y);
Vector3 origin3 = new Vector3(r.x, r.y, 0);
// Sanitize
if (islands == null || islands.Length == 0 ||
!islands[0].IsValid())
{
islands = new tk2dSpriteColliderIsland[1];
islands[0] = new tk2dSpriteColliderIsland();
islands[0].connected = true;
int w = tex.width;
int h = tex.height;
Vector2[] p = new Vector2[4];
p[0] = new Vector2(0, 0);
p[1] = new Vector2(0, h);
p[2] = new Vector2(w, h);
p[3] = new Vector2(w, 0);
islands[0].points = p;
}
Color previousHandleColor = Handles.color;
bool insertPoint = false;
if (Event.current.clickCount == 2 && Event.current.type == EventType.MouseDown)
{
insertPoint = true;
Event.current.Use();
}
if (r.Contains(Event.current.mousePosition) && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.C)
{
Vector2 min = Event.current.mousePosition / editorDisplayScale - new Vector2(16.0f, 16.0f);
Vector3 max = Event.current.mousePosition / editorDisplayScale + new Vector2(16.0f, 16.0f);
min.x = Mathf.Clamp(min.x, 0, tex.width * editorDisplayScale);
min.y = Mathf.Clamp(min.y, 0, tex.height * editorDisplayScale);
max.x = Mathf.Clamp(max.x, 0, tex.width * editorDisplayScale);
max.y = Mathf.Clamp(max.y, 0, tex.height * editorDisplayScale);
tk2dSpriteColliderIsland island = new tk2dSpriteColliderIsland();
island.connected = true;
Vector2[] p = new Vector2[4];
p[0] = new Vector2(min.x, min.y);
p[1] = new Vector2(min.x, max.y);
p[2] = new Vector2(max.x, max.y);
p[3] = new Vector2(max.x, min.y);
island.points = p;
System.Array.Resize(ref islands, islands.Length + 1);
islands[islands.Length - 1] = island;
Event.current.Use();
}
// Draw outline lines
int deletedIsland = -1;
for (int islandId = 0; islandId < islands.Length; ++islandId)
{
float closestDistanceSq = 1.0e32f;
Vector2 closestPoint = Vector2.zero;
int closestPreviousPoint = 0;
var island = islands[islandId];
Handles.color = handleInactiveColor;
Vector2 ov = (island.points.Length>0)?island.points[island.points.Length-1]:Vector2.zero;
for (int i = 0; i < island.points.Length; ++i)
{
Vector2 v = island.points[i];
// Don't draw last connection if its not connected
if (!island.connected && i == 0)
{
ov = v;
continue;
}
if (insertPoint)
{
Vector2 localMousePosition = (Event.current.mousePosition - origin) / editorDisplayScale;
Vector2 closestPointToCursor = ClosestPointOnLine(localMousePosition, ov, v);
float lengthSq = (closestPointToCursor - localMousePosition).sqrMagnitude;
if (lengthSq < closestDistanceSq)
{
closestDistanceSq = lengthSq;
closestPoint = closestPointToCursor;
closestPreviousPoint = i;
}
}
if (drawColliderNormals)
{
Vector2 l = (ov - v).normalized;
Vector2 n = new Vector2(l.y, -l.x);
Vector2 c = (v + ov) * 0.5f * editorDisplayScale + origin;
Handles.DrawLine(c, c + n * 16.0f);
}
Handles.DrawLine(v * editorDisplayScale + origin, ov * editorDisplayScale + origin);
ov = v;
}
Handles.color = previousHandleColor;
if (insertPoint && closestDistanceSq < 16.0f)
{
var tmpList = new List<Vector2>(island.points);
tmpList.Insert(closestPreviousPoint, closestPoint);
island.points = tmpList.ToArray();
HandleUtility.Repaint();
}
int deletedIndex = -1;
bool flipIsland = false;
bool disconnectIsland = false;
Event ev = Event.current;
for (int i = 0; i < island.points.Length; ++i)
{
Vector3 cp = island.points[i];
int id = "tk2dPolyEditor".GetHashCode() + islandId * 10000 + i;
cp = (tk2dGuiUtility.PositionHandle(id, cp * editorDisplayScale + origin3, 4.0f, handleInactiveColor, handleActiveColor, true) - origin) / editorDisplayScale;
if (GUIUtility.keyboardControl == id && ev.type == EventType.KeyDown) {
switch (ev.keyCode) {
case KeyCode.Backspace:
case KeyCode.Delete: {
GUIUtility.keyboardControl = 0;
deletedIndex = i;
ev.Use();
break;
}
case KeyCode.X: {
GUIUtility.keyboardControl = 0;
deletedIsland = islandId;
ev.Use();
break;
}
case KeyCode.T: {
if (!forceClosed) {
GUIUtility.keyboardControl = 0;
disconnectIsland = true;
ev.Use();
}
break;
}
case KeyCode.F: {
flipIsland = true;
GUIUtility.keyboardControl = 0;
ev.Use();
break;
}
case KeyCode.Escape: {
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
ev.Use();
break;
}
}
}
cp.x = Mathf.Round(cp.x * 2) / 2.0f; // allow placing point at half texel
cp.y = Mathf.Round(cp.y * 2) / 2.0f;
// constrain
cp.x = Mathf.Clamp(cp.x, 0.0f, tex.width);
cp.y = Mathf.Clamp(cp.y, 0.0f, tex.height);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(cp.x, cp.y));
island.points[i] = cp;
}
if (flipIsland)
{
System.Array.Reverse(island.points);
}
if (disconnectIsland)
{
island.connected = !island.connected;
if (island.connected && island.points.Length < 3)
{
Vector2 pp = (island.points[1] - island.points[0]);
float l = pp.magnitude;
pp.Normalize();
Vector2 nn = new Vector2(pp.y, -pp.x);
nn.y = Mathf.Clamp(nn.y, 0, tex.height);
nn.x = Mathf.Clamp(nn.x, 0, tex.width);
System.Array.Resize(ref island.points, island.points.Length + 1);
island.points[island.points.Length - 1] = (island.points[0] + island.points[1]) * 0.5f + nn * l * 0.5f;
}
}
if (deletedIndex != -1 &&
((island.connected && island.points.Length > 3) ||
(!island.connected && island.points.Length > 2)) )
{
var tmpList = new List<Vector2>(island.points);
tmpList.RemoveAt(deletedIndex);
island.points = tmpList.ToArray();
}
}
// Can't delete the last island
if (deletedIsland != -1 && islands.Length > 1)
{
var tmpIslands = new List<tk2dSpriteColliderIsland>(islands);
tmpIslands.RemoveAt(deletedIsland);
islands = tmpIslands.ToArray();
}
}
void DrawCustomBoxColliderEditor(Rect r, tk2dSpriteCollectionDefinition param, Texture2D tex)
{
Vector2 origin = new Vector2(r.x, r.y);
// sanitize
if (param.boxColliderMin == Vector2.zero && param.boxColliderMax == Vector2.zero)
{
param.boxColliderMax = new Vector2(tex.width, tex.height);
}
Vector3[] pt = new Vector3[] {
new Vector3(param.boxColliderMin.x * editorDisplayScale + origin.x, param.boxColliderMin.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMax.x * editorDisplayScale + origin.x, param.boxColliderMin.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMax.x * editorDisplayScale + origin.x, param.boxColliderMax.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMin.x * editorDisplayScale + origin.x, param.boxColliderMax.y * editorDisplayScale + origin.y, 0.0f),
};
Color32 transparentColor = handleInactiveColor;
transparentColor.a = 10;
Handles.DrawSolidRectangleWithOutline(pt, transparentColor, handleInactiveColor);
// Draw grab handles
Vector3 handlePos;
int id = 16433;
// Draw top handle
handlePos = (pt[0] + pt[1]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 0, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMin.y = handlePos.y;
if (param.boxColliderMin.y > param.boxColliderMax.y) param.boxColliderMin.y = param.boxColliderMax.y;
// Draw bottom handle
handlePos = (pt[2] + pt[3]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 1, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMax.y = handlePos.y;
if (param.boxColliderMax.y < param.boxColliderMin.y) param.boxColliderMax.y = param.boxColliderMin.y;
// Draw left handle
handlePos = (pt[0] + pt[3]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 2, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMin.x = handlePos.x;
if (param.boxColliderMin.x > param.boxColliderMax.x) param.boxColliderMin.x = param.boxColliderMax.x;
// Draw right handle
handlePos = (pt[1] + pt[2]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 3, handlePos, 4.0f, handleInactiveColor, handleActiveColor) - origin) / editorDisplayScale;
param.boxColliderMax.x = handlePos.x;
if (param.boxColliderMax.x < param.boxColliderMin.x) param.boxColliderMax.x = param.boxColliderMin.x;
param.boxColliderMax.x = Mathf.Round(param.boxColliderMax.x);
param.boxColliderMax.y = Mathf.Round(param.boxColliderMax.y);
param.boxColliderMin.x = Mathf.Round(param.boxColliderMin.x);
param.boxColliderMin.y = Mathf.Round(param.boxColliderMin.y);
// constrain
param.boxColliderMax.x = Mathf.Clamp(param.boxColliderMax.x, 0.0f, tex.width);
param.boxColliderMax.y = Mathf.Clamp(param.boxColliderMax.y, 0.0f, tex.height);
param.boxColliderMin.x = Mathf.Clamp(param.boxColliderMin.x, 0.0f, tex.width);
param.boxColliderMin.y = Mathf.Clamp(param.boxColliderMin.y, 0.0f, tex.height);
tk2dGuiUtility.SetPositionHandleValue(id + 0, new Vector2(0, param.boxColliderMin.y));
tk2dGuiUtility.SetPositionHandleValue(id + 1, new Vector2(0, param.boxColliderMax.y));
tk2dGuiUtility.SetPositionHandleValue(id + 2, new Vector2(param.boxColliderMin.x, 0));
tk2dGuiUtility.SetPositionHandleValue(id + 3, new Vector2(param.boxColliderMax.x, 0));
}
void HandleKeys()
{
Event evt = Event.current;
if (evt.type == EventType.KeyUp && evt.shift)
{
Mode newMode = Mode.None;
switch (evt.keyCode)
{
case KeyCode.Q: newMode = Mode.Texture; break;
case KeyCode.W: newMode = Mode.Anchor; break;
case KeyCode.E: newMode = Mode.Collider; break;
case KeyCode.N: drawColliderNormals = !drawColliderNormals; HandleUtility.Repaint(); break;
}
if (newMode != Mode.None)
{
mode = newMode;
evt.Use();
}
}
}
public void DrawTextureView(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
HandleKeys();
if (mode == Mode.None)
mode = Mode.Texture;
// sanity check
if (editorDisplayScale <= 1.0f) editorDisplayScale = 1.0f;
// mirror data
currentColliderColor = param.colliderColor;
GUILayout.BeginVertical(tk2dEditorSkin.SC_BodyBackground, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
if (texture == null)
{
// Get somewhere to put the texture...
GUILayoutUtility.GetRect(128.0f, 128.0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
}
else
{
bool allowAnchor = param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom;
bool allowCollider = (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom);
if (mode == Mode.Anchor && !allowAnchor) mode = Mode.Texture;
if (mode == Mode.Collider && !allowCollider) mode = Mode.Texture;
Rect rect = GUILayoutUtility.GetRect(128.0f, 128.0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
tk2dGrid.Draw(rect);
// middle mouse drag and scroll zoom
if (rect.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.MouseDrag && Event.current.button == 2)
{
textureScrollPos -= Event.current.delta * editorDisplayScale;
Event.current.Use();
HandleUtility.Repaint();
}
if (Event.current.type == EventType.ScrollWheel)
{
editorDisplayScale -= Event.current.delta.y * 0.03f;
Event.current.Use();
HandleUtility.Repaint();
}
}
bool alphaBlend = true;
textureScrollPos = GUI.BeginScrollView(rect, textureScrollPos,
new Rect(0, 0, textureBorderPixels * 2 + (texture.width) * editorDisplayScale, textureBorderPixels * 2 + (texture.height) * editorDisplayScale));
Rect textureRect = new Rect(textureBorderPixels, textureBorderPixels, texture.width * editorDisplayScale, texture.height * editorDisplayScale);
texture.filterMode = FilterMode.Point;
GUI.DrawTexture(textureRect, texture, ScaleMode.ScaleAndCrop, alphaBlend);
if (mode == Mode.Collider)
{
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom)
DrawCustomBoxColliderEditor(textureRect, param, texture);
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon)
DrawPolygonColliderEditor(textureRect, ref param.polyColliderIslands, texture, false);
}
if (mode == Mode.Texture && param.customSpriteGeometry)
{
DrawPolygonColliderEditor(textureRect, ref param.geometryIslands, texture, true);
}
// Anchor
if (mode == Mode.Anchor)
{
Color handleColor = new Color(0,0,0,0.2f);
Color lineColor = Color.white;
Vector2 anchor = new Vector2(param.anchorX, param.anchorY);
Vector2 origin = new Vector2(textureRect.x, textureRect.y);
int id = 99999;
anchor = (tk2dGuiUtility.PositionHandle(id, anchor * editorDisplayScale + origin, 12.0f, handleColor, handleColor ) - origin) / editorDisplayScale;
Color oldColor = Handles.color;
Handles.color = lineColor;
float w = Mathf.Max(rect.width, texture.width * editorDisplayScale);
float h = Mathf.Max(rect.height, texture.height * editorDisplayScale);
Handles.DrawLine(new Vector3(textureRect.x, textureRect.y + anchor.y * editorDisplayScale, 0), new Vector3(textureRect.x + w, textureRect.y + anchor.y * editorDisplayScale, 0));
Handles.DrawLine(new Vector3(textureRect.x + anchor.x * editorDisplayScale, textureRect.y + 0, 0), new Vector3(textureRect.x + anchor.x * editorDisplayScale, textureRect.y + h, 0));
Handles.color = oldColor;
// constrain
param.anchorX = Mathf.Clamp(Mathf.Round(anchor.x), 0.0f, texture.width);
param.anchorY = Mathf.Clamp(Mathf.Round(anchor.y), 0.0f, texture.height);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(param.anchorX, param.anchorY));
HandleUtility.Repaint();
}
GUI.EndScrollView();
}
// Draw toolbar
DrawToolbar(param, texture);
GUILayout.EndVertical();
}
public void DrawToolbar(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
bool allowAnchor = param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom;
bool allowCollider = (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom);
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
mode = GUILayout.Toggle((mode == Mode.Texture), new GUIContent("Sprite", "Shift+Q"), EditorStyles.toolbarButton)?Mode.Texture:mode;
if (allowAnchor)
mode = GUILayout.Toggle((mode == Mode.Anchor), new GUIContent("Anchor", "Shift+W"), EditorStyles.toolbarButton)?Mode.Anchor:mode;
if (allowCollider)
mode = GUILayout.Toggle((mode == Mode.Collider), new GUIContent("Collider", "Shift+E"), EditorStyles.toolbarButton)?Mode.Collider:mode;
GUILayout.FlexibleSpace();
if (tk2dGuiUtility.HasActivePositionHandle)
{
string str = "X: " + tk2dGuiUtility.ActiveHandlePosition.x + " Y: " + tk2dGuiUtility.ActiveHandlePosition.y;
GUILayout.Label(str, EditorStyles.toolbarTextField);
}
if ((mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon) ||
(mode == Mode.Texture && param.customSpriteGeometry))
{
drawColliderNormals = GUILayout.Toggle(drawColliderNormals, new GUIContent("Show Normals", "Shift+N"), EditorStyles.toolbarButton);
}
if (mode == Mode.Texture && texture != null) {
GUILayout.Label(string.Format("W: {0} H: {1}", texture.width, texture.height));
}
GUILayout.EndHorizontal();
}
public void DrawEmptyTextureView()
{
mode = Mode.None;
GUILayout.FlexibleSpace();
}
public void DrawTextureInspector(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
if (mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon)
{
param.colliderColor = (tk2dSpriteCollectionDefinition.ColliderColor)EditorGUILayout.EnumPopup("Display Color", param.colliderColor);
tk2dGuiUtility.InfoBox("Points" +
"\nClick drag - move point" +
"\nClick hold + delete/bkspace - delete point" +
"\nDouble click on line - add point", tk2dGuiUtility.WarningLevel.Info);
tk2dGuiUtility.InfoBox("Islands" +
"\nClick hold point + X - delete island" +
"\nPress C - create island at cursor" +
"\nClick hold point + T - toggle connected" +
"\nClick hold point + F - flip island", tk2dGuiUtility.WarningLevel.Info);
}
if (mode == Mode.Texture && param.customSpriteGeometry)
{
param.colliderColor = (tk2dSpriteCollectionDefinition.ColliderColor)EditorGUILayout.EnumPopup("Display Color", param.colliderColor);
tk2dGuiUtility.InfoBox("Points" +
"\nClick drag - move point" +
"\nClick hold + delete/bkspace - delete point" +
"\nDouble click on line - add point", tk2dGuiUtility.WarningLevel.Info);
tk2dGuiUtility.InfoBox("Islands" +
"\nClick hold point + X - delete island" +
"\nPress C - create island at cursor" +
"\nClick hold point + F - flip island", tk2dGuiUtility.WarningLevel.Info);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet
{
protected object CreateDiskGetDynamicParameters()
{
dynamicParameters = new RuntimeDefinedParameterDictionary();
var pResourceGroupName = new RuntimeDefinedParameter();
pResourceGroupName.Name = "ResourceGroupName";
pResourceGroupName.ParameterType = typeof(string);
pResourceGroupName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 1,
Mandatory = true
});
pResourceGroupName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ResourceGroupName", pResourceGroupName);
var pDiskName = new RuntimeDefinedParameter();
pDiskName.Name = "DiskName";
pDiskName.ParameterType = typeof(string);
pDiskName.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByDynamicParameters",
Position = 2,
Mandatory = true
});
pDiskName.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("DiskName", pDiskName);
var pArgumentList = new RuntimeDefinedParameter();
pArgumentList.Name = "ArgumentList";
pArgumentList.ParameterType = typeof(object[]);
pArgumentList.Attributes.Add(new ParameterAttribute
{
ParameterSetName = "InvokeByStaticParameters",
Position = 3,
Mandatory = true
});
pArgumentList.Attributes.Add(new AllowNullAttribute());
dynamicParameters.Add("ArgumentList", pArgumentList);
return dynamicParameters;
}
protected void ExecuteDiskGetMethod(object[] invokeMethodInputParameters)
{
string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]);
string diskName = (string)ParseParameter(invokeMethodInputParameters[1]);
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(diskName))
{
var result = DisksClient.Get(resourceGroupName, diskName);
WriteObject(result);
}
else if (!string.IsNullOrEmpty(resourceGroupName))
{
var result = DisksClient.ListByResourceGroup(resourceGroupName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = DisksClient.ListByResourceGroupNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
WriteObject(resultList, true);
}
else
{
var result = DisksClient.List();
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = DisksClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
WriteObject(resultList, true);
}
}
}
public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet
{
protected PSArgument[] CreateDiskGetParameters()
{
string resourceGroupName = string.Empty;
string diskName = string.Empty;
return ConvertFromObjectsToArguments(
new string[] { "ResourceGroupName", "DiskName" },
new object[] { resourceGroupName, diskName });
}
}
[Cmdlet(VerbsCommon.Get, "AzureRmDisk", DefaultParameterSetName = "DefaultParameter")]
[OutputType(typeof(PSDisk))]
public partial class GetAzureRmDisk : ComputeAutomationBaseCmdlet
{
protected override void ProcessRecord()
{
ExecuteClientAction(() =>
{
string resourceGroupName = this.ResourceGroupName;
string diskName = this.DiskName;
if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(diskName))
{
var result = DisksClient.Get(resourceGroupName, diskName);
var psObject = new PSDisk();
ComputeAutomationAutoMapperProfile.Mapper.Map<Disk, PSDisk>(result, psObject);
WriteObject(psObject);
}
else if (!string.IsNullOrEmpty(resourceGroupName))
{
var result = DisksClient.ListByResourceGroup(resourceGroupName);
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = DisksClient.ListByResourceGroupNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSDiskList>();
foreach (var r in resultList)
{
psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<Disk, PSDiskList>(r));
}
WriteObject(psObject, true);
}
else
{
var result = DisksClient.List();
var resultList = result.ToList();
var nextPageLink = result.NextPageLink;
while (!string.IsNullOrEmpty(nextPageLink))
{
var pageResult = DisksClient.ListNext(nextPageLink);
foreach (var pageItem in pageResult)
{
resultList.Add(pageItem);
}
nextPageLink = pageResult.NextPageLink;
}
var psObject = new List<PSDiskList>();
foreach (var r in resultList)
{
psObject.Add(ComputeAutomationAutoMapperProfile.Mapper.Map<Disk, PSDiskList>(r));
}
WriteObject(psObject, true);
}
});
}
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 1,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[AllowNull]
public string ResourceGroupName { get; set; }
[Parameter(
ParameterSetName = "DefaultParameter",
Position = 2,
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ValueFromPipeline = false)]
[Alias("Name")]
[AllowNull]
public string DiskName { get; set; }
}
}
| |
/**
* @file
* AllJoyn session options
*/
/******************************************************************************
* Copyright (c) 2012-2013 AllSeen Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
******************************************************************************/
using System;
using System.Runtime.InteropServices;
namespace AllJoynUnity
{
public partial class AllJoyn
{
/**
* SessionOpts contains a set of parameters that define a Session's characteristics.
*/
public class SessionOpts : IDisposable
{
/** Traffic type */
public enum TrafficType : byte
{
Messages = 0x01, /**< Session carries message traffic */
RawUnreliable = 0x02, /**< Session carries an unreliable (lossy) byte stream */
RawReliable = 0x04 /**< Session carries a reliable byte stream */
}
/** Proximity type */
public enum ProximityType : byte
{
Any = 0xFF,
Physical = 0x01,
Network = 0x02
}
#region Properties
public TrafficType Traffic /**< holds the Traffic type for this SessionOpt*/
{
get
{
return (TrafficType)alljoyn_sessionopts_get_traffic(_sessionOpts);
}
set
{
alljoyn_sessionopts_set_traffic(_sessionOpts, (byte)value);
}
}
/**
* Multi-point session capable.
* A session is multi-point if it can be joined multiple times to form a single
* session with multi (greater than 2) endpoints. When false, each join attempt
* creates a new point-to-point session.
*/
public bool IsMultipoint
{
get
{
return (alljoyn_sessionopts_get_multipoint(_sessionOpts) == 1 ? true : false);
}
set
{
alljoyn_sessionopts_set_multipoint(_sessionOpts, (value) ? (int)1 : (int)0);
}
}
/**
* Defines the proximity of the Session as Physical, Network, or Any.
*/
public ProximityType Proximity
{
get
{
return (ProximityType)alljoyn_sessionopts_get_proximity(_sessionOpts);
}
set
{
alljoyn_sessionopts_set_proximity(_sessionOpts, (byte)value);
}
}
/** Allowed Transports */
public TransportMask Transports
{
get
{
return (TransportMask)alljoyn_sessionopts_get_transports(_sessionOpts);
}
set
{
alljoyn_sessionopts_set_transports(_sessionOpts, (ushort)value);
}
}
#endregion
/**
* Construct a SessionOpts with specific parameters.
*
* @param trafficType Type of traffic.
* @param isMultipoint true iff session supports multipoint (greater than two endpoints).
* @param proximity Proximity constraint bitmask.
* @param transports Allowed transport types bitmask.
*/
public SessionOpts(TrafficType trafficType, bool isMultipoint, ProximityType proximity, TransportMask transports)
{
_sessionOpts = alljoyn_sessionopts_create((byte)trafficType, isMultipoint ? 1 : 0, (byte)proximity, (ushort)transports);
}
internal SessionOpts(IntPtr sessionOpts)
{
_sessionOpts = sessionOpts;
_isDisposed = true;
}
/**
* Determine whether this SessionOpts is compatible with the SessionOpts offered by other
*
* @param other Options to be compared against this one.
* @return true iff this SessionOpts can use the option set offered by other.
*/
public bool IsCompatible(SessionOpts other)
{
return (alljoyn_sessionopts_iscompatible(_sessionOpts, other._sessionOpts) == 1 ? true : false);
}
/**
* Compare SessionOpts
*
* @param one the SessionOpts being compared to
* @param other the SessionOpts being compared against
* @return true if all of the SessionOpts parameters are the same
*
*/
public static int Compare(SessionOpts one, SessionOpts other)
{
return alljoyn_sessionopts_cmp(one._sessionOpts, other._sessionOpts);
}
#region DLL Imports
[DllImport(DLL_IMPORT_TARGET)]
private static extern IntPtr alljoyn_sessionopts_create(byte traffic, int isMultipoint,
byte proximity, ushort transports);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_sessionopts_destroy(IntPtr opts);
[DllImport(DLL_IMPORT_TARGET)]
private static extern byte alljoyn_sessionopts_get_traffic(IntPtr opts);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_sessionopts_set_traffic(IntPtr opts, byte traffic);
[DllImport(DLL_IMPORT_TARGET)]
private static extern int alljoyn_sessionopts_get_multipoint(IntPtr opts);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_sessionopts_set_multipoint(IntPtr opts, int isMultipoint);
[DllImport(DLL_IMPORT_TARGET)]
private static extern byte alljoyn_sessionopts_get_proximity(IntPtr opts);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_sessionopts_set_proximity(IntPtr opts, byte proximity);
[DllImport(DLL_IMPORT_TARGET)]
private static extern ushort alljoyn_sessionopts_get_transports(IntPtr opts);
[DllImport(DLL_IMPORT_TARGET)]
private static extern void alljoyn_sessionopts_set_transports(IntPtr opts, ushort transports);
[DllImport(DLL_IMPORT_TARGET)]
private static extern int alljoyn_sessionopts_iscompatible(IntPtr one, IntPtr other);
[DllImport(DLL_IMPORT_TARGET)]
private static extern int alljoyn_sessionopts_cmp(IntPtr one, IntPtr other);
#endregion
#region IDisposable
~SessionOpts()
{
Dispose(false);
}
/**
* Dispose the SessionOpts
* @param disposing describes if its activly being disposed
*/
protected virtual void Dispose(bool disposing)
{
if(!_isDisposed)
{
alljoyn_sessionopts_destroy(_sessionOpts);
_sessionOpts = IntPtr.Zero;
}
_isDisposed = true;
}
/**
* Dispose the SessionOpts
*/
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region Internal Properties
internal IntPtr UnmanagedPtr
{
get
{
return _sessionOpts;
}
}
#endregion
#region Data
IntPtr _sessionOpts;
bool _isDisposed = false;
#endregion
}
}
}
| |
/// Credit jack.sydorenko, firagon
/// Sourced from - http://forum.unity3d.com/threads/new-ui-and-line-drawing.253772/
/// Updated/Refactored from - http://forum.unity3d.com/threads/new-ui-and-line-drawing.253772/#post-2528050
using System.Collections.Generic;
namespace UnityEngine.UI.Extensions
{
[AddComponentMenu("UI/Extensions/Primitives/UILineRenderer")]
[RequireComponent(typeof(RectTransform))]
public class UILineRenderer : UIPrimitiveBase
{
private enum SegmentType
{
Start,
Middle,
End,
Full,
}
public enum JoinType
{
Bevel,
Miter
}
public enum BezierType
{
None,
Quick,
Basic,
Improved,
Catenary,
}
private const float MIN_MITER_JOIN = 15 * Mathf.Deg2Rad;
// A bevel 'nice' join displaces the vertices of the line segment instead of simply rendering a
// quad to connect the endpoints. This improves the look of textured and transparent lines, since
// there is no overlapping.
private const float MIN_BEVEL_NICE_JOIN = 30 * Mathf.Deg2Rad;
private static Vector2 UV_TOP_LEFT, UV_BOTTOM_LEFT, UV_TOP_CENTER_LEFT, UV_TOP_CENTER_RIGHT, UV_BOTTOM_CENTER_LEFT, UV_BOTTOM_CENTER_RIGHT, UV_TOP_RIGHT, UV_BOTTOM_RIGHT;
private static Vector2[] startUvs, middleUvs, endUvs, fullUvs;
[SerializeField, Tooltip("Points to draw lines between\n Can be improved using the Resolution Option")]
internal Vector2[] m_points;
[SerializeField, Tooltip("Segments to be drawn\n This is a list of arrays of points")]
internal List<Vector2[]> m_segments;
[SerializeField, Tooltip("Thickness of the line")]
internal float lineThickness = 2;
[SerializeField, Tooltip("Use the relative bounds of the Rect Transform (0,0 -> 0,1) or screen space coordinates")]
internal bool relativeSize;
[SerializeField, Tooltip("Do the points identify a single line or split pairs of lines")]
internal bool lineList;
[SerializeField, Tooltip("Add end caps to each line\nMultiple caps when used with Line List")]
internal bool lineCaps;
[SerializeField, Tooltip("Resolution of the Bezier curve, different to line Resolution")]
internal int bezierSegmentsPerCurve = 10;
public float LineThickness
{
get { return lineThickness; }
set { lineThickness = value; SetAllDirty(); }
}
public bool RelativeSize
{
get { return relativeSize; }
set { relativeSize = value; SetAllDirty(); }
}
public bool LineList
{
get { return lineList; }
set { lineList = value; SetAllDirty(); }
}
public bool LineCaps
{
get { return lineCaps; }
set { lineCaps = value; SetAllDirty(); }
}
[Tooltip("The type of Join used between lines, Square/Mitre or Curved/Bevel")]
public JoinType LineJoins = JoinType.Bevel;
[Tooltip("Bezier method to apply to line, see docs for options\nCan't be used in conjunction with Resolution as Bezier already changes the resolution")]
public BezierType BezierMode = BezierType.None;
public int BezierSegmentsPerCurve
{
get { return bezierSegmentsPerCurve; }
set { bezierSegmentsPerCurve = value; }
}
[HideInInspector]
public bool drivenExternally = false;
/// <summary>
/// Points to be drawn in the line.
/// </summary>
public Vector2[] Points
{
get
{
return m_points;
}
set
{
if (m_points == value)
return;
m_points = value;
SetAllDirty();
}
}
/// <summary>
/// List of Segments to be drawn.
/// </summary>
public List<Vector2[]> Segments
{
get
{
return m_segments;
}
set
{
m_segments = value;
SetAllDirty();
}
}
private void PopulateMesh(VertexHelper vh, Vector2[] pointsToDraw)
{
//If Bezier is desired, pick the implementation
if (BezierMode != BezierType.None && BezierMode != BezierType.Catenary && pointsToDraw.Length > 3) {
BezierPath bezierPath = new BezierPath ();
bezierPath.SetControlPoints (pointsToDraw);
bezierPath.SegmentsPerCurve = bezierSegmentsPerCurve;
List<Vector2> drawingPoints;
switch (BezierMode) {
case BezierType.Basic:
drawingPoints = bezierPath.GetDrawingPoints0 ();
break;
case BezierType.Improved:
drawingPoints = bezierPath.GetDrawingPoints1 ();
break;
default:
drawingPoints = bezierPath.GetDrawingPoints2 ();
break;
}
pointsToDraw = drawingPoints.ToArray ();
}
if (BezierMode == BezierType.Catenary && pointsToDraw.Length == 2) {
CableCurve cable = new CableCurve (pointsToDraw);
cable.slack = Resoloution;
cable.steps = BezierSegmentsPerCurve;
pointsToDraw = cable.Points ();
}
if (ImproveResolution != ResolutionMode.None) {
pointsToDraw = IncreaseResolution (pointsToDraw);
}
// scale based on the size of the rect or use absolute, this is switchable
var sizeX = !relativeSize ? 1 : rectTransform.rect.width;
var sizeY = !relativeSize ? 1 : rectTransform.rect.height;
var offsetX = -rectTransform.pivot.x * sizeX;
var offsetY = -rectTransform.pivot.y * sizeY;
// Generate the quads that make up the wide line
var segments = new List<UIVertex[]> ();
if (lineList) {
for (var i = 1; i < pointsToDraw.Length; i += 2) {
var start = pointsToDraw [i - 1];
var end = pointsToDraw [i];
start = new Vector2 (start.x * sizeX + offsetX, start.y * sizeY + offsetY);
end = new Vector2 (end.x * sizeX + offsetX, end.y * sizeY + offsetY);
if (lineCaps) {
segments.Add (CreateLineCap (start, end, SegmentType.Start));
}
//segments.Add(CreateLineSegment(start, end, SegmentType.Full));
segments.Add (CreateLineSegment (start, end, SegmentType.Middle));
if (lineCaps) {
segments.Add (CreateLineCap (start, end, SegmentType.End));
}
}
} else {
for (var i = 1; i < pointsToDraw.Length; i++) {
var start = pointsToDraw [i - 1];
var end = pointsToDraw [i];
start = new Vector2 (start.x * sizeX + offsetX, start.y * sizeY + offsetY);
end = new Vector2 (end.x * sizeX + offsetX, end.y * sizeY + offsetY);
if (lineCaps && i == 1) {
segments.Add (CreateLineCap (start, end, SegmentType.Start));
}
segments.Add (CreateLineSegment (start, end, SegmentType.Middle));
//segments.Add(CreateLineSegment(start, end, SegmentType.Full));
if (lineCaps && i == pointsToDraw.Length - 1) {
segments.Add (CreateLineCap (start, end, SegmentType.End));
}
}
}
// Add the line segments to the vertex helper, creating any joins as needed
for (var i = 0; i < segments.Count; i++) {
if (!lineList && i < segments.Count - 1) {
var vec1 = segments [i] [1].position - segments [i] [2].position;
var vec2 = segments [i + 1] [2].position - segments [i + 1] [1].position;
var angle = Vector2.Angle (vec1, vec2) * Mathf.Deg2Rad;
// Positive sign means the line is turning in a 'clockwise' direction
var sign = Mathf.Sign (Vector3.Cross (vec1.normalized, vec2.normalized).z);
// Calculate the miter point
var miterDistance = lineThickness / (2 * Mathf.Tan (angle / 2));
var miterPointA = segments [i] [2].position - vec1.normalized * miterDistance * sign;
var miterPointB = segments [i] [3].position + vec1.normalized * miterDistance * sign;
var joinType = LineJoins;
if (joinType == JoinType.Miter) {
// Make sure we can make a miter join without too many artifacts.
if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_MITER_JOIN) {
segments [i] [2].position = miterPointA;
segments [i] [3].position = miterPointB;
segments [i + 1] [0].position = miterPointB;
segments [i + 1] [1].position = miterPointA;
} else {
joinType = JoinType.Bevel;
}
}
if (joinType == JoinType.Bevel) {
if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_BEVEL_NICE_JOIN) {
if (sign < 0) {
segments [i] [2].position = miterPointA;
segments [i + 1] [1].position = miterPointA;
} else {
segments [i] [3].position = miterPointB;
segments [i + 1] [0].position = miterPointB;
}
}
var join = new UIVertex[] { segments [i] [2], segments [i] [3], segments [i + 1] [0], segments [i + 1] [1] };
vh.AddUIVertexQuad (join);
}
}
vh.AddUIVertexQuad (segments [i]);
}
if (vh.currentVertCount > 64000) {
Debug.LogError ("Max Verticies size is 64000, current mesh vertcies count is [" + vh.currentVertCount + "] - Cannot Draw");
vh.Clear ();
return;
}
}
protected override void OnPopulateMesh(VertexHelper vh)
{
if (m_points != null && m_points.Length > 0) {
GeneratedUVs ();
vh.Clear ();
PopulateMesh (vh, m_points);
}
else if (m_segments != null && m_segments.Count > 0) {
GeneratedUVs ();
vh.Clear ();
for (int s = 0; s < m_segments.Count; s++) {
Vector2[] pointsToDraw = m_segments [s];
PopulateMesh (vh, pointsToDraw);
}
}
}
private UIVertex[] CreateLineCap(Vector2 start, Vector2 end, SegmentType type)
{
if (type == SegmentType.Start)
{
var capStart = start - ((end - start).normalized * lineThickness / 2);
return CreateLineSegment(capStart, start, SegmentType.Start);
}
else if (type == SegmentType.End)
{
var capEnd = end + ((end - start).normalized * lineThickness / 2);
return CreateLineSegment(end, capEnd, SegmentType.End);
}
Debug.LogError("Bad SegmentType passed in to CreateLineCap. Must be SegmentType.Start or SegmentType.End");
return null;
}
private UIVertex[] CreateLineSegment(Vector2 start, Vector2 end, SegmentType type)
{
Vector2 offset = new Vector2((start.y - end.y), end.x - start.x).normalized * lineThickness / 2;
var v1 = start - offset;
var v2 = start + offset;
var v3 = end + offset;
var v4 = end - offset;
//Return the VDO with the correct uvs
switch (type)
{
case SegmentType.Start:
return SetVbo(new[] { v1, v2, v3, v4 }, startUvs);
case SegmentType.End:
return SetVbo(new[] { v1, v2, v3, v4 }, endUvs);
case SegmentType.Full:
return SetVbo(new[] { v1, v2, v3, v4 }, fullUvs);
default:
return SetVbo(new[] { v1, v2, v3, v4 }, middleUvs);
}
}
protected override void GeneratedUVs()
{
if (activeSprite != null)
{
var outer = Sprites.DataUtility.GetOuterUV(activeSprite);
var inner = Sprites.DataUtility.GetInnerUV(activeSprite);
UV_TOP_LEFT = new Vector2(outer.x, outer.y);
UV_BOTTOM_LEFT = new Vector2(outer.x, outer.w);
UV_TOP_CENTER_LEFT = new Vector2(inner.x, inner.y);
UV_TOP_CENTER_RIGHT = new Vector2(inner.z, inner.y);
UV_BOTTOM_CENTER_LEFT = new Vector2(inner.x, inner.w);
UV_BOTTOM_CENTER_RIGHT = new Vector2(inner.z, inner.w);
UV_TOP_RIGHT = new Vector2(outer.z, outer.y);
UV_BOTTOM_RIGHT = new Vector2(outer.z, outer.w);
}
else
{
UV_TOP_LEFT = Vector2.zero;
UV_BOTTOM_LEFT = new Vector2(0, 1);
UV_TOP_CENTER_LEFT = new Vector2(0.5f, 0);
UV_TOP_CENTER_RIGHT = new Vector2(0.5f, 0);
UV_BOTTOM_CENTER_LEFT = new Vector2(0.5f, 1);
UV_BOTTOM_CENTER_RIGHT = new Vector2(0.5f, 1);
UV_TOP_RIGHT = new Vector2(1, 0);
UV_BOTTOM_RIGHT = Vector2.one;
}
startUvs = new[] { UV_TOP_LEFT, UV_BOTTOM_LEFT, UV_BOTTOM_CENTER_LEFT, UV_TOP_CENTER_LEFT };
middleUvs = new[] { UV_TOP_CENTER_LEFT, UV_BOTTOM_CENTER_LEFT, UV_BOTTOM_CENTER_RIGHT, UV_TOP_CENTER_RIGHT };
endUvs = new[] { UV_TOP_CENTER_RIGHT, UV_BOTTOM_CENTER_RIGHT, UV_BOTTOM_RIGHT, UV_TOP_RIGHT };
fullUvs = new[] { UV_TOP_LEFT, UV_BOTTOM_LEFT, UV_BOTTOM_RIGHT, UV_TOP_RIGHT };
}
protected override void ResolutionToNativeSize(float distance)
{
if (UseNativeSize)
{
m_Resolution = distance / (activeSprite.rect.width / pixelsPerUnit);
lineThickness = activeSprite.rect.height / pixelsPerUnit;
}
}
}
}
| |
using System;
namespace Cocos2D
{
public class CCMenuItemSprite : CCMenuItem
{
protected float m_fOriginalScale;
private CCNode m_pDisabledImage;
private CCNode m_pNormalImage;
private CCNode m_pSelectedImage;
public CCNode NormalImage
{
get { return m_pNormalImage; }
set
{
if (value != null)
{
AddChild(value);
value.AnchorPoint = new CCPoint(0, 0);
ContentSize = value.ContentSize;
}
if (m_pNormalImage != null)
{
RemoveChild(m_pNormalImage, true);
}
m_pNormalImage = value;
UpdateImagesVisibility();
}
}
public CCNode SelectedImage
{
get { return m_pSelectedImage; }
set
{
if (value != null)
{
AddChild(value);
value.AnchorPoint = new CCPoint(0, 0);
}
if (m_pSelectedImage != null)
{
RemoveChild(m_pSelectedImage, true);
}
m_pSelectedImage = value;
UpdateImagesVisibility();
}
}
public CCNode DisabledImage
{
get { return m_pDisabledImage; }
set
{
if (value != null)
{
AddChild(value);
value.AnchorPoint = new CCPoint(0, 0);
}
if (m_pDisabledImage != null)
{
RemoveChild(m_pDisabledImage, true);
}
m_pDisabledImage = value;
UpdateImagesVisibility();
}
}
public override bool Enabled
{
get { return base.Enabled; }
set
{
base.Enabled = value;
UpdateImagesVisibility();
}
}
public CCMenuItemSprite()
: this(null, null, null, null)
{
ZoomBehaviorOnTouch = false;
}
public CCMenuItemSprite(Action<object> selector)
: base(selector)
{
}
public CCMenuItemSprite(string normalSprite, string selectedSprite, Action<object> selector)
:this(new CCSprite(normalSprite), new CCSprite(selectedSprite), null, selector)
{
}
public CCMenuItemSprite(CCNode normalSprite, CCNode selectedSprite)
:this(normalSprite, selectedSprite, null, null)
{
}
public CCMenuItemSprite(CCNode normalSprite, CCNode selectedSprite, Action<object> selector)
:this(normalSprite, selectedSprite, null, selector)
{
}
public CCMenuItemSprite(CCNode normalSprite, CCNode selectedSprite, CCNode disabledSprite, Action<object> selector)
{
InitWithTarget(selector);
NormalImage = normalSprite;
SelectedImage = selectedSprite;
DisabledImage = disabledSprite;
if (m_pNormalImage != null)
{
ContentSize = m_pNormalImage.ContentSize;
}
CascadeColorEnabled = true;
CascadeOpacityEnabled = true;
}
/// <summary>
/// Set this to true if you want to zoom-in/out on the button image like the CCMenuItemLabel works.
/// </summary>
public bool ZoomBehaviorOnTouch { get; set; }
public override void Selected()
{
base.Selected();
if (m_pNormalImage != null)
{
if (m_pDisabledImage != null)
{
m_pDisabledImage.Visible = false;
}
if (m_pSelectedImage != null)
{
m_pNormalImage.Visible = false;
m_pSelectedImage.Visible = true;
}
else
{
m_pNormalImage.Visible = true;
if (ZoomBehaviorOnTouch)
{
CCAction action = GetActionByTag(unchecked((int)kZoomActionTag));
if (action != null)
{
StopAction(action);
}
else
{
m_fOriginalScale = Scale;
}
CCAction zoomAction = new CCScaleTo(0.1f, m_fOriginalScale * 1.2f);
zoomAction.Tag = unchecked((int)kZoomActionTag);
RunAction(zoomAction);
}
}
}
}
public override void Unselected()
{
base.Unselected();
if (m_pNormalImage != null)
{
m_pNormalImage.Visible = true;
if (m_pSelectedImage != null)
{
m_pSelectedImage.Visible = false;
if (ZoomBehaviorOnTouch)
{
StopActionByTag(unchecked((int)kZoomActionTag));
CCAction zoomAction = new CCScaleTo(0.1f, m_fOriginalScale);
zoomAction.Tag = unchecked((int)kZoomActionTag);
RunAction(zoomAction);
}
}
if (m_pDisabledImage != null)
{
m_pDisabledImage.Visible = false;
}
}
}
public override void Activate()
{
if (m_bIsEnabled)
{
if (ZoomBehaviorOnTouch)
{
StopAllActions();
Scale = m_fOriginalScale;
}
base.Activate();
}
}
// Helper
private void UpdateImagesVisibility()
{
if (m_bIsEnabled)
{
if (m_pNormalImage != null) m_pNormalImage.Visible = true;
if (m_pSelectedImage != null) m_pSelectedImage.Visible = false;
if (m_pDisabledImage != null) m_pDisabledImage.Visible = false;
}
else
{
if (m_pDisabledImage != null)
{
if (m_pNormalImage != null) m_pNormalImage.Visible = false;
if (m_pSelectedImage != null) m_pSelectedImage.Visible = false;
if (m_pDisabledImage != null) m_pDisabledImage.Visible = true;
}
else
{
if (m_pNormalImage != null) m_pNormalImage.Visible = true;
if (m_pSelectedImage != null) m_pSelectedImage.Visible = false;
if (m_pDisabledImage != null) m_pDisabledImage.Visible = false;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace docdbwebservice.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if FEATURE_REGISTRY
using Microsoft.Win32;
#endif
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Threading;
namespace System.Diagnostics
{
internal sealed class PerformanceCounterLib
{
private static string s_computerName;
private PerformanceMonitor _performanceMonitor;
private string _machineName;
private string _perfLcid;
private static ConcurrentDictionary<(string machineName, string lcidString), PerformanceCounterLib> s_libraryTable;
private Dictionary<int, string> _nameTable;
private readonly object _nameTableLock = new Object();
private static Object s_internalSyncObject;
internal PerformanceCounterLib(string machineName, string lcid)
{
_machineName = machineName;
_perfLcid = lcid;
}
/// <internalonly/>
internal static string ComputerName => LazyInitializer.EnsureInitialized(ref s_computerName, ref s_internalSyncObject, () => Interop.Kernel32.GetComputerName());
internal Dictionary<int, string> NameTable
{
get
{
if (_nameTable == null)
{
lock (_nameTableLock)
{
if (_nameTable == null)
_nameTable = GetStringTable(false);
}
}
return _nameTable;
}
}
internal string GetCounterName(int index)
{
string result;
return NameTable.TryGetValue(index, out result) ? result : "";
}
internal static PerformanceCounterLib GetPerformanceCounterLib(string machineName, CultureInfo culture)
{
string lcidString = culture.Name.ToLowerInvariant();
if (machineName.CompareTo(".") == 0)
machineName = ComputerName.ToLowerInvariant();
else
machineName = machineName.ToLowerInvariant();
LazyInitializer.EnsureInitialized(ref s_libraryTable, ref s_internalSyncObject, () => new ConcurrentDictionary<(string, string), PerformanceCounterLib>());
return PerformanceCounterLib.s_libraryTable.GetOrAdd((machineName, lcidString), (key) => new PerformanceCounterLib(key.machineName, key.lcidString));
}
internal byte[] GetPerformanceData(string item)
{
if (_performanceMonitor == null)
{
lock (LazyInitializer.EnsureInitialized(ref s_internalSyncObject))
{
if (_performanceMonitor == null)
_performanceMonitor = new PerformanceMonitor(_machineName);
}
}
return _performanceMonitor.GetData(item);
}
private Dictionary<int, string> GetStringTable(bool isHelp)
{
#if FEATURE_REGISTRY
Dictionary<int, string> stringTable;
RegistryKey libraryKey;
libraryKey = Registry.PerformanceData;
try
{
string[] names = null;
int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins
int waitSleep = 0;
// In some stress situations, querying counter values from
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009
// often returns null/empty data back. We should build fault-tolerance logic to
// make it more reliable because getting null back once doesn't necessarily mean
// that the data is corrupted, most of the time we would get the data just fine
// in subsequent tries.
while (waitRetries > 0)
{
try
{
if (!isHelp)
names = (string[])libraryKey.GetValue("Counter " + _perfLcid);
else
names = (string[])libraryKey.GetValue("Explain " + _perfLcid);
if ((names == null) || (names.Length == 0))
{
--waitRetries;
if (waitSleep == 0)
waitSleep = 10;
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
}
else
break;
}
catch (IOException)
{
// RegistryKey throws if it can't find the value. We want to return an empty table
// and throw a different exception higher up the stack.
names = null;
break;
}
catch (InvalidCastException)
{
// Unable to cast object of type 'System.Byte[]' to type 'System.String[]'.
// this happens when the registry data store is corrupt and the type is not even REG_MULTI_SZ
names = null;
break;
}
}
if (names == null)
stringTable = new Dictionary<int, string>();
else
{
stringTable = new Dictionary<int, string>(names.Length / 2);
for (int index = 0; index < (names.Length / 2); ++index)
{
string nameString = names[(index * 2) + 1];
if (nameString == null)
nameString = String.Empty;
int key;
if (!Int32.TryParse(names[index * 2], NumberStyles.Integer, CultureInfo.InvariantCulture, out key))
{
if (isHelp)
{
// Category Help Table
throw new InvalidOperationException(SR.Format(SR.CategoryHelpCorrupt, names[index * 2]));
}
else
{
// Counter Name Table
throw new InvalidOperationException(SR.Format(SR.CounterNameCorrupt, names[index * 2]));
}
}
stringTable[key] = nameString;
}
}
}
finally
{
libraryKey.Dispose();
}
return stringTable;
#else
return new Dictionary<int, string>();
#endif
}
internal class PerformanceMonitor
{
#if FEATURE_REGISTRY
private RegistryKey _perfDataKey = null;
#endif
private string _machineName;
internal PerformanceMonitor(string machineName)
{
_machineName = machineName;
Init();
}
private void Init()
{
#if FEATURE_REGISTRY
if (ProcessManager.IsRemoteMachine(_machineName))
{
_perfDataKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.PerformanceData, _machineName);
}
else
{
_perfDataKey = Registry.PerformanceData;
}
#endif
}
// Win32 RegQueryValueEx for perf data could deadlock (for a Mutex) up to 2mins in some
// scenarios before they detect it and exit gracefully. In the mean time, ERROR_BUSY,
// ERROR_NOT_READY etc can be seen by other concurrent calls (which is the reason for the
// wait loop and switch case below). We want to wait most certainly more than a 2min window.
// The current wait time of up to 10mins takes care of the known stress deadlock issues. In most
// cases we wouldn't wait for more than 2mins anyways but in worst cases how much ever time
// we wait may not be sufficient if the Win32 code keeps running into this deadlock again
// and again. A condition very rare but possible in theory. We would get back to the user
// in this case with InvalidOperationException after the wait time expires.
internal byte[] GetData(string item)
{
#if FEATURE_REGISTRY
int waitRetries = 17; //2^16*10ms == approximately 10mins
int waitSleep = 0;
byte[] data = null;
int error = 0;
while (waitRetries > 0)
{
try
{
data = (byte[])_perfDataKey.GetValue(item);
return data;
}
catch (IOException e)
{
error = e.HResult;
switch (error)
{
case Interop.Advapi32.RPCStatus.RPC_S_CALL_FAILED:
case Interop.Errors.ERROR_INVALID_HANDLE:
case Interop.Advapi32.RPCStatus.RPC_S_SERVER_UNAVAILABLE:
Init();
goto case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT;
case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT:
case Interop.Errors.ERROR_NOT_READY:
case Interop.Errors.ERROR_LOCK_FAILED:
case Interop.Errors.ERROR_BUSY:
--waitRetries;
if (waitSleep == 0)
{
waitSleep = 10;
}
else
{
System.Threading.Thread.Sleep(waitSleep);
waitSleep *= 2;
}
break;
default:
throw new Win32Exception(error);
}
}
catch (InvalidCastException e)
{
throw new InvalidOperationException(SR.Format(SR.CounterDataCorrupt, _perfDataKey.ToString()), e);
}
}
throw new Win32Exception(error);
#else
return Array.Empty<byte>();
#endif
}
}
}
}
| |
// Licensed to the Apache Software Foundation(ASF) under one
// or more contributor license agreements.See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Thrift.Protocol.Entities;
using Thrift.Transport;
namespace Thrift.Protocol
{
// ReSharper disable once InconsistentNaming
public abstract class TProtocol : IDisposable
{
public const int DefaultRecursionDepth = 64;
private bool _isDisposed;
protected int RecursionDepth;
protected TTransport Trans;
protected TProtocol(TTransport trans)
{
Trans = trans;
RecursionLimit = DefaultRecursionDepth;
RecursionDepth = 0;
}
public TTransport Transport => Trans;
protected int RecursionLimit { get; set; }
public void Dispose()
{
Dispose(true);
}
public void IncrementRecursionDepth()
{
if (RecursionDepth < RecursionLimit)
{
++RecursionDepth;
}
else
{
throw new TProtocolException(TProtocolException.DEPTH_LIMIT, "Depth limit exceeded");
}
}
public void DecrementRecursionDepth()
{
--RecursionDepth;
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
(Trans as IDisposable)?.Dispose();
}
}
_isDisposed = true;
}
public virtual async Task WriteMessageBeginAsync(TMessage message)
{
await WriteMessageBeginAsync(message, CancellationToken.None);
}
public abstract Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken);
public virtual async Task WriteMessageEndAsync()
{
await WriteMessageEndAsync(CancellationToken.None);
}
public abstract Task WriteMessageEndAsync(CancellationToken cancellationToken);
public virtual async Task WriteStructBeginAsync(TStruct @struct)
{
await WriteStructBeginAsync(@struct, CancellationToken.None);
}
public abstract Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken);
public virtual async Task WriteStructEndAsync()
{
await WriteStructEndAsync(CancellationToken.None);
}
public abstract Task WriteStructEndAsync(CancellationToken cancellationToken);
public virtual async Task WriteFieldBeginAsync(TField field)
{
await WriteFieldBeginAsync(field, CancellationToken.None);
}
public abstract Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken);
public virtual async Task WriteFieldEndAsync()
{
await WriteFieldEndAsync(CancellationToken.None);
}
public abstract Task WriteFieldEndAsync(CancellationToken cancellationToken);
public virtual async Task WriteFieldStopAsync()
{
await WriteFieldStopAsync(CancellationToken.None);
}
public abstract Task WriteFieldStopAsync(CancellationToken cancellationToken);
public virtual async Task WriteMapBeginAsync(TMap map)
{
await WriteMapBeginAsync(map, CancellationToken.None);
}
public abstract Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken);
public virtual async Task WriteMapEndAsync()
{
await WriteMapEndAsync(CancellationToken.None);
}
public abstract Task WriteMapEndAsync(CancellationToken cancellationToken);
public virtual async Task WriteListBeginAsync(TList list)
{
await WriteListBeginAsync(list, CancellationToken.None);
}
public abstract Task WriteListBeginAsync(TList list, CancellationToken cancellationToken);
public virtual async Task WriteListEndAsync()
{
await WriteListEndAsync(CancellationToken.None);
}
public abstract Task WriteListEndAsync(CancellationToken cancellationToken);
public virtual async Task WriteSetBeginAsync(TSet set)
{
await WriteSetBeginAsync(set, CancellationToken.None);
}
public abstract Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken);
public virtual async Task WriteSetEndAsync()
{
await WriteSetEndAsync(CancellationToken.None);
}
public abstract Task WriteSetEndAsync(CancellationToken cancellationToken);
public virtual async Task WriteBoolAsync(bool b)
{
await WriteBoolAsync(b, CancellationToken.None);
}
public abstract Task WriteBoolAsync(bool b, CancellationToken cancellationToken);
public virtual async Task WriteByteAsync(sbyte b)
{
await WriteByteAsync(b, CancellationToken.None);
}
public abstract Task WriteByteAsync(sbyte b, CancellationToken cancellationToken);
public virtual async Task WriteI16Async(short i16)
{
await WriteI16Async(i16, CancellationToken.None);
}
public abstract Task WriteI16Async(short i16, CancellationToken cancellationToken);
public virtual async Task WriteI32Async(int i32)
{
await WriteI32Async(i32, CancellationToken.None);
}
public abstract Task WriteI32Async(int i32, CancellationToken cancellationToken);
public virtual async Task WriteI64Async(long i64)
{
await WriteI64Async(i64, CancellationToken.None);
}
public abstract Task WriteI64Async(long i64, CancellationToken cancellationToken);
public virtual async Task WriteDoubleAsync(double d)
{
await WriteDoubleAsync(d, CancellationToken.None);
}
public abstract Task WriteDoubleAsync(double d, CancellationToken cancellationToken);
public virtual async Task WriteStringAsync(string s)
{
await WriteStringAsync(s, CancellationToken.None);
}
public virtual async Task WriteStringAsync(string s, CancellationToken cancellationToken)
{
var bytes = Encoding.UTF8.GetBytes(s);
await WriteBinaryAsync(bytes, cancellationToken);
}
public virtual async Task WriteBinaryAsync(byte[] bytes)
{
await WriteBinaryAsync(bytes, CancellationToken.None);
}
public abstract Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken);
public virtual async ValueTask<TMessage> ReadMessageBeginAsync()
{
return await ReadMessageBeginAsync(CancellationToken.None);
}
public abstract ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken);
public virtual async Task ReadMessageEndAsync()
{
await ReadMessageEndAsync(CancellationToken.None);
}
public abstract Task ReadMessageEndAsync(CancellationToken cancellationToken);
public virtual async ValueTask<TStruct> ReadStructBeginAsync()
{
return await ReadStructBeginAsync(CancellationToken.None);
}
public abstract ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken);
public virtual async Task ReadStructEndAsync()
{
await ReadStructEndAsync(CancellationToken.None);
}
public abstract Task ReadStructEndAsync(CancellationToken cancellationToken);
public virtual async ValueTask<TField> ReadFieldBeginAsync()
{
return await ReadFieldBeginAsync(CancellationToken.None);
}
public abstract ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken);
public virtual async Task ReadFieldEndAsync()
{
await ReadFieldEndAsync(CancellationToken.None);
}
public abstract Task ReadFieldEndAsync(CancellationToken cancellationToken);
public virtual async ValueTask<TMap> ReadMapBeginAsync()
{
return await ReadMapBeginAsync(CancellationToken.None);
}
public abstract ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken);
public virtual async Task ReadMapEndAsync()
{
await ReadMapEndAsync(CancellationToken.None);
}
public abstract Task ReadMapEndAsync(CancellationToken cancellationToken);
public virtual async ValueTask<TList> ReadListBeginAsync()
{
return await ReadListBeginAsync(CancellationToken.None);
}
public abstract ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken);
public virtual async Task ReadListEndAsync()
{
await ReadListEndAsync(CancellationToken.None);
}
public abstract Task ReadListEndAsync(CancellationToken cancellationToken);
public virtual async ValueTask<TSet> ReadSetBeginAsync()
{
return await ReadSetBeginAsync(CancellationToken.None);
}
public abstract ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken);
public virtual async Task ReadSetEndAsync()
{
await ReadSetEndAsync(CancellationToken.None);
}
public abstract Task ReadSetEndAsync(CancellationToken cancellationToken);
public virtual async ValueTask<bool> ReadBoolAsync()
{
return await ReadBoolAsync(CancellationToken.None);
}
public abstract ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken);
public virtual async ValueTask<sbyte> ReadByteAsync()
{
return await ReadByteAsync(CancellationToken.None);
}
public abstract ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken);
public virtual async ValueTask<short> ReadI16Async()
{
return await ReadI16Async(CancellationToken.None);
}
public abstract ValueTask<short> ReadI16Async(CancellationToken cancellationToken);
public virtual async ValueTask<int> ReadI32Async()
{
return await ReadI32Async(CancellationToken.None);
}
public abstract ValueTask<int> ReadI32Async(CancellationToken cancellationToken);
public virtual async ValueTask<long> ReadI64Async()
{
return await ReadI64Async(CancellationToken.None);
}
public abstract ValueTask<long> ReadI64Async(CancellationToken cancellationToken);
public virtual async ValueTask<double> ReadDoubleAsync()
{
return await ReadDoubleAsync(CancellationToken.None);
}
public abstract ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken);
public virtual async ValueTask<string> ReadStringAsync()
{
return await ReadStringAsync(CancellationToken.None);
}
public virtual async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken)
{
var buf = await ReadBinaryAsync(cancellationToken);
return Encoding.UTF8.GetString(buf, 0, buf.Length);
}
public virtual async ValueTask<byte[]> ReadBinaryAsync()
{
return await ReadBinaryAsync(CancellationToken.None);
}
public abstract ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken);
}
}
| |
namespace Azure.Data.Tables
{
public partial interface ITableEntity
{
Azure.ETag ETag { get; set; }
string PartitionKey { get; set; }
string RowKey { get; set; }
System.DateTimeOffset? Timestamp { get; set; }
}
public partial class TableClient
{
protected TableClient() { }
public TableClient(string connectionString, string tableName) { }
public TableClient(string connectionString, string tableName, Azure.Data.Tables.TableClientOptions options = null) { }
public TableClient(System.Uri endpoint, string tableName, Azure.Data.Tables.TableClientOptions options = null) { }
public TableClient(System.Uri endpoint, string tableName, Azure.Data.Tables.TableSharedKeyCredential credential) { }
public TableClient(System.Uri endpoint, string tableName, Azure.Data.Tables.TableSharedKeyCredential credential, Azure.Data.Tables.TableClientOptions options = null) { }
public virtual System.Threading.Tasks.Task<Azure.Response> AddEntityAsync<T>(T entity, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Response AddEntity<T>(T entity, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Response<Azure.Data.Tables.Models.TableItem> Create(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableItem>> CreateAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Data.Tables.Models.TableItem> CreateIfNotExists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableItem>> CreateIfNotExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static string CreateQueryFilter<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> filter) { throw null; }
public virtual Azure.Data.Tables.TableTransactionalBatch CreateTransactionalBatch(string partitionKey) { throw null; }
public virtual Azure.Response Delete(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteEntity(string partitionKey, string rowKey, Azure.ETag ifMatch = default(Azure.ETag), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteEntityAsync(string partitionKey, string rowKey, Azure.ETag ifMatch = default(Azure.ETag), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Data.Tables.Models.SignedIdentifier>> GetAccessPolicy(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.Data.Tables.Models.SignedIdentifier>>> GetAccessPolicyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<T>> GetEntityAsync<T>(string partitionKey, string rowKey, System.Collections.Generic.IEnumerable<string> select = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Response<T> GetEntity<T>(string partitionKey, string rowKey, System.Collections.Generic.IEnumerable<string> select = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Data.Tables.Sas.TableSasBuilder GetSasBuilder(Azure.Data.Tables.Sas.TableSasPermissions permissions, System.DateTimeOffset expiresOn) { throw null; }
public virtual Azure.Data.Tables.Sas.TableSasBuilder GetSasBuilder(string rawPermissions, System.DateTimeOffset expiresOn) { throw null; }
public virtual Azure.AsyncPageable<T> QueryAsync<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> filter, int? maxPerPage = default(int?), System.Collections.Generic.IEnumerable<string> select = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.AsyncPageable<T> QueryAsync<T>(string filter = null, int? maxPerPage = default(int?), System.Collections.Generic.IEnumerable<string> select = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Pageable<T> Query<T>(System.Linq.Expressions.Expression<System.Func<T, bool>> filter, int? maxPerPage = default(int?), System.Collections.Generic.IEnumerable<string> select = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Pageable<T> Query<T>(string filter = null, int? maxPerPage = default(int?), System.Collections.Generic.IEnumerable<string> select = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Response SetAccessPolicy(System.Collections.Generic.IEnumerable<Azure.Data.Tables.Models.SignedIdentifier> tableAcl, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetAccessPolicyAsync(System.Collections.Generic.IEnumerable<Azure.Data.Tables.Models.SignedIdentifier> tableAcl, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> UpdateEntityAsync<T>(T entity, Azure.ETag ifMatch, Azure.Data.Tables.TableUpdateMode mode = Azure.Data.Tables.TableUpdateMode.Merge, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Response UpdateEntity<T>(T entity, Azure.ETag ifMatch, Azure.Data.Tables.TableUpdateMode mode = Azure.Data.Tables.TableUpdateMode.Merge, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> UpsertEntityAsync<T>(T entity, Azure.Data.Tables.TableUpdateMode mode = Azure.Data.Tables.TableUpdateMode.Merge, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
public virtual Azure.Response UpsertEntity<T>(T entity, Azure.Data.Tables.TableUpdateMode mode = Azure.Data.Tables.TableUpdateMode.Merge, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) where T : class, Azure.Data.Tables.ITableEntity, new() { throw null; }
}
public partial class TableClientOptions : Azure.Core.ClientOptions
{
public TableClientOptions(Azure.Data.Tables.TableClientOptions.ServiceVersion serviceVersion = Azure.Data.Tables.TableClientOptions.ServiceVersion.V2019_02_02) { }
public enum ServiceVersion
{
V2019_02_02 = 1,
}
}
public sealed partial class TableEntity : Azure.Data.Tables.ITableEntity, System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.Generic.IDictionary<string, object>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, object>>, System.Collections.IEnumerable
{
public TableEntity() { }
public TableEntity(System.Collections.Generic.IDictionary<string, object> values) { }
public TableEntity(string partitionKey, string rowKey) { }
public int Count { get { throw null; } }
public Azure.ETag ETag { get { throw null; } set { } }
public object this[string key] { get { throw null; } set { } }
public System.Collections.Generic.ICollection<string> Keys { get { throw null; } }
public string PartitionKey { get { throw null; } set { } }
public string RowKey { get { throw null; } set { } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.IsReadOnly { get { throw null; } }
System.Collections.Generic.ICollection<object> System.Collections.Generic.IDictionary<System.String,System.Object>.Values { get { throw null; } }
public System.DateTimeOffset? Timestamp { get { throw null; } set { } }
public void Add(string key, object value) { }
public void Clear() { }
public bool ContainsKey(string key) { throw null; }
public byte[] GetBinary(string key) { throw null; }
public bool? GetBoolean(string key) { throw null; }
public System.DateTime? GetDateTime(string key) { throw null; }
public System.DateTimeOffset? GetDateTimeOffset(string key) { throw null; }
public double? GetDouble(string key) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<string, object>> GetEnumerator() { throw null; }
public System.Guid? GetGuid(string key) { throw null; }
public int? GetInt32(string key) { throw null; }
public long? GetInt64(string key) { throw null; }
public string GetString(string key) { throw null; }
public bool Remove(string key) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Add(System.Collections.Generic.KeyValuePair<string, object> item) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Contains(System.Collections.Generic.KeyValuePair<string, object> item) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.CopyTo(System.Collections.Generic.KeyValuePair<string, object>[] array, int arrayIndex) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.Remove(System.Collections.Generic.KeyValuePair<string, object> item) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public bool TryGetValue(string key, out object value) { throw null; }
}
public partial class TableServiceClient
{
protected TableServiceClient() { }
public TableServiceClient(string connectionString) { }
public TableServiceClient(string connectionString, Azure.Data.Tables.TableClientOptions options = null) { }
public TableServiceClient(System.Uri endpoint) { }
public TableServiceClient(System.Uri endpoint, Azure.Data.Tables.TableClientOptions options = null) { }
public TableServiceClient(System.Uri endpoint, Azure.Data.Tables.TableSharedKeyCredential credential) { }
public TableServiceClient(System.Uri endpoint, Azure.Data.Tables.TableSharedKeyCredential credential, Azure.Data.Tables.TableClientOptions options = null) { }
public virtual Azure.Response<Azure.Data.Tables.Models.TableItem> CreateTable(string tableName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableItem>> CreateTableAsync(string tableName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Data.Tables.Models.TableItem> CreateTableIfNotExists(string tableName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableItem>> CreateTableIfNotExistsAsync(string tableName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response DeleteTable(string tableName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> DeleteTableAsync(string tableName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response<Azure.Data.Tables.Models.TableServiceProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableServiceProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Data.Tables.Sas.TableAccountSasBuilder GetSasBuilder(Azure.Data.Tables.Sas.TableAccountSasPermissions permissions, Azure.Data.Tables.Sas.TableAccountSasResourceTypes resourceTypes, System.DateTimeOffset expiresOn) { throw null; }
public virtual Azure.Data.Tables.Sas.TableAccountSasBuilder GetSasBuilder(string rawPermissions, Azure.Data.Tables.Sas.TableAccountSasResourceTypes resourceTypes, System.DateTimeOffset expiresOn) { throw null; }
public virtual Azure.Response<Azure.Data.Tables.Models.TableServiceStatistics> GetStatistics(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableServiceStatistics>> GetStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Data.Tables.TableClient GetTableClient(string tableName) { throw null; }
public virtual Azure.Pageable<Azure.Data.Tables.Models.TableItem> GetTables(string filter = null, int? maxPerPage = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.AsyncPageable<Azure.Data.Tables.Models.TableItem> GetTablesAsync(string filter = null, int? maxPerPage = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual Azure.Response SetProperties(Azure.Data.Tables.Models.TableServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response> SetPropertiesAsync(Azure.Data.Tables.Models.TableServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
}
public partial class TableSharedKeyCredential
{
public TableSharedKeyCredential(string accountName, string accountKey) { }
public string AccountName { get { throw null; } }
public void SetAccountKey(string accountKey) { }
}
public static partial class TablesModelFactory
{
public static Azure.Data.Tables.Models.TableItem TableItem(string tableName, string odataType, string odataId, string odataEditLink) { throw null; }
}
public partial class TableTransactionalBatch
{
protected TableTransactionalBatch() { }
public virtual void AddEntities<T>(System.Collections.Generic.IEnumerable<T> entities) where T : class, Azure.Data.Tables.ITableEntity, new() { }
public virtual void AddEntity<T>(T entity) where T : class, Azure.Data.Tables.ITableEntity, new() { }
public virtual void DeleteEntity(string rowKey, Azure.ETag ifMatch = default(Azure.ETag)) { }
public virtual Azure.Response<Azure.Data.Tables.Models.TableBatchResponse> SubmitBatch(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Data.Tables.Models.TableBatchResponse>> SubmitBatchAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public virtual bool TryGetFailedEntityFromException(Azure.RequestFailedException exception, out Azure.Data.Tables.ITableEntity failedEntity) { throw null; }
public virtual void UpdateEntity<T>(T entity, Azure.ETag ifMatch, Azure.Data.Tables.TableUpdateMode mode = Azure.Data.Tables.TableUpdateMode.Merge) where T : class, Azure.Data.Tables.ITableEntity, new() { }
public virtual void UpsertEntity<T>(T entity, Azure.Data.Tables.TableUpdateMode mode = Azure.Data.Tables.TableUpdateMode.Merge) where T : class, Azure.Data.Tables.ITableEntity, new() { }
}
public enum TableUpdateMode
{
Merge = 0,
Replace = 1,
}
}
namespace Azure.Data.Tables.Models
{
public partial class RetentionPolicy
{
public RetentionPolicy(bool enabled) { }
public int? Days { get { throw null; } set { } }
public bool Enabled { get { throw null; } set { } }
}
public partial class SignedIdentifier
{
public SignedIdentifier(string id, Azure.Data.Tables.Models.TableAccessPolicy accessPolicy) { }
public Azure.Data.Tables.Models.TableAccessPolicy AccessPolicy { get { throw null; } set { } }
public string Id { get { throw null; } set { } }
}
public partial class TableAccessPolicy
{
public TableAccessPolicy(System.DateTimeOffset startsOn, System.DateTimeOffset expiresOn, string permission) { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
public string Permission { get { throw null; } set { } }
public System.DateTimeOffset StartsOn { get { throw null; } set { } }
}
public partial class TableAnalyticsLoggingSettings
{
public TableAnalyticsLoggingSettings(string version, bool delete, bool read, bool write, Azure.Data.Tables.Models.RetentionPolicy retentionPolicy) { }
public bool Delete { get { throw null; } set { } }
public bool Read { get { throw null; } set { } }
public Azure.Data.Tables.Models.RetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
public bool Write { get { throw null; } set { } }
}
public partial class TableBatchResponse
{
internal TableBatchResponse() { }
public int ResponseCount { get { throw null; } }
public Azure.Response GetResponseForEntity(string rowKey) { throw null; }
}
public partial class TableCorsRule
{
public TableCorsRule(string allowedOrigins, string allowedMethods, string allowedHeaders, string exposedHeaders, int maxAgeInSeconds) { }
public string AllowedHeaders { get { throw null; } set { } }
public string AllowedMethods { get { throw null; } set { } }
public string AllowedOrigins { get { throw null; } set { } }
public string ExposedHeaders { get { throw null; } set { } }
public int MaxAgeInSeconds { get { throw null; } set { } }
}
public partial class TableGeoReplicationInfo
{
internal TableGeoReplicationInfo() { }
public System.DateTimeOffset LastSyncedOn { get { throw null; } }
public Azure.Data.Tables.Models.TableGeoReplicationStatus Status { get { throw null; } }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct TableGeoReplicationStatus : System.IEquatable<Azure.Data.Tables.Models.TableGeoReplicationStatus>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public TableGeoReplicationStatus(string value) { throw null; }
public static Azure.Data.Tables.Models.TableGeoReplicationStatus Bootstrap { get { throw null; } }
public static Azure.Data.Tables.Models.TableGeoReplicationStatus Live { get { throw null; } }
public static Azure.Data.Tables.Models.TableGeoReplicationStatus Unavailable { get { throw null; } }
public bool Equals(Azure.Data.Tables.Models.TableGeoReplicationStatus other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Data.Tables.Models.TableGeoReplicationStatus left, Azure.Data.Tables.Models.TableGeoReplicationStatus right) { throw null; }
public static implicit operator Azure.Data.Tables.Models.TableGeoReplicationStatus (string value) { throw null; }
public static bool operator !=(Azure.Data.Tables.Models.TableGeoReplicationStatus left, Azure.Data.Tables.Models.TableGeoReplicationStatus right) { throw null; }
public override string ToString() { throw null; }
}
public partial class TableItem
{
internal TableItem() { }
public string TableName { get { throw null; } }
}
public partial class TableMetrics
{
public TableMetrics(bool enabled) { }
public bool Enabled { get { throw null; } set { } }
public bool? IncludeApis { get { throw null; } set { } }
public Azure.Data.Tables.Models.RetentionPolicy RetentionPolicy { get { throw null; } set { } }
public string Version { get { throw null; } set { } }
}
public partial class TableServiceProperties
{
public TableServiceProperties() { }
public System.Collections.Generic.IList<Azure.Data.Tables.Models.TableCorsRule> Cors { get { throw null; } }
public Azure.Data.Tables.Models.TableMetrics HourMetrics { get { throw null; } set { } }
public Azure.Data.Tables.Models.TableAnalyticsLoggingSettings Logging { get { throw null; } set { } }
public Azure.Data.Tables.Models.TableMetrics MinuteMetrics { get { throw null; } set { } }
}
public partial class TableServiceStatistics
{
internal TableServiceStatistics() { }
public Azure.Data.Tables.Models.TableGeoReplicationInfo GeoReplication { get { throw null; } }
}
}
namespace Azure.Data.Tables.Sas
{
public partial class TableAccountSasBuilder
{
public TableAccountSasBuilder(Azure.Data.Tables.Sas.TableAccountSasPermissions permissions, Azure.Data.Tables.Sas.TableAccountSasResourceTypes resourceTypes, System.DateTimeOffset expiresOn) { }
public TableAccountSasBuilder(string rawPermissions, Azure.Data.Tables.Sas.TableAccountSasResourceTypes resourceTypes, System.DateTimeOffset expiresOn) { }
public TableAccountSasBuilder(System.Uri uri) { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
public string Identifier { get { throw null; } set { } }
public Azure.Data.Tables.Sas.TableSasIPRange IPRange { get { throw null; } set { } }
public string Permissions { get { throw null; } }
public Azure.Data.Tables.Sas.TableSasProtocol Protocol { get { throw null; } set { } }
public Azure.Data.Tables.Sas.TableAccountSasResourceTypes ResourceTypes { get { throw null; } set { } }
public System.DateTimeOffset StartsOn { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public void SetPermissions(Azure.Data.Tables.Sas.TableAccountSasPermissions permissions) { }
public void SetPermissions(string rawPermissions) { }
public string Sign(Azure.Data.Tables.TableSharedKeyCredential sharedKeyCredential) { throw null; }
public Azure.Data.Tables.Sas.TableAccountSasQueryParameters ToSasQueryParameters(Azure.Data.Tables.TableSharedKeyCredential sharedKeyCredential) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum TableAccountSasPermissions
{
All = -1,
Read = 1,
Write = 2,
Delete = 4,
List = 8,
Add = 16,
Update = 64,
}
public partial class TableAccountSasQueryParameters
{
internal TableAccountSasQueryParameters() { }
public System.DateTimeOffset ExpiresOn { get { throw null; } }
public string Identifier { get { throw null; } }
public Azure.Data.Tables.Sas.TableSasIPRange IPRange { get { throw null; } }
public string Permissions { get { throw null; } }
public Azure.Data.Tables.Sas.TableSasProtocol Protocol { get { throw null; } }
public string Resource { get { throw null; } }
public Azure.Data.Tables.Sas.TableAccountSasResourceTypes? ResourceTypes { get { throw null; } }
public string Signature { get { throw null; } }
public System.DateTimeOffset StartsOn { get { throw null; } }
public string Version { get { throw null; } }
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum TableAccountSasResourceTypes
{
All = -1,
Service = 1,
Container = 2,
Object = 4,
}
public partial class TableSasBuilder
{
public TableSasBuilder(string tableName, Azure.Data.Tables.Sas.TableSasPermissions permissions, System.DateTimeOffset expiresOn) { }
public TableSasBuilder(string tableName, string rawPermissions, System.DateTimeOffset expiresOn) { }
public TableSasBuilder(System.Uri uri) { }
public System.DateTimeOffset ExpiresOn { get { throw null; } set { } }
public string Identifier { get { throw null; } set { } }
public Azure.Data.Tables.Sas.TableSasIPRange IPRange { get { throw null; } set { } }
public string PartitionKeyEnd { get { throw null; } set { } }
public string PartitionKeyStart { get { throw null; } set { } }
public string Permissions { get { throw null; } }
public Azure.Data.Tables.Sas.TableSasProtocol Protocol { get { throw null; } set { } }
public string RowKeyEnd { get { throw null; } set { } }
public string RowKeyStart { get { throw null; } set { } }
public System.DateTimeOffset StartsOn { get { throw null; } set { } }
public string TableName { get { throw null; } set { } }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public void SetPermissions(Azure.Data.Tables.Sas.TableSasPermissions permissions) { }
public void SetPermissions(string rawPermissions) { }
public string Sign(Azure.Data.Tables.TableSharedKeyCredential sharedKeyCredential) { throw null; }
public Azure.Data.Tables.Sas.TableSasQueryParameters ToSasQueryParameters(Azure.Data.Tables.TableSharedKeyCredential sharedKeyCredential) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override string ToString() { throw null; }
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public readonly partial struct TableSasIPRange : System.IEquatable<Azure.Data.Tables.Sas.TableSasIPRange>
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public TableSasIPRange(System.Net.IPAddress start, System.Net.IPAddress end = null) { throw null; }
public System.Net.IPAddress End { get { throw null; } }
public System.Net.IPAddress Start { get { throw null; } }
public bool Equals(Azure.Data.Tables.Sas.TableSasIPRange other) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override bool Equals(object obj) { throw null; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public override int GetHashCode() { throw null; }
public static bool operator ==(Azure.Data.Tables.Sas.TableSasIPRange left, Azure.Data.Tables.Sas.TableSasIPRange right) { throw null; }
public static bool operator !=(Azure.Data.Tables.Sas.TableSasIPRange left, Azure.Data.Tables.Sas.TableSasIPRange right) { throw null; }
public static Azure.Data.Tables.Sas.TableSasIPRange Parse(string s) { throw null; }
public override string ToString() { throw null; }
}
[System.FlagsAttribute]
public enum TableSasPermissions
{
All = -1,
Read = 1,
Add = 2,
Update = 4,
Delete = 8,
}
public enum TableSasProtocol
{
None = 0,
HttpsAndHttp = 1,
Https = 2,
}
public sealed partial class TableSasQueryParameters : Azure.Data.Tables.Sas.TableAccountSasQueryParameters
{
internal TableSasQueryParameters() { }
public static Azure.Data.Tables.Sas.TableSasQueryParameters Empty { get { throw null; } }
public string EndPartitionKey { get { throw null; } set { } }
public string EndRowKey { get { throw null; } set { } }
public string StartPartitionKey { get { throw null; } set { } }
public string StartRowKey { get { throw null; } set { } }
public override string ToString() { throw null; }
}
public partial class TableUriBuilder
{
public TableUriBuilder(System.Uri uri) { }
public string AccountName { get { throw null; } set { } }
public string Host { get { throw null; } set { } }
public int Port { get { throw null; } set { } }
public string Query { get { throw null; } set { } }
public Azure.Data.Tables.Sas.TableSasQueryParameters Sas { get { throw null; } set { } }
public string Scheme { get { throw null; } set { } }
public string Tablename { get { throw null; } set { } }
public override string ToString() { throw null; }
public System.Uri ToUri() { throw null; }
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using NuGet.Test.Helpers;
using Sleet;
using Xunit;
namespace SleetLib.Tests
{
public class FileSystemLockTests
{
[Fact]
public async Task FileSystemLock_VerifyMessageShownInLog()
{
using (var target = new TestFolder())
using (var cache = new LocalCache())
{
var log = new TestLogger();
var log2 = new TestLogger();
var fileSystem1 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
var fileSystem2 = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
var settings = new LocalSettings();
var lockMessage = Guid.NewGuid().ToString();
await InitCommand.RunAsync(settings, fileSystem1, log);
var lockObj1 = await SourceUtility.VerifyInitAndLock(settings, fileSystem1, lockMessage, log, CancellationToken.None);
lockObj1.IsLocked.Should().BeTrue();
var lockObj2Task = Task.Run(async () => await SourceUtility.VerifyInitAndLock(settings, fileSystem2, lockMessage, log2, CancellationToken.None));
while (!log2.GetMessages().Contains($"Feed is locked by: {lockMessage}"))
{
await Task.Delay(10);
}
lockObj1.Release();
var lockObj2 = await lockObj2Task;
while (!lockObj2.IsLocked)
{
await Task.Delay(10);
}
lockObj1.IsLocked.Should().BeFalse();
lockObj2.IsLocked.Should().BeTrue();
}
}
[Fact]
public async Task FileSystemLock_VerifyMessage()
{
using (var target = new TestFolder())
using (var cache = new LocalCache())
{
var log = new TestLogger();
var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
var settings = new LocalSettings();
var lockMessage = Guid.NewGuid().ToString();
await InitCommand.RunAsync(settings, fileSystem, log);
var lockObj = await SourceUtility.VerifyInitAndLock(settings, fileSystem, lockMessage, log, CancellationToken.None);
lockObj.IsLocked.Should().BeTrue();
var path = Path.Combine(target.Root, ".lock");
var json = JObject.Parse(File.ReadAllText(path));
json["message"].ToString().Should().Be(lockMessage);
json["date"].ToString().Should().NotBeNullOrEmpty();
json["pid"].ToString().Should().NotBeNullOrEmpty();
}
}
[Fact]
public async Task FileSystemLock_VerifyMessageFromSettings()
{
using (var target = new TestFolder())
using (var cache = new LocalCache())
{
var log = new TestLogger();
var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
var settings = new LocalSettings();
settings.FeedLockMessage = "FROMSETTINGS!!";
var lockMessage = Guid.NewGuid().ToString();
await InitCommand.RunAsync(settings, fileSystem, log);
var lockObj = await SourceUtility.VerifyInitAndLock(settings, fileSystem, lockMessage, log, CancellationToken.None);
lockObj.IsLocked.Should().BeTrue();
var path = Path.Combine(target.Root, ".lock");
var json = JObject.Parse(File.ReadAllText(path));
json["message"].ToString().Should().Be("FROMSETTINGS!!");
json["date"].ToString().Should().NotBeNullOrEmpty();
json["pid"].ToString().Should().NotBeNullOrEmpty();
}
}
[Fact]
public async Task FileSystemLock_SameFileSystemAsync()
{
using (var target = new TestFolder())
using (var cache = new LocalCache())
{
// Arrange
var log = new TestLogger();
var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(target.Root));
var lock1 = fileSystem.CreateLock(log);
var lock2 = fileSystem.CreateLock(log);
var lock3 = fileSystem.CreateLock(log);
// Act
var lock1Result = await lock1.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
var lock2Result = await lock2.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
var lock3Result = await lock3.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
// Assert
Assert.True(lock1Result);
Assert.False(lock2Result);
Assert.False(lock2Result);
// Act
lock1.Release();
lock2Result = await lock2.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
lock3Result = await lock3.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
// Assert
Assert.True(lock2Result);
Assert.False(lock3Result);
}
}
[Fact]
public async Task FileSystemLock_DifferentFileSystemsAsync()
{
using (var target = new TestFolder())
using (var cache1 = new LocalCache())
using (var cache2 = new LocalCache())
{
// Arrange
var log = new TestLogger();
var fileSystem1 = new PhysicalFileSystem(cache1, UriUtility.CreateUri(target.Root));
var fileSystem2 = new PhysicalFileSystem(cache2, UriUtility.CreateUri(target.Root));
var lock1 = fileSystem1.CreateLock(log);
var lock2 = fileSystem2.CreateLock(log);
// Act 1
var lock1Result = await lock1.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
var lock2Result = await lock2.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
// Assert 1
Assert.True(lock1Result);
Assert.False(lock2Result);
// Act 2
lock1.Release();
lock2Result = await lock2.GetLock(TimeSpan.FromSeconds(1), string.Empty, CancellationToken.None);
// Assert 2
Assert.True(lock2Result);
}
}
[Fact]
public async Task FileSystemLock_MultipleThreadsAsync()
{
using (var target = new TestFolder())
{
// Arrange
var tasks = new List<Task<bool>>();
var data = new ConcurrentDictionary<string, object>();
// Act
for (var i = 0; i < 100; i++)
{
tasks.Add(Task.Run(async () => await ThreadWork(data, target.Root)));
}
// Assert
foreach (var task in tasks)
{
Assert.True(await task);
}
}
}
private static async Task<bool> ThreadWork(ConcurrentDictionary<string, object> data, string root)
{
using (var cache = new LocalCache())
{
var log = new TestLogger();
var fileSystem = new PhysicalFileSystem(cache, UriUtility.CreateUri(root));
var lockData = fileSystem.CreateLock(log);
var result = await lockData.GetLock(TimeSpan.FromMinutes(1), string.Empty, CancellationToken.None);
try
{
var obj = new object();
if (!data.TryAdd("test", obj)
|| !data.TryRemove("test", out obj))
{
return false;
}
}
finally
{
lockData.Release();
}
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using OnlineExamPrep.WebAPI.Areas.HelpPage.ModelDescriptions;
using OnlineExamPrep.WebAPI.Areas.HelpPage.Models;
namespace OnlineExamPrep.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Ami Bar
// amibar@gmail.com
using System;
namespace Amib.Threading.Internal
{
#region WorkItemFactory class
public class WorkItemFactory
{
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback)
{
return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null);
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "workItemPriority">The priority of the work item</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
WorkItemPriority workItemPriority)
{
return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null, workItemPriority);
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "workItemInfo">Work item info</param>
/// <param name = "callback">A callback to execute</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemInfo workItemInfo,
WorkItemCallback callback)
{
return CreateWorkItem(
workItemsGroup,
wigStartInfo,
workItemInfo,
callback,
null);
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state)
{
ValidateCallback(callback);
WorkItemInfo workItemInfo = new WorkItemInfo
{
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
UseCallerHttpContext = wigStartInfo.UseCallerHttpContext,
PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback,
CallToPostExecute = wigStartInfo.CallToPostExecute,
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects
};
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name = "workItemPriority">The work item priority</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
WorkItemPriority workItemPriority)
{
ValidateCallback(callback);
WorkItemInfo workItemInfo = new WorkItemInfo
{
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
UseCallerHttpContext = wigStartInfo.UseCallerHttpContext,
PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback,
CallToPostExecute = wigStartInfo.CallToPostExecute,
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects,
WorkItemPriority = workItemPriority
};
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "workItemInfo">Work item information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemInfo workItemInfo,
WorkItemCallback callback,
object state)
{
ValidateCallback(callback);
ValidateCallback(workItemInfo.PostExecuteWorkItemCallback);
WorkItem workItem = new WorkItem(
workItemsGroup,
new WorkItemInfo(workItemInfo),
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name = "postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo
{
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
UseCallerHttpContext = wigStartInfo.UseCallerHttpContext,
PostExecuteWorkItemCallback = postExecuteWorkItemCallback,
CallToPostExecute = wigStartInfo.CallToPostExecute,
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects
};
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name = "postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name = "workItemPriority">The work item priority</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
WorkItemPriority workItemPriority)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo
{
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
UseCallerHttpContext = wigStartInfo.UseCallerHttpContext,
PostExecuteWorkItemCallback = postExecuteWorkItemCallback,
CallToPostExecute = wigStartInfo.CallToPostExecute,
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects,
WorkItemPriority = workItemPriority
};
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name = "postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name = "callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo
{
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
UseCallerHttpContext = wigStartInfo.UseCallerHttpContext,
PostExecuteWorkItemCallback = postExecuteWorkItemCallback,
CallToPostExecute = callToPostExecute,
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects
};
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
/// <summary>
/// Create a new work item
/// </summary>
/// <param name = "wigStartInfo">Work item group start information</param>
/// <param name = "callback">A callback to execute</param>
/// <param name = "state">
/// The context object of the work item. Used for passing arguments to the work item.
/// </param>
/// <param name = "postExecuteWorkItemCallback">
/// A delegate to call after the callback completion
/// </param>
/// <param name = "callToPostExecute">Indicates on which cases to call to the post execute callback</param>
/// <param name = "workItemPriority">The work item priority</param>
/// <returns>Returns a work item</returns>
public static WorkItem CreateWorkItem(
IWorkItemsGroup workItemsGroup,
WIGStartInfo wigStartInfo,
WorkItemCallback callback,
object state,
PostExecuteWorkItemCallback postExecuteWorkItemCallback,
CallToPostExecute callToPostExecute,
WorkItemPriority workItemPriority)
{
ValidateCallback(callback);
ValidateCallback(postExecuteWorkItemCallback);
WorkItemInfo workItemInfo = new WorkItemInfo
{
UseCallerCallContext = wigStartInfo.UseCallerCallContext,
UseCallerHttpContext = wigStartInfo.UseCallerHttpContext,
PostExecuteWorkItemCallback = postExecuteWorkItemCallback,
CallToPostExecute = callToPostExecute,
WorkItemPriority = workItemPriority,
DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects
};
WorkItem workItem = new WorkItem(
workItemsGroup,
workItemInfo,
callback,
state);
return workItem;
}
private static void ValidateCallback(Delegate callback)
{
if (callback.GetInvocationList().Length > 1)
{
throw new NotSupportedException("SmartThreadPool doesn't support delegates chains");
}
}
}
#endregion
}
| |
using System;
/// <summary>
/// String.Replace(Char, Char)
/// Replaces all occurrences of a specified Unicode character in this instance
/// with another specified Unicode character.
/// </summary>
public class StringReplace1
{
private const int c_MIN_STRING_LEN = 8;
private const int c_MAX_STRING_LEN = 256;
private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars)
private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars)
private const int c_MAX_LONG_STR_LEN = 65535;
public static int Main()
{
StringReplace1 sr = new StringReplace1();
TestLibrary.TestFramework.BeginTestCase("for method: System.String.Replace(Int32, Int32)");
if (sr.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;
return retVal;
}
#region Positive test scenarios
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1: Old char exists in source string, random new char.";
const string c_TEST_ID = "P001";
string strSrc;
char oldChar, newChar;
bool condition1 = false; //Verify the length invariant
bool condition2 = false; //Verify to replace correctly
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
//New update: modified by Noter(v-yaduoj) 8-10-2006
oldChar = strSrc[TestLibrary.Generator.GetInt32(-55) % (strSrc.Length)];
newChar = TestLibrary.Generator.GetChar(-55);
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldChar, newChar);
condition1 = (strReplaced.Length == strSrc.Length);
if (condition1)
{
condition2 = true;
for (int i = 0; i < strReplaced.Length; i++)
{
//Delete the incorrect check logic
// new update 8-10-2006, Noter(v-yaduoj)
if (strSrc[i] == oldChar)
{
condition2 = (strReplaced[i] == newChar) && condition2;
}
else
{
condition2 = (strSrc[i] == strReplaced[i]) && condition2;
}
} // end for statement
} // end if
actualValue = condition1 && condition2;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldChar, newChar);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldChar, newChar));
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2: Old char does not exist in source string, random new char.";
const string c_TEST_ID = "P002";
string strSrc;
char oldChar, newChar;
bool expectedValue = true;
bool actualValue = false;
//New update: modified by Noter(v-yaduoj) 8-10-2006
oldChar = TestLibrary.Generator.GetChar(-55);
newChar = TestLibrary.Generator.GetChar(-55);
//Generate source string does not contain old char
int length = GetInt32(c_MIN_STRING_LEN, c_MAX_STRING_LEN);
int index = 0;
char ch;
strSrc = string.Empty;
while (index < length)
{
ch = TestLibrary.Generator.GetChar(-55);
if (oldChar == ch)
{
continue;
}
strSrc += ch.ToString();
index++;
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldChar, newChar);
//New update: modified by Noter(v-yaduoj) 8-10-2006
actualValue = (0 == string.CompareOrdinal(strReplaced, strSrc));
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldChar, newChar);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldChar, newChar));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = @"PosTest3: Old char exists in source string, new char is \0 ";
const string c_TEST_ID = "P003";
string strSrc;
char oldChar, newChar;
bool condition1 = false; //Verify the length invariant
bool condition2 = false; //Verify to replace correctly
bool expectedValue = true;
bool actualValue = false;
strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
oldChar = strSrc[TestLibrary.Generator.GetInt32(-55) % strSrc.Length];
newChar = '\0';
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldChar, newChar);
condition1 = (strReplaced.Length == strSrc.Length);
if (condition1)
{
condition2 = true;
for (int i = 0; i < strReplaced.Length; i++)
{
//Delete the incorrect check logic
// new update 8-10-2006, Noter(v-yaduoj)
if (strSrc[i] == oldChar)
{
condition2 = (strReplaced[i] == newChar) && condition2;
}
else
{
condition2 = (strSrc[i] == strReplaced[i]) && condition2;
}
}// end for
} // end if
actualValue = condition1 && condition2;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldChar, newChar);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldChar, newChar));
retVal = false;
}
return retVal;
}
//Zero weight character '\u0400'
// new update 8-10-2006, Noter(v-yaduoj)
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = @"PosTest4: Old char '\u0400' is zero weight character, random new char";
const string c_TEST_ID = "P004";
string strSrc;
char oldChar, newChar;
bool condition1 = false; //Verify the length invariant
bool condition2 = false; //Verify to replace correctly
bool expectedValue = true;
bool actualValue = false;
oldChar = '\u0400';
newChar = TestLibrary.Generator.GetChar(-55);
//Generate source string contains '\u0400'
int length = GetInt32(c_MIN_STRING_LEN, c_MAX_STRING_LEN);
char[] chs = new char[length];
strSrc = oldChar.ToString();
for (int i, index = 1; index < length; index++)
{
i = TestLibrary.Generator.GetInt32(-55) % 6;
if (4 == i)
{
strSrc += oldChar.ToString();
}
else
{
strSrc += TestLibrary.Generator.GetChar(-55);
}
}
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
string strReplaced = strSrc.Replace(oldChar, newChar);
condition1 = (strReplaced.Length == strSrc.Length);
if (condition1)
{
condition2 = true;
for (int i = 0; i < strReplaced.Length; i++)
{
if (strSrc[i] == oldChar)
{
condition2 = (strReplaced[i] == newChar) && condition2;
}
else
{
condition2 = (strSrc[i] == strReplaced[i]) && condition2;
}
}// end for
} // end if
actualValue = condition1 && condition2;
if (actualValue != expectedValue)
{
string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")";
errorDesc += GetDataString(strSrc, oldChar, newChar);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, oldChar, newChar));
retVal = false;
}
return retVal;
}
#endregion
#region helper methods for generating test data
private bool GetBoolean()
{
Int32 i = this.GetInt32(1, 2);
return (i == 1) ? true : false;
}
//Get a non-negative integer between minValue and maxValue
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
private Int32 Min(Int32 i1, Int32 i2)
{
return (i1 <= i2) ? i1 : i2;
}
private Int32 Max(Int32 i1, Int32 i2)
{
return (i1 >= i2) ? i1 : i2;
}
#endregion
private string GetDataString(string strSrc, char oldChar, char newChar)
{
string str1, str;
int len1;
if (null == strSrc)
{
str1 = "null";
len1 = 0;
}
else
{
str1 = strSrc;
len1 = strSrc.Length;
}
str = string.Format("\n[Source string value]\n \"{0}\"", str1);
str += string.Format("\n[Length of source string]\n {0}", len1);
str += string.Format("\n[Old char]\n{0}", oldChar);
str += string.Format("\n[New char]\n{0}", newChar);
return str;
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator 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.
//
#endregion
using System.Data;
using FluentMigrator.Runner.Generators.Hana;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.Hana
{
[TestFixture]
[Category("Hana")]
public class HanaConstraintsTests : BaseConstraintsTests
{
protected HanaGenerator Generator;
[SetUp]
public void Setup()
{
Generator = new HanaGenerator();
}
[Test]
public override void CanCreateForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_TestTable1_TestColumn1_TestTable2_TestColumn2\" " +
"FOREIGN KEY (\"TestColumn1\") REFERENCES \"TestTable2\" (\"TestColumn2\");");
}
[Test]
public override void CanCreateForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_TestTable1_TestColumn1_TestTable2_TestColumn2\" " +
"FOREIGN KEY (\"TestColumn1\") REFERENCES \"TestTable2\" (\"TestColumn2\");");
}
[Test]
public override void CanCreateForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_TestTable1_TestColumn1_TestTable2_TestColumn2\" " +
"FOREIGN KEY (\"TestColumn1\") REFERENCES \"TestTable2\" (\"TestColumn2\");");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT " +
"\"FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4\" " +
"FOREIGN KEY (\"TestColumn1\", \"TestColumn3\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\", \"TestColumn4\");");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT " +
"\"FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4\" " +
"FOREIGN KEY (\"TestColumn1\", \"TestColumn3\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\", \"TestColumn4\");");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT " +
"\"FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4\" " +
"FOREIGN KEY (\"TestColumn1\", \"TestColumn3\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\", \"TestColumn4\");");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"PK_TestTable1_TestColumn1_TestColumn2\" " +
"PRIMARY KEY (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"PK_TestTable1_TestColumn1_TestColumn2\" " +
"PRIMARY KEY (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"UC_TestTable1_TestColumn1_TestColumn2\" " +
"UNIQUE (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"UC_TestTable1_TestColumn1_TestColumn2\" " +
"UNIQUE (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateNamedForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_Test\" " +
"FOREIGN KEY (\"TestColumn1\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\");");
}
[Test]
public override void CanCreateNamedForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_Test\" " +
"FOREIGN KEY (\"TestColumn1\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\");");
}
[Test]
public override void CanCreateNamedForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_Test\" " +
"FOREIGN KEY (\"TestColumn1\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\");");
}
[Test]
public override void CanCreateNamedForeignKeyWithOnDeleteAndOnUpdateOptions()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = Rule.Cascade;
expression.ForeignKey.OnUpdate = Rule.SetDefault;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_Test\" " +
"FOREIGN KEY (\"TestColumn1\") REFERENCES \"TestTable2\" (\"TestColumn2\") " +
"ON DELETE CASCADE ON UPDATE SET DEFAULT;");
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnDeleteOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format(
"ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_Test\" " +
"FOREIGN KEY (\"TestColumn1\") REFERENCES \"TestTable2\" (\"TestColumn2\") " +
"ON DELETE {0};", output));
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnUpdateOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnUpdate = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format(
"ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"FK_Test\" " +
"FOREIGN KEY (\"TestColumn1\") REFERENCES \"TestTable2\" (\"TestColumn2\") " +
"ON UPDATE {0};", output));
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"TestColumn1\", \"TestColumn3\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\", \"TestColumn4\");");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"TestColumn1\", \"TestColumn3\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\", \"TestColumn4\");");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"FK_Test\" FOREIGN KEY (\"TestColumn1\", \"TestColumn3\") " +
"REFERENCES \"TestTable2\" (\"TestColumn2\", \"TestColumn4\");");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTPRIMARYKEY\" " +
"PRIMARY KEY (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTPRIMARYKEY\" " +
"PRIMARY KEY (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTUNIQUECONSTRAINT\" " +
"UNIQUE (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTUNIQUECONSTRAINT\" " +
"UNIQUE (\"TestColumn1\", \"TestColumn2\");");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTPRIMARYKEY\" " +
"PRIMARY KEY (\"TestColumn1\");");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTPRIMARYKEY\" " +
"PRIMARY KEY (\"TestColumn1\");");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTUNIQUECONSTRAINT\" " +
"UNIQUE (\"TestColumn1\");");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" " +
"ADD CONSTRAINT \"TESTUNIQUECONSTRAINT\" " +
"UNIQUE (\"TestColumn1\");");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"PK_TestTable1_TestColumn1\" PRIMARY KEY (\"TestColumn1\");");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"PK_TestTable1_TestColumn1\" PRIMARY KEY (\"TestColumn1\");");
}
[Test]
public override void CanCreateUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"UC_TestTable1_TestColumn1\" UNIQUE (\"TestColumn1\");");
}
[Test]
public override void CanCreateUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" ADD CONSTRAINT \"UC_TestTable1_TestColumn1\" UNIQUE (\"TestColumn1\");");
}
[Test]
public override void CanDropForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP CONSTRAINT \"FK_Test\";");
}
[Test]
public override void CanDropForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP CONSTRAINT \"FK_Test\";");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP PRIMARY KEY;");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP PRIMARY KEY;");
}
[Test]
public override void CanDropUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP CONSTRAINT \"TESTUNIQUECONSTRAINT\";");
}
[Test]
public override void CanDropUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE \"TestTable1\" DROP CONSTRAINT \"TESTUNIQUECONSTRAINT\";");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Workspaces
{
public partial class WorkspaceTests
{
private TestWorkspace CreateWorkspace(bool disablePartialSolutions = true)
{
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext());
return new TestWorkspace(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, disablePartialSolutions: disablePartialSolutions);
}
private static void WaitForWorkspaceOperationsToComplete(TestWorkspace workspace)
{
var workspasceWaiter = workspace.ExportProvider
.GetExports<IAsynchronousOperationListener, FeatureMetadata>()
.First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter;
workspasceWaiter.CreateWaitTask().PumpingWait();
}
[Fact]
public void TestEmptySolutionUpdate()
{
using (var workspace = CreateWorkspace())
{
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
var solution = workspace.CurrentSolution;
bool workspaceChanged = false;
workspace.WorkspaceChanged += (s, e) => workspaceChanged = true;
workspace.OnParseOptionsChanged(project.Id, project.ParseOptions);
WaitForWorkspaceOperationsToComplete(workspace);
Assert.Equal(solution, workspace.CurrentSolution);
Assert.False(workspaceChanged);
}
}
[Fact]
public void TestAddProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
solution = workspace.CurrentSolution;
Assert.Equal(1, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveExistingProject1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
workspace.OnProjectRemoved(project.Id);
solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveExistingProject2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
workspace.AddTestProject(project);
solution = workspace.CurrentSolution;
workspace.OnProjectRemoved(project.Id);
solution = workspace.CurrentSolution;
Assert.Equal(0, solution.Projects.Count());
}
}
[Fact]
public void TestRemoveNonAddedProject1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project = new TestHostProject(workspace);
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project.Id));
}
}
[Fact]
public void TestRemoveNonAddedProject2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project2.Id));
}
}
[Fact]
public void TestChangeOptions1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(
@"#if FOO
class C { }
#else
class D { }
#endif");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
VerifyRootTypeName(workspace, "D");
workspace.OnParseOptionsChanged(document.Id.ProjectId,
new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" }));
VerifyRootTypeName(workspace, "C");
}
}
[Fact]
public void TestChangeOptions2()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(
@"#if FOO
class C { }
#else
class D { }
#endif");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
VerifyRootTypeName(workspace, "D");
workspace.OnParseOptionsChanged(document.Id.ProjectId,
new CSharpParseOptions(preprocessorSymbols: new[] { "FOO" }));
VerifyRootTypeName(workspace, "C");
workspace.OnDocumentClosed(document.Id);
}
}
private static void VerifyRootTypeName(TestWorkspace workspaceSnapshotBuilder, string typeName)
{
var currentSnapshot = workspaceSnapshotBuilder.CurrentSolution;
var type = GetRootTypeDeclaration(currentSnapshot);
Assert.Equal(type.Identifier.ValueText, typeName);
}
private static TypeDeclarationSyntax GetRootTypeDeclaration(Solution currentSnapshot)
{
var tree = currentSnapshot.Projects.First().Documents.First().GetSyntaxTreeAsync().Result;
var root = (CompilationUnitSyntax)tree.GetRoot();
var type = (TypeDeclarationSyntax)root.Members[0];
return type;
}
[Fact]
public void TestAddP2PReferenceFails()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)));
}
}
[Fact]
public void TestAddP2PReference1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var reference = new ProjectReference(project2.Id);
workspace.OnProjectReferenceAdded(project1.Id, reference);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
Assert.True(snapshot.GetProject(id1).ProjectReferences.Contains(reference), "ProjectReferences did not contain project2");
}
}
[Fact]
public void TestAddP2PReferenceTwice()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id)));
}
}
[Fact]
public void TestRemoveP2PReference1()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
workspace.OnProjectReferenceRemoved(project1.Id, new ProjectReference(project2.Id));
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
Assert.Equal(0, snapshot.GetProject(id1).ProjectReferences.Count());
}
}
[Fact]
public void TestAddP2PReferenceCircularity()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var project1 = new TestHostProject(workspace, name: "project1");
var project2 = new TestHostProject(workspace, name: "project2");
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
workspace.OnProjectReferenceAdded(project1.Id, new ProjectReference(project2.Id));
Assert.Throws<ArgumentException>(() => workspace.OnProjectReferenceAdded(project2.Id, new ProjectReference(project1.Id)));
}
}
[Fact]
public void TestRemoveProjectWithOpenedDocuments()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
Assert.Throws<ArgumentException>(() => workspace.OnProjectRemoved(project1.Id));
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public void TestRemoveProjectWithClosedDocuments()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public void TestRemoveOpenedDocument()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
Assert.Throws<ArgumentException>(() => workspace.OnDocumentRemoved(document.Id));
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public void TestGetCompilation()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(@"class C { }");
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
VerifyRootTypeName(workspace, "C");
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var compilation = snapshot.GetProject(id1).GetCompilationAsync().Result;
var classC = compilation.SourceModule.GlobalNamespace.GetMembers("C").Single();
}
}
[Fact]
public void TestGetCompilationOnDependentProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument(@"class D : C { }");
var project2 = new TestHostProject(workspace, document2, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = snapshot.GetProject(id2).GetCompilationAsync().Result;
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
}
}
[Fact]
public void TestGetCompilationOnCrossLanguageDependentProject()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var snapshot = workspace.CurrentSolution;
var id1 = snapshot.Projects.First(p => p.Name == project1.Name).Id;
var id2 = snapshot.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = snapshot.GetProject(id2).GetCompilationAsync().Result;
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
}
}
[Fact]
public void TestGetCompilationOnCrossLanguageDependentProjectChanged()
{
using (var workspace = CreateWorkspace())
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2 = solutionY.GetProject(id2).GetCompilationAsync().Result;
var errors = compilation2.GetDiagnostics();
var classD = compilation2.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classC = classD.BaseType;
Assert.NotEqual(TypeKind.Error, classC.TypeKind);
// change the class name in document1
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
var buffer1 = document1.GetTextBuffer();
// change C to X
buffer1.Replace(new Span(13, 1), "X");
// this solution should have the change
var solutionZ = workspace.CurrentSolution;
var docZ = solutionZ.GetDocument(document1.Id);
var docZText = docZ.GetTextAsync().PumpingWaitResult();
var compilation2Z = solutionZ.GetProject(id2).GetCompilationAsync().Result;
var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCz = classDz.BaseType;
Assert.Equal(TypeKind.Error, classCz.TypeKind);
}
}
[Fact]
public void TestDependentSemanticVersionChangesWhenNotOriginallyAccessed()
{
using (var workspace = CreateWorkspace(disablePartialSolutions: false))
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2y = solutionY.GetProject(id2).GetCompilationAsync().Result;
var errors = compilation2y.GetDiagnostics();
var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCy = classDy.BaseType;
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
// change C to X
var buffer1 = document1.GetTextBuffer();
buffer1.Replace(new Span(13, 1), "X");
for (int iter = 0; iter < 10; iter++)
{
WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle);
Thread.Sleep(1000);
// the current solution should eventually have the change
var cs = workspace.CurrentSolution;
var doc1Z = cs.GetDocument(document1.Id);
var hasX = doc1Z.GetTextAsync().Result.ToString().Contains("X");
if (hasX)
{
var newVersion = cs.GetProject(project1.Id).GetDependentSemanticVersionAsync().Result;
var newVersionX = doc1Z.Project.GetDependentSemanticVersionAsync().Result;
Assert.NotEqual(VersionStamp.Default, newVersion);
Assert.Equal(newVersion, newVersionX);
break;
}
}
}
}
[Fact]
public void TestGetCompilationOnCrossLanguageDependentProjectChangedInProgress()
{
using (var workspace = CreateWorkspace(disablePartialSolutions: false))
{
var solutionX = workspace.CurrentSolution;
var document1 = new TestHostDocument(@"public class C { }");
var project1 = new TestHostProject(workspace, document1, name: "project1");
var document2 = new TestHostDocument("Public Class D \r\n Inherits C\r\nEnd Class");
var project2 = new TestHostProject(workspace, document2, language: LanguageNames.VisualBasic, name: "project2", projectReferences: new[] { project1 });
workspace.AddTestProject(project1);
workspace.AddTestProject(project2);
var solutionY = workspace.CurrentSolution;
var id1 = solutionY.Projects.First(p => p.Name == project1.Name).Id;
var id2 = solutionY.Projects.First(p => p.Name == project2.Name).Id;
var compilation2y = solutionY.GetProject(id2).GetCompilationAsync().Result;
var errors = compilation2y.GetDiagnostics();
var classDy = compilation2y.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCy = classDy.BaseType;
Assert.NotEqual(TypeKind.Error, classCy.TypeKind);
// open both documents so background compiler works on their compilations
workspace.OnDocumentOpened(document1.Id, document1.GetOpenTextContainer());
workspace.OnDocumentOpened(document2.Id, document2.GetOpenTextContainer());
// change C to X
var buffer1 = document1.GetTextBuffer();
buffer1.Replace(new Span(13, 1), "X");
var foundTheError = false;
for (int iter = 0; iter < 10; iter++)
{
WaitHelper.WaitForDispatchedOperationsToComplete(System.Windows.Threading.DispatcherPriority.ApplicationIdle);
Thread.Sleep(1000);
// the current solution should eventually have the change
var cs = workspace.CurrentSolution;
var doc1Z = cs.GetDocument(document1.Id);
var hasX = doc1Z.GetTextAsync().Result.ToString().Contains("X");
if (hasX)
{
var doc2Z = cs.GetDocument(document2.Id);
var partialDoc2Z = doc2Z.WithFrozenPartialSemanticsAsync(CancellationToken.None).Result;
var compilation2Z = partialDoc2Z.Project.GetCompilationAsync().Result;
var classDz = compilation2Z.SourceModule.GlobalNamespace.GetTypeMembers("D").Single();
var classCz = classDz.BaseType;
if (classCz.TypeKind == TypeKind.Error)
{
foundTheError = true;
break;
}
}
}
Assert.True(foundTheError, "Did not find error");
}
}
[Fact]
public void TestOpenAndChangeDocument()
{
using (var workspace = CreateWorkspace())
{
var solution = workspace.CurrentSolution;
var document = new TestHostDocument(string.Empty);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
buffer.Insert(0, "class C {}");
solution = workspace.CurrentSolution;
var doc = solution.Projects.Single().Documents.First();
var syntaxTree = doc.GetSyntaxTreeAsync(CancellationToken.None).Result;
Assert.True(syntaxTree.GetRoot().Width() > 0, "syntaxTree.GetRoot().Width should be > 0");
workspace.OnDocumentClosed(document.Id);
workspace.OnProjectRemoved(project1.Id);
}
}
[Fact]
public void TestApplyChangesWithDocumentTextUpdated()
{
using (var workspace = CreateWorkspace())
{
var startText = "public class C { }";
var newText = "public class D { }";
var document = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
var buffer = document.GetTextBuffer();
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer());
// prove the document has the correct text
Assert.Equal(startText, workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync().PumpingWaitResult().ToString());
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.WithDocumentText(document.Id, SourceText.From(newText));
// prove that current document text is unchanged
Assert.Equal(startText, workspace.CurrentSolution.GetDocument(document.Id).GetTextAsync().PumpingWaitResult().ToString());
// prove buffer is unchanged too
Assert.Equal(startText, buffer.CurrentSnapshot.GetText());
workspace.TryApplyChanges(newSolution);
// new text should have been pushed into buffer
Assert.Equal(newText, buffer.CurrentSnapshot.GetText());
}
}
[Fact]
public void TestApplyChangesWithDocumentAdded()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var doc2Text = "public class D { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.AddDocument(DocumentId.CreateNewId(project1.Id), "Doc2", SourceText.From(doc2Text));
workspace.TryApplyChanges(newSolution);
// new document should have been added.
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
}
}
[Fact]
public void TestApplyChangesWithDocumentRemoved()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
workspace.AddTestProject(project1);
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.RemoveDocument(document.Id);
workspace.TryApplyChanges(newSolution);
// document should have been removed
Assert.Equal(0, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
}
}
[Fact]
public void TestDocumentEvents()
{
using (var workspace = CreateWorkspace())
{
var doc1Text = "public class C { }";
var document = new TestHostDocument(doc1Text);
var project1 = new TestHostProject(workspace, document, name: "project1");
var longEventTimeout = TimeSpan.FromMinutes(5);
var shortEventTimeout = TimeSpan.FromSeconds(5);
workspace.AddTestProject(project1);
// Creating two waiters that will allow us to know for certain if the events have fired.
using (var closeWaiter = new EventWaiter())
using (var openWaiter = new EventWaiter())
{
// Wrapping event handlers so they can notify us on being called.
var documentOpenedEventHandler = openWaiter.Wrap<DocumentEventArgs>(
(sender, args) => Assert.True(args.Document.Id == document.Id,
"The document given to the 'DocumentOpened' event handler did not have the same id as the one created for the test."));
var documentClosedEventHandler = closeWaiter.Wrap<DocumentEventArgs>(
(sender, args) => Assert.True(args.Document.Id == document.Id,
"The document given to the 'DocumentClosed' event handler did not have the same id as the one created for the test."));
workspace.DocumentOpened += documentOpenedEventHandler;
workspace.DocumentClosed += documentClosedEventHandler;
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
// Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified.
WaitForWorkspaceOperationsToComplete(workspace);
// Wait to recieve signal that events have fired.
Assert.True(openWaiter.WaitForEventToFire(longEventTimeout),
string.Format("event 'DocumentOpened' was not fired within {0} minutes.",
longEventTimeout.Minutes));
Assert.True(closeWaiter.WaitForEventToFire(longEventTimeout),
string.Format("event 'DocumentClosed' was not fired within {0} minutes.",
longEventTimeout.Minutes));
workspace.DocumentOpened -= documentOpenedEventHandler;
workspace.DocumentClosed -= documentClosedEventHandler;
workspace.OpenDocument(document.Id);
workspace.CloseDocument(document.Id);
// Wait for all workspace tasks to finish. After this is finished executing, all handlers should have been notified.
WaitForWorkspaceOperationsToComplete(workspace);
// Verifiying that an event has not been called is difficult to prove.
// All events should have already been called so we wait 5 seconds and then assume the event handler was removed correctly.
Assert.False(openWaiter.WaitForEventToFire(shortEventTimeout),
string.Format("event handler 'DocumentOpened' was called within {0} seconds though it was removed from the list.",
shortEventTimeout.Seconds));
Assert.False(closeWaiter.WaitForEventToFire(shortEventTimeout),
string.Format("event handler 'DocumentClosed' was called within {0} seconds though it was removed from the list.",
shortEventTimeout.Seconds));
}
}
}
[Fact]
public void TestAdditionalFile_Properties()
{
using (var workspace = CreateWorkspace())
{
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument("some text");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
Assert.Equal(1, project.Documents.Count());
Assert.Equal(1, project.AdditionalDocuments.Count());
Assert.Equal(1, project.AdditionalDocumentIds.Count);
var doc = project.GetDocument(additionalDoc.Id);
Assert.Null(doc);
var additionalDocument = project.GetAdditionalDocument(additionalDoc.Id);
Assert.Equal("some text", additionalDocument.GetTextAsync().PumpingWaitResult().ToString());
}
}
[Fact]
public void TestAdditionalFile_DocumentChanged()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var newText = @"<setting value = ""foo1""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var buffer = additionalDoc.GetTextBuffer();
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
var project = workspace.CurrentSolution.Projects.Single();
var oldVersion = project.GetSemanticVersionAsync().PumpingWaitResult();
// fork the solution to introduce a change.
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.WithAdditionalDocumentText(additionalDoc.Id, SourceText.From(newText));
workspace.TryApplyChanges(newSolution);
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
// new text should have been pushed into buffer
Assert.Equal(newText, buffer.CurrentSnapshot.GetText());
// Text changes are considered top level changes and they change the project's semantic version.
Assert.Equal(doc.GetTextVersionAsync().PumpingWaitResult(), doc.GetTopLevelChangeTextVersionAsync().PumpingWaitResult());
Assert.NotEqual(oldVersion, doc.Project.GetSemanticVersionAsync().PumpingWaitResult());
}
}
[Fact]
public void TestAdditionalFile_OpenClose()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText);
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var buffer = additionalDoc.GetTextBuffer();
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
var text = doc.GetTextAsync(CancellationToken.None).PumpingWaitResult();
var version = doc.GetTextVersionAsync(CancellationToken.None).PumpingWaitResult();
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
// We don't have a GetOpenAdditionalDocumentIds since we don't need it. But make sure additional documents
// don't creep into OpenDocumentIds (Bug: 1087470)
Assert.Empty(workspace.GetOpenDocumentIds());
workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version)));
// Reopen and close to make sure we are not leaking anything.
workspace.OnAdditionalDocumentOpened(additionalDoc.Id, additionalDoc.GetOpenTextContainer());
workspace.OnAdditionalDocumentClosed(additionalDoc.Id, TextLoader.From(TextAndVersion.Create(text, version)));
Assert.Empty(workspace.GetOpenDocumentIds());
}
}
[Fact]
public void TestAdditionalFile_AddRemove()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText, "original.config");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
// fork the solution to introduce a change.
var newDocId = DocumentId.CreateNewId(project.Id);
var oldSolution = workspace.CurrentSolution;
var newSolution = oldSolution.AddAdditionalDocument(newDocId, "app.config", "text");
var doc = workspace.CurrentSolution.GetAdditionalDocument(additionalDoc.Id);
workspace.TryApplyChanges(newSolution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
// Now remove the newly added document
oldSolution = workspace.CurrentSolution;
newSolution = oldSolution.RemoveAdditionalDocument(newDocId);
workspace.TryApplyChanges(newSolution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
[Fact]
public void TestAdditionalFile_AddRemove_FromProject()
{
using (var workspace = CreateWorkspace())
{
var startText = @"<setting value = ""foo""";
var document = new TestHostDocument("public class C { }");
var additionalDoc = new TestHostDocument(startText, "original.config");
var project1 = new TestHostProject(workspace, name: "project1", documents: new[] { document }, additionalDocuments: new[] { additionalDoc });
workspace.AddTestProject(project1);
var project = workspace.CurrentSolution.Projects.Single();
// fork the solution to introduce a change.
var doc = project.AddAdditionalDocument("app.config", "text");
workspace.TryApplyChanges(doc.Project.Solution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(2, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
// Now remove the newly added document
project = workspace.CurrentSolution.Projects.Single();
workspace.TryApplyChanges(project.RemoveAdditionalDocument(doc.Id).Solution);
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).Documents.Count());
Assert.Equal(1, workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Count());
Assert.Equal("original.config", workspace.CurrentSolution.GetProject(project1.Id).AdditionalDocuments.Single().Name);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using System.Collections;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
namespace OpenSim.Services.Connectors.Simulation
{
public class SimulationServiceConnector : ISimulationService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// we use this dictionary to track the pending updateagent requests, maps URI --> position update
private Dictionary<string,AgentPosition> m_updateAgentQueue = new Dictionary<string,AgentPosition>();
//private GridRegion m_Region;
public SimulationServiceConnector()
{
}
public SimulationServiceConnector(IConfigSource config)
{
//m_Region = region;
}
public IScene GetScene(UUID regionId)
{
return null;
}
public ISimulationService GetInnerService()
{
return null;
}
#region Agents
protected virtual string AgentPath()
{
return "agent/";
}
protected virtual void PackData(OSDMap args, GridRegion source, AgentCircuitData aCircuit, GridRegion destination, uint flags)
{
if (source != null)
{
args["source_x"] = OSD.FromString(source.RegionLocX.ToString());
args["source_y"] = OSD.FromString(source.RegionLocY.ToString());
args["source_name"] = OSD.FromString(source.RegionName);
args["source_uuid"] = OSD.FromString(source.RegionID.ToString());
if (!String.IsNullOrEmpty(source.RawServerURI))
args["source_server_uri"] = OSD.FromString(source.RawServerURI);
}
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
args["teleport_flags"] = OSD.FromString(flags.ToString());
}
public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, out string reason)
{
string tmp = String.Empty;
return CreateAgent(source, destination, aCircuit, flags, out tmp, out reason);
}
public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint flags, out string myipaddress, out string reason)
{
m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: Creating agent at {0}", destination.ServerURI);
reason = String.Empty;
myipaddress = String.Empty;
if (destination == null)
{
m_log.Debug("[REMOTE SIMULATION CONNECTOR]: Given destination is null");
return false;
}
string uri = destination.ServerURI + AgentPath() + aCircuit.AgentID + "/";
try
{
OSDMap args = aCircuit.PackAgentCircuitData();
PackData(args, source, aCircuit, destination, flags);
OSDMap result = WebUtil.PostToServiceCompressed(uri, args, 30000);
bool success = result["success"].AsBoolean();
if (success && result.ContainsKey("_Result"))
{
OSDMap data = (OSDMap)result["_Result"];
reason = data["reason"].AsString();
success = data["success"].AsBoolean();
myipaddress = data["your_ip"].AsString();
return success;
}
// Try the old version, uncompressed
result = WebUtil.PostToService(uri, args, 30000, false);
if (result["Success"].AsBoolean())
{
if (result.ContainsKey("_Result"))
{
OSDMap data = (OSDMap)result["_Result"];
reason = data["reason"].AsString();
success = data["success"].AsBoolean();
myipaddress = data["your_ip"].AsString();
m_log.WarnFormat(
"[REMOTE SIMULATION CONNECTOR]: Remote simulator {0} did not accept compressed transfer, suggest updating it.", destination.RegionName);
return success;
}
}
m_log.WarnFormat(
"[REMOTE SIMULATION CONNECTOR]: Failed to create agent {0} {1} at remote simulator {2}",
aCircuit.firstname, aCircuit.lastname, destination.RegionName);
reason = result["Message"] != null ? result["Message"].AsString() : "error";
return false;
}
catch (Exception e)
{
m_log.Warn("[REMOTE SIMULATION CONNECTOR]: CreateAgent failed with exception: " + e.ToString());
reason = e.Message;
}
return false;
}
/// <summary>
/// Send complete data about an agent in this region to a neighbor
/// </summary>
public bool UpdateAgent(GridRegion destination, AgentData data)
{
return UpdateAgent(destination, (IAgentData)data, 200000); // yes, 200 seconds
}
private ExpiringCache<string, bool> _failedSims = new ExpiringCache<string, bool>();
/// <summary>
/// Send updated position information about an agent in this region to a neighbor
/// This operation may be called very frequently if an avatar is moving about in
/// the region.
/// </summary>
public bool UpdateAgent(GridRegion destination, AgentPosition data)
{
bool v = true;
if (_failedSims.TryGetValue(destination.ServerURI, out v))
return false;
// The basic idea of this code is that the first thread that needs to
// send an update for a specific avatar becomes the worker for any subsequent
// requests until there are no more outstanding requests. Further, only send the most
// recent update; this *should* never be needed but some requests get
// slowed down and once that happens the problem with service end point
// limits kicks in and nothing proceeds
string uri = destination.ServerURI + AgentPath() + data.AgentID + "/";
lock (m_updateAgentQueue)
{
if (m_updateAgentQueue.ContainsKey(uri))
{
// Another thread is already handling
// updates for this simulator, just update
// the position and return, overwrites are
// not a problem since we only care about the
// last update anyway
m_updateAgentQueue[uri] = data;
return true;
}
// Otherwise update the reference and start processing
m_updateAgentQueue[uri] = data;
}
AgentPosition pos = null;
bool success = true;
while (success)
{
lock (m_updateAgentQueue)
{
// save the position
AgentPosition lastpos = pos;
pos = m_updateAgentQueue[uri];
// this is true if no one put a new
// update in the map since the last
// one we processed, if thats the
// case then we are done
if (pos == lastpos)
{
m_updateAgentQueue.Remove(uri);
return true;
}
}
success = UpdateAgent(destination, (IAgentData)pos, 10000);
}
// we get here iff success == false
// blacklist sim for 2 minutes
lock (m_updateAgentQueue)
{
_failedSims.AddOrUpdate(destination.ServerURI, true, 120);
m_updateAgentQueue.Remove(uri);
}
return false;
}
/// <summary>
/// This is the worker function to send AgentData to a neighbor region
/// </summary>
private bool UpdateAgent(GridRegion destination, IAgentData cAgentData, int timeout)
{
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: UpdateAgent in {0}", destination.ServerURI);
// Eventually, we want to use a caps url instead of the agentID
string uri = destination.ServerURI + AgentPath() + cAgentData.AgentID + "/";
try
{
OSDMap args = cAgentData.Pack();
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
OSDMap result = WebUtil.PutToServiceCompressed(uri, args, timeout);
if (result["Success"].AsBoolean())
return true;
result = WebUtil.PutToService(uri, args, timeout);
return result["Success"].AsBoolean();
}
catch (Exception e)
{
m_log.Warn("[REMOTE SIMULATION CONNECTOR]: UpdateAgent failed with exception: " + e.ToString());
}
return false;
}
public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, string myversion, out string version, out string reason)
{
reason = "Failed to contact destination";
version = "Unknown";
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: QueryAccess start, position={0}", position);
IPEndPoint ext = destination.ExternalEndPoint;
if (ext == null) return false;
// Eventually, we want to use a caps url instead of the agentID
string uri = destination.ServerURI + AgentPath() + agentID + "/" + destination.RegionID.ToString() + "/";
OSDMap request = new OSDMap();
request.Add("viaTeleport", OSD.FromBoolean(viaTeleport));
request.Add("position", OSD.FromString(position.ToString()));
request.Add("my_version", OSD.FromString(myversion));
if (agentHomeURI != null)
request.Add("agent_home_uri", OSD.FromString(agentHomeURI));
try
{
OSDMap result = WebUtil.ServiceOSDRequest(uri, request, "QUERYACCESS", 30000, false, false);
bool success = result["success"].AsBoolean();
if (result.ContainsKey("_Result"))
{
OSDMap data = (OSDMap)result["_Result"];
// FIXME: If there is a _Result map then it's the success key here that indicates the true success
// or failure, not the sibling result node.
success = data["success"];
reason = data["reason"].AsString();
if (data["version"] != null && data["version"].AsString() != string.Empty)
version = data["version"].AsString();
m_log.DebugFormat(
"[REMOTE SIMULATION CONNECTOR]: QueryAccess to {0} returned {1}, reason {2}, version {3} ({4})",
uri, success, reason, version, data["version"].AsString());
}
if (!success)
{
// If we don't check this then OpenSimulator 0.7.3.1 and some period before will never see the
// actual failure message
if (!result.ContainsKey("_Result"))
{
if (result.ContainsKey("Message"))
{
string message = result["Message"].AsString();
if (message == "Service request failed: [MethodNotAllowed] MethodNotAllowed") // Old style region
{
m_log.Info("[REMOTE SIMULATION CONNECTOR]: The above web util error was caused by a TP to a sim that doesn't support QUERYACCESS and can be ignored");
return true;
}
reason = result["Message"];
}
else
{
reason = "Communications failure";
}
}
return false;
}
return success;
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] QueryAcesss failed with exception; {0}",e.ToString());
}
return false;
}
/// <summary>
/// </summary>
public bool ReleaseAgent(UUID origin, UUID id, string uri)
{
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: ReleaseAgent start");
try
{
WebUtil.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false);
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] ReleaseAgent failed with exception; {0}",e.ToString());
}
return true;
}
/// <summary>
/// </summary>
public bool CloseAgent(GridRegion destination, UUID id, string auth_code)
{
string uri = destination.ServerURI + AgentPath() + id + "/" + destination.RegionID.ToString() + "/?auth=" + auth_code;
m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CloseAgent {0}", uri);
try
{
WebUtil.ServiceOSDRequest(uri, null, "DELETE", 10000, false, false);
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CloseAgent failed with exception; {0}",e.ToString());
}
return true;
}
#endregion Agents
#region Objects
protected virtual string ObjectPath()
{
return "object/";
}
/// <summary>
///
/// </summary>
public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall)
{
// m_log.DebugFormat("[REMOTE SIMULATION CONNECTOR]: CreateObject start");
string uri = destination.ServerURI + ObjectPath() + sog.UUID + "/";
try
{
OSDMap args = new OSDMap(2);
args["sog"] = OSD.FromString(sog.ToXml2());
args["extra"] = OSD.FromString(sog.ExtraToXmlString());
args["modified"] = OSD.FromBoolean(sog.HasGroupChanged);
args["new_position"] = newPosition.ToString();
string state = sog.GetStateSnapshot();
if (state.Length > 0)
args["state"] = OSD.FromString(state);
// Add the input general arguments
args["destination_x"] = OSD.FromString(destination.RegionLocX.ToString());
args["destination_y"] = OSD.FromString(destination.RegionLocY.ToString());
args["destination_name"] = OSD.FromString(destination.RegionName);
args["destination_uuid"] = OSD.FromString(destination.RegionID.ToString());
OSDMap result = WebUtil.PostToService(uri, args, 40000, false);
if (result == null)
return false;
bool success = result["success"].AsBoolean();
if (!success)
return false;
}
catch (Exception e)
{
m_log.WarnFormat("[REMOTE SIMULATION CONNECTOR] CreateObject failed with exception; {0}",e.ToString());
return false;
}
return true;
}
/// <summary>
///
/// </summary>
public bool CreateObject(GridRegion destination, UUID userID, UUID itemID)
{
// TODO, not that urgent
return false;
}
#endregion Objects
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace GitReleaseNotes
{
public class SemanticReleaseNotes
{
//readonly Regex _issueRegex = new Regex(" - (?<Issue>.*?)(?<IssueLink> \\[(?<IssueId>.*?)\\]\\((?<IssueUrl>.*?)\\))*( *\\+(?<Tag>[^ \\+]*))*", RegexOptions.Compiled);
static readonly Regex ReleaseRegex = new Regex("# (?<Title>.*?)( \\((?<Date>.*?)\\))?$", RegexOptions.Compiled);
static readonly Regex LinkRegex = new Regex(@"\[(?<Text>.*?)\]\((?<Link>.*?)\)$", RegexOptions.Compiled);
readonly Categories categories;
public SemanticReleaseNotes()
{
categories = new Categories();
Releases = new SemanticRelease[0];
}
public SemanticReleaseNotes(IEnumerable<SemanticRelease> releaseNoteItems, Categories categories)
{
this.categories = categories;
Releases = releaseNoteItems.ToArray();
}
public SemanticRelease[] Releases { get; private set; }
public override string ToString()
{
var builder = new StringBuilder();
var index = 0;
foreach (var release in Releases)
{
if (release.ReleaseNoteLines.Count == 0)
{
continue;
}
if (index++ > 0)
{
builder.AppendLine();
builder.AppendLine();
}
if (Releases.Length > 1)
{
var hasBeenReleased = String.IsNullOrEmpty(release.ReleaseName);
if (hasBeenReleased)
{
builder.AppendLine("# vNext");
}
else if (release.When != null)
{
builder.AppendLine(string.Format("# {0} ({1:dd MMMM yyyy})", release.ReleaseName,
release.When.Value.Date));
}
else
{
builder.AppendLine(string.Format("# {0}", release.ReleaseName));
}
builder.AppendLine();
}
IEnumerable<IReleaseNoteLine> releaseNoteItems = release.ReleaseNoteLines;
foreach (var releaseNoteItem in releaseNoteItems)
{
builder.AppendLine(releaseNoteItem.ToString(categories));
}
builder.AppendLine();
if (string.IsNullOrEmpty(release.DiffInfo.DiffUrlFormat))
{
builder.AppendLine(string.Format("Commits: {0}...{1}", release.DiffInfo.BeginningSha, release.DiffInfo.EndSha));
}
else
{
builder.AppendLine(string.Format("Commits: [{0}...{1}]({2})",
release.DiffInfo.BeginningSha, release.DiffInfo.EndSha,
string.Format(release.DiffInfo.DiffUrlFormat, release.DiffInfo.BeginningSha, release.DiffInfo.EndSha)));
}
}
return builder.ToString();
}
public static SemanticReleaseNotes Parse(string releaseNotes)
{
var releases = new List<SemanticRelease>();
var lines = releaseNotes.Replace("\r", string.Empty).Split('\n');
var currentRelease = new SemanticRelease();
foreach (var line in lines)
{
if (line.TrimStart().StartsWith("# "))
{
var match = ReleaseRegex.Match(line);
if (line != lines.First())
{
releases.Add(currentRelease);
}
currentRelease = new SemanticRelease
{
ReleaseName = match.Groups["Title"].Value
};
if (currentRelease.ReleaseName == "vNext")
{
currentRelease.ReleaseName = null;
}
if (match.Groups["Date"].Success)
{
DateTime parsed;
var toParse = match.Groups["Date"].Value;
if (DateTime.TryParse(toParse, out parsed))
{
currentRelease.When = parsed;
}
if (DateTime.TryParseExact(toParse, "dd MMMM yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
currentRelease.When = parsed;
}
else if (DateTime.TryParseExact(toParse, "MMMM dd, yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
currentRelease.When = parsed;
}
else
{
// We failed to parse the date, just append to the end
currentRelease.ReleaseName += " (" + toParse + ")";
}
}
}
else if (line.StartsWith("Commits: "))
{
var commitText = line.Replace("Commits: ", string.Empty);
var linkMatch = LinkRegex.Match(commitText);
if (linkMatch.Success)
{
commitText = linkMatch.Groups["Text"].Value;
currentRelease.DiffInfo.DiffUrlFormat = linkMatch.Groups["Link"].Value;
}
var commits = commitText.Split(new[] { "..." }, StringSplitOptions.None);
currentRelease.DiffInfo.BeginningSha = commits[0];
currentRelease.DiffInfo.EndSha = commits[1];
}
else if (line.StartsWith(" - "))
{
// Improve this parsing to extract issue numbers etc
var title = line.StartsWith(" - ") ? line.Substring(3) : line;
var releaseNoteItem = new ReleaseNoteItem(title, null, null, null, currentRelease.When, new Contributor[0]);
currentRelease.ReleaseNoteLines.Add(releaseNoteItem);
}
else if (string.IsNullOrWhiteSpace(line))
{
currentRelease.ReleaseNoteLines.Add(new BlankLine());
}
else
{
// This picks up comments and such
var title = line.StartsWith(" - ") ? line.Substring(3) : line;
var releaseNoteItem = new ReleaseNoteLine(title);
currentRelease.ReleaseNoteLines.Add(releaseNoteItem);
}
}
releases.Add(currentRelease);
// Remove additional blank lines
foreach (var semanticRelease in releases)
{
for (int i = 0; i < semanticRelease.ReleaseNoteLines.Count; i++)
{
if (semanticRelease.ReleaseNoteLines[i] is BlankLine)
{
semanticRelease.ReleaseNoteLines.RemoveAt(i--);
}
else
{
break;
}
}
for (int i = semanticRelease.ReleaseNoteLines.Count - 1; i >= 0; i--)
{
if (semanticRelease.ReleaseNoteLines[i] is BlankLine)
{
semanticRelease.ReleaseNoteLines.RemoveAt(i);
}
else
{
break;
}
}
}
return new SemanticReleaseNotes(releases, new Categories());
}
public SemanticReleaseNotes Merge(SemanticReleaseNotes previousReleaseNotes)
{
var semanticReleases = previousReleaseNotes.Releases
.Where(r => Releases.All(r2 => r.ReleaseName != r2.ReleaseName))
.Select(CreateMergedSemanticRelease);
var enumerable = Releases.Select(CreateMergedSemanticRelease);
var mergedReleases =
enumerable
.Union(semanticReleases)
.ToArray();
foreach (var semanticRelease in mergedReleases)
{
var releaseFromThis = Releases.SingleOrDefault(r => r.ReleaseName == semanticRelease.ReleaseName);
var releaseFromPrevious = previousReleaseNotes.Releases.SingleOrDefault(r => r.ReleaseName == semanticRelease.ReleaseName);
if (releaseFromThis != null)
{
semanticRelease.ReleaseNoteLines.AddRange(releaseFromThis.ReleaseNoteLines);
}
if (releaseFromPrevious != null)
{
semanticRelease.ReleaseNoteLines.AddRange(releaseFromPrevious.ReleaseNoteLines);
}
}
return new SemanticReleaseNotes(mergedReleases, new Categories(categories.AvailableCategories.Union(previousReleaseNotes.categories.AvailableCategories).Distinct().ToArray(), categories.AllLabels));
}
private static SemanticRelease CreateMergedSemanticRelease(SemanticRelease r)
{
return new SemanticRelease(r.ReleaseName, r.When, new List<IReleaseNoteLine>(), r.DiffInfo);
}
}
}
| |
//
// 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 System;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
static partial class Mixin {
public const int TableCount = 58;
public const int CodedIndexCount = 14;
public static uint ReadCompressedUInt32 (this byte [] data, ref int position)
{
uint integer;
if ((data [position] & 0x80) == 0) {
integer = data [position];
position++;
} else if ((data [position] & 0x40) == 0) {
integer = (uint) (data [position] & ~0x80) << 8;
integer |= data [position + 1];
position += 2;
} else {
integer = (uint) (data [position] & ~0xc0) << 24;
integer |= (uint) data [position + 1] << 16;
integer |= (uint) data [position + 2] << 8;
integer |= (uint) data [position + 3];
position += 4;
}
return integer;
}
public static MetadataToken GetMetadataToken (this CodedIndex self, uint data)
{
uint rid;
TokenType token_type;
switch (self) {
case CodedIndex.TypeDefOrRef:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.TypeRef; goto ret;
case 2:
token_type = TokenType.TypeSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasConstant:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Param; goto ret;
case 2:
token_type = TokenType.Property; goto ret;
default:
goto exit;
}
case CodedIndex.HasCustomAttribute:
rid = data >> 5;
switch (data & 31) {
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.Field; goto ret;
case 2:
token_type = TokenType.TypeRef; goto ret;
case 3:
token_type = TokenType.TypeDef; goto ret;
case 4:
token_type = TokenType.Param; goto ret;
case 5:
token_type = TokenType.InterfaceImpl; goto ret;
case 6:
token_type = TokenType.MemberRef; goto ret;
case 7:
token_type = TokenType.Module; goto ret;
case 8:
token_type = TokenType.Permission; goto ret;
case 9:
token_type = TokenType.Property; goto ret;
case 10:
token_type = TokenType.Event; goto ret;
case 11:
token_type = TokenType.Signature; goto ret;
case 12:
token_type = TokenType.ModuleRef; goto ret;
case 13:
token_type = TokenType.TypeSpec; goto ret;
case 14:
token_type = TokenType.Assembly; goto ret;
case 15:
token_type = TokenType.AssemblyRef; goto ret;
case 16:
token_type = TokenType.File; goto ret;
case 17:
token_type = TokenType.ExportedType; goto ret;
case 18:
token_type = TokenType.ManifestResource; goto ret;
case 19:
token_type = TokenType.GenericParam; goto ret;
case 20:
token_type = TokenType.GenericParamConstraint; goto ret;
case 21:
token_type = TokenType.MethodSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasFieldMarshal:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Param; goto ret;
default:
goto exit;
}
case CodedIndex.HasDeclSecurity:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
case 2:
token_type = TokenType.Assembly; goto ret;
default:
goto exit;
}
case CodedIndex.MemberRefParent:
rid = data >> 3;
switch (data & 7) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.TypeRef; goto ret;
case 2:
token_type = TokenType.ModuleRef; goto ret;
case 3:
token_type = TokenType.Method; goto ret;
case 4:
token_type = TokenType.TypeSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasSemantics:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Event; goto ret;
case 1:
token_type = TokenType.Property; goto ret;
default:
goto exit;
}
case CodedIndex.MethodDefOrRef:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.MemberRef; goto ret;
default:
goto exit;
}
case CodedIndex.MemberForwarded:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
default:
goto exit;
}
case CodedIndex.Implementation:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.File; goto ret;
case 1:
token_type = TokenType.AssemblyRef; goto ret;
case 2:
token_type = TokenType.ExportedType; goto ret;
default:
goto exit;
}
case CodedIndex.CustomAttributeType:
rid = data >> 3;
switch (data & 7) {
case 2:
token_type = TokenType.Method; goto ret;
case 3:
token_type = TokenType.MemberRef; goto ret;
default:
goto exit;
}
case CodedIndex.ResolutionScope:
rid = data >> 2;
switch (data & 3) {
case 0:
token_type = TokenType.Module; goto ret;
case 1:
token_type = TokenType.ModuleRef; goto ret;
case 2:
token_type = TokenType.AssemblyRef; goto ret;
case 3:
token_type = TokenType.TypeRef; goto ret;
default:
goto exit;
}
case CodedIndex.TypeOrMethodDef:
rid = data >> 1;
switch (data & 1) {
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
default: goto exit;
}
case CodedIndex.HasCustomDebugInformation:
rid = data >> 5;
switch (data & 31) {
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.Field; goto ret;
case 2:
token_type = TokenType.TypeRef; goto ret;
case 3:
token_type = TokenType.TypeDef; goto ret;
case 4:
token_type = TokenType.Param; goto ret;
case 5:
token_type = TokenType.InterfaceImpl; goto ret;
case 6:
token_type = TokenType.MemberRef; goto ret;
case 7:
token_type = TokenType.Module; goto ret;
case 8:
token_type = TokenType.Permission; goto ret;
case 9:
token_type = TokenType.Property; goto ret;
case 10:
token_type = TokenType.Event; goto ret;
case 11:
token_type = TokenType.Signature; goto ret;
case 12:
token_type = TokenType.ModuleRef; goto ret;
case 13:
token_type = TokenType.TypeSpec; goto ret;
case 14:
token_type = TokenType.Assembly; goto ret;
case 15:
token_type = TokenType.AssemblyRef; goto ret;
case 16:
token_type = TokenType.File; goto ret;
case 17:
token_type = TokenType.ExportedType; goto ret;
case 18:
token_type = TokenType.ManifestResource; goto ret;
case 19:
token_type = TokenType.GenericParam; goto ret;
case 20:
token_type = TokenType.GenericParamConstraint; goto ret;
case 21:
token_type = TokenType.MethodSpec; goto ret;
case 22:
token_type = TokenType.Document; goto ret;
case 23:
token_type = TokenType.LocalScope; goto ret;
case 24:
token_type = TokenType.LocalVariable; goto ret;
case 25:
token_type = TokenType.LocalConstant; goto ret;
case 26:
token_type = TokenType.ImportScope; goto ret;
default:
goto exit;
}
default:
goto exit;
}
ret:
return new MetadataToken (token_type, rid);
exit:
return MetadataToken.Zero;
}
#if !READ_ONLY
public static uint CompressMetadataToken (this CodedIndex self, MetadataToken token)
{
uint ret = 0;
if (token.RID == 0)
return ret;
switch (self) {
case CodedIndex.TypeDefOrRef:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.TypeRef:
return ret | 1;
case TokenType.TypeSpec:
return ret | 2;
default:
goto exit;
}
case CodedIndex.HasConstant:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Field:
return ret | 0;
case TokenType.Param:
return ret | 1;
case TokenType.Property:
return ret | 2;
default:
goto exit;
}
case CodedIndex.HasCustomAttribute:
ret = token.RID << 5;
switch (token.TokenType) {
case TokenType.Method:
return ret | 0;
case TokenType.Field:
return ret | 1;
case TokenType.TypeRef:
return ret | 2;
case TokenType.TypeDef:
return ret | 3;
case TokenType.Param:
return ret | 4;
case TokenType.InterfaceImpl:
return ret | 5;
case TokenType.MemberRef:
return ret | 6;
case TokenType.Module:
return ret | 7;
case TokenType.Permission:
return ret | 8;
case TokenType.Property:
return ret | 9;
case TokenType.Event:
return ret | 10;
case TokenType.Signature:
return ret | 11;
case TokenType.ModuleRef:
return ret | 12;
case TokenType.TypeSpec:
return ret | 13;
case TokenType.Assembly:
return ret | 14;
case TokenType.AssemblyRef:
return ret | 15;
case TokenType.File:
return ret | 16;
case TokenType.ExportedType:
return ret | 17;
case TokenType.ManifestResource:
return ret | 18;
case TokenType.GenericParam:
return ret | 19;
case TokenType.GenericParamConstraint:
return ret | 20;
case TokenType.MethodSpec:
return ret | 21;
default:
goto exit;
}
case CodedIndex.HasFieldMarshal:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field:
return ret | 0;
case TokenType.Param:
return ret | 1;
default:
goto exit;
}
case CodedIndex.HasDeclSecurity:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.Method:
return ret | 1;
case TokenType.Assembly:
return ret | 2;
default:
goto exit;
}
case CodedIndex.MemberRefParent:
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.TypeRef:
return ret | 1;
case TokenType.ModuleRef:
return ret | 2;
case TokenType.Method:
return ret | 3;
case TokenType.TypeSpec:
return ret | 4;
default:
goto exit;
}
case CodedIndex.HasSemantics:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Event:
return ret | 0;
case TokenType.Property:
return ret | 1;
default:
goto exit;
}
case CodedIndex.MethodDefOrRef:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Method:
return ret | 0;
case TokenType.MemberRef:
return ret | 1;
default:
goto exit;
}
case CodedIndex.MemberForwarded:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.Field:
return ret | 0;
case TokenType.Method:
return ret | 1;
default:
goto exit;
}
case CodedIndex.Implementation:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.File:
return ret | 0;
case TokenType.AssemblyRef:
return ret | 1;
case TokenType.ExportedType:
return ret | 2;
default:
goto exit;
}
case CodedIndex.CustomAttributeType:
ret = token.RID << 3;
switch (token.TokenType) {
case TokenType.Method:
return ret | 2;
case TokenType.MemberRef:
return ret | 3;
default:
goto exit;
}
case CodedIndex.ResolutionScope:
ret = token.RID << 2;
switch (token.TokenType) {
case TokenType.Module:
return ret | 0;
case TokenType.ModuleRef:
return ret | 1;
case TokenType.AssemblyRef:
return ret | 2;
case TokenType.TypeRef:
return ret | 3;
default:
goto exit;
}
case CodedIndex.TypeOrMethodDef:
ret = token.RID << 1;
switch (token.TokenType) {
case TokenType.TypeDef:
return ret | 0;
case TokenType.Method:
return ret | 1;
default:
goto exit;
}
case CodedIndex.HasCustomDebugInformation:
ret = token.RID << 5;
switch (token.TokenType) {
case TokenType.Method:
return ret | 0;
case TokenType.Field:
return ret | 1;
case TokenType.TypeRef:
return ret | 2;
case TokenType.TypeDef:
return ret | 3;
case TokenType.Param:
return ret | 4;
case TokenType.InterfaceImpl:
return ret | 5;
case TokenType.MemberRef:
return ret | 6;
case TokenType.Module:
return ret | 7;
case TokenType.Permission:
return ret | 8;
case TokenType.Property:
return ret | 9;
case TokenType.Event:
return ret | 10;
case TokenType.Signature:
return ret | 11;
case TokenType.ModuleRef:
return ret | 12;
case TokenType.TypeSpec:
return ret | 13;
case TokenType.Assembly:
return ret | 14;
case TokenType.AssemblyRef:
return ret | 15;
case TokenType.File:
return ret | 16;
case TokenType.ExportedType:
return ret | 17;
case TokenType.ManifestResource:
return ret | 18;
case TokenType.GenericParam:
return ret | 19;
case TokenType.GenericParamConstraint:
return ret | 20;
case TokenType.MethodSpec:
return ret | 21;
case TokenType.Document:
return ret | 22;
case TokenType.LocalScope:
return ret | 23;
case TokenType.LocalVariable:
return ret | 24;
case TokenType.LocalConstant:
return ret | 25;
case TokenType.ImportScope:
return ret | 26;
default:
goto exit;
}
default:
goto exit;
}
exit:
throw new ArgumentException ();
}
#endif
public static int GetSize (this CodedIndex self, Func<Table, int> counter)
{
int bits;
Table [] tables;
switch (self) {
case CodedIndex.TypeDefOrRef:
bits = 2;
tables = new [] { Table.TypeDef, Table.TypeRef, Table.TypeSpec };
break;
case CodedIndex.HasConstant:
bits = 2;
tables = new [] { Table.Field, Table.Param, Table.Property };
break;
case CodedIndex.HasCustomAttribute:
bits = 5;
tables = new [] {
Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,
Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,
Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,
Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec,
};
break;
case CodedIndex.HasFieldMarshal:
bits = 1;
tables = new [] { Table.Field, Table.Param };
break;
case CodedIndex.HasDeclSecurity:
bits = 2;
tables = new [] { Table.TypeDef, Table.Method, Table.Assembly };
break;
case CodedIndex.MemberRefParent:
bits = 3;
tables = new [] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec };
break;
case CodedIndex.HasSemantics:
bits = 1;
tables = new [] { Table.Event, Table.Property };
break;
case CodedIndex.MethodDefOrRef:
bits = 1;
tables = new [] { Table.Method, Table.MemberRef };
break;
case CodedIndex.MemberForwarded:
bits = 1;
tables = new [] { Table.Field, Table.Method };
break;
case CodedIndex.Implementation:
bits = 2;
tables = new [] { Table.File, Table.AssemblyRef, Table.ExportedType };
break;
case CodedIndex.CustomAttributeType:
bits = 3;
tables = new [] { Table.Method, Table.MemberRef };
break;
case CodedIndex.ResolutionScope:
bits = 2;
tables = new [] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef };
break;
case CodedIndex.TypeOrMethodDef:
bits = 1;
tables = new [] { Table.TypeDef, Table.Method };
break;
case CodedIndex.HasCustomDebugInformation:
bits = 5;
tables = new[] {
Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,
Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,
Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,
Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec,
Table.Document, Table.LocalScope, Table.LocalVariable, Table.LocalConstant, Table.ImportScope,
};
break;
default:
throw new ArgumentException ();
}
int max = 0;
for (int i = 0; i < tables.Length; i++) {
max = System.Math.Max (counter (tables [i]), max);
}
return max < (1 << (16 - bits)) ? 2 : 4;
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class EnvelopeTemplateResults : IEquatable<EnvelopeTemplateResults>
{
/// <summary>
/// The list of requested templates.
/// </summary>
/// <value>The list of requested templates.</value>
[DataMember(Name="envelopeTemplates", EmitDefaultValue=false)]
public List<EnvelopeTemplateResult> EnvelopeTemplates { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response.</value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set.</value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the `resultSetSize` property.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.</value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="folders", EmitDefaultValue=false)]
public List<Folder> Folders { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class EnvelopeTemplateResults {\n");
sb.Append(" EnvelopeTemplates: ").Append(EnvelopeTemplates).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" Folders: ").Append(Folders).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as EnvelopeTemplateResults);
}
/// <summary>
/// Returns true if EnvelopeTemplateResults instances are equal
/// </summary>
/// <param name="other">Instance of EnvelopeTemplateResults to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(EnvelopeTemplateResults other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.EnvelopeTemplates == other.EnvelopeTemplates ||
this.EnvelopeTemplates != null &&
this.EnvelopeTemplates.SequenceEqual(other.EnvelopeTemplates)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.Folders == other.Folders ||
this.Folders != null &&
this.Folders.SequenceEqual(other.Folders)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.EnvelopeTemplates != null)
hash = hash * 57 + this.EnvelopeTemplates.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 57 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 57 + this.StartPosition.GetHashCode();
if (this.EndPosition != null)
hash = hash * 57 + this.EndPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 57 + this.TotalSetSize.GetHashCode();
if (this.NextUri != null)
hash = hash * 57 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 57 + this.PreviousUri.GetHashCode();
if (this.Folders != null)
hash = hash * 57 + this.Folders.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Logging;
using Orleans.AzureUtils.Utilities;
using Orleans.Configuration;
using Orleans.Hosting.AzureCloudServices;
using Orleans.Hosting;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
[Obsolete("This type is obsolete and may be removed in a future release. Use SiloHostBuilder to create an instance of ISiloHost instead.")]
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
/// <summary>delegate to add some configuration to the client</summary>
public Action<ISiloHostBuilder> ConfigureSiloHostDelegate { get; set; }
private SiloHost host;
private readonly ILogger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper;
//TODO: hook this up with SiloBuilder when SiloBuilder supports create AzureSilo
private static ILoggerFactory DefaultLoggerFactory = CreateDefaultLoggerFactory("AzureSilo.log");
private readonly ILoggerFactory loggerFactory = DefaultLoggerFactory;
public AzureSilo()
:this(new ServiceRuntimeWrapper(DefaultLoggerFactory), DefaultLoggerFactory)
{
}
/// <summary>
/// Constructor
/// </summary>
public AzureSilo(ILoggerFactory loggerFactory)
: this(new ServiceRuntimeWrapper(loggerFactory), loggerFactory)
{
}
public static ILoggerFactory CreateDefaultLoggerFactory(string filePath)
{
var factory = new LoggerFactory();
factory.AddProvider(new FileLoggerProvider(filePath));
if (ConsoleText.IsConsoleAvailable)
factory.AddConsole();
return factory;
}
internal AzureSilo(IServiceRuntimeWrapper serviceRuntimeWrapper, ILoggerFactory loggerFactory)
{
this.serviceRuntimeWrapper = serviceRuntimeWrapper;
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
this.loggerFactory = loggerFactory;
logger = loggerFactory.CreateLogger<AzureSilo>();
}
/// <summary>
/// Async method to validate specific cluster configuration
/// </summary>
/// <param name="config"></param>
/// <returns>Task object of boolean type for this async method </returns>
public async Task<bool> ValidateConfiguration(ClusterConfiguration config)
{
if (config.Globals.LivenessType == GlobalConfiguration.LivenessProviderType.AzureTable)
{
string clusterId = config.Globals.ClusterId ?? serviceRuntimeWrapper.DeploymentId;
string connectionString = config.Globals.DataConnectionString ??
serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
var manager = await OrleansSiloInstanceManager.GetManager(clusterId, connectionString, AzureStorageClusteringOptions.DEFAULT_TABLE_NAME, loggerFactory);
var instances = await manager.DumpSiloInstanceTable();
logger.Debug(instances);
}
catch (Exception exc)
{
var error = String.Format("Connecting to the storage table has failed with {0}", LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error((int)AzureSiloErrorCode.AzureTable_34, error, exc);
return false;
}
}
return true;
}
/// <summary>
/// Default cluster configuration
/// </summary>
/// <returns>Default ClusterConfiguration </returns>
public static ClusterConfiguration DefaultConfiguration()
{
return DefaultConfiguration(new ServiceRuntimeWrapper(DefaultLoggerFactory));
}
internal static ClusterConfiguration DefaultConfiguration(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.ClusterId = serviceRuntimeWrapper.DeploymentId;
try
{
config.Globals.DataConnectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
catch (Exception exc)
{
if (exc.GetType().Name.Contains("RoleEnvironmentException"))
{
config.Globals.DataConnectionString = null;
}
else
{
throw;
}
}
return config;
}
/// <summary>
/// Initialize this Orleans silo for execution. Config data will be read from silo config file as normal
/// </summary>
/// <param name="deploymentId">Azure ClusterId this silo is running under. If null, defaults to the value from the configuration.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(string deploymentId = null, string connectionString = null)
{
return Start(null, deploymentId, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <param name="config">Use the specified config data.</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string connectionString = null)
{
if (config == null)
throw new ArgumentNullException(nameof(config));
return Start(config, null, connectionString);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure clusterId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="clusterId">Azure ClusterId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> if the silo startup was successful</returns>
internal bool Start(ClusterConfiguration config, string clusterId, string connectionString)
{
if (config != null && clusterId != null)
throw new ArgumentException("Cannot use config and clusterId on the same time");
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
// If clusterId was not direclty provided, take the value in the config. If it is not
// in the config too, just take the ClusterId from Azure
if (clusterId == null)
clusterId = string.IsNullOrWhiteSpace(host.Config.Globals.ClusterId)
? serviceRuntimeWrapper.DeploymentId
: host.Config.Globals.ClusterId;
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
// Initialize this Orleans silo instance
host.SetDeploymentId(clusterId, connectionString);
host.SetSiloEndpoint(myEndpoint, 0);
host.SetProxyEndpoint(proxyEndpoint);
host.ConfigureSiloHostDelegate = ConfigureSiloHostDelegate;
host.InitializeSilo();
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping);
host.ShutdownSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForSiloShutdown(cancellationToken.Value);
else
host.WaitForSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
namespace Microsoft.DotNet.CodeFormatting
{
internal sealed partial class FormattingEngineImplementation : IFormattingEngine
{
/// <summary>
/// Developers who want to opt out of the code formatter for items like unicode
/// tables can surround them with #if !DOTNET_FORMATTER.
/// </summary>
internal const string TablePreprocessorSymbolName = "DOTNET_FORMATTER";
private readonly FormattingOptions _options;
private readonly IEnumerable<CodeFixProvider> _fixers;
private readonly IEnumerable<IFormattingFilter> _filters;
private readonly IEnumerable<DiagnosticAnalyzer> _analyzers;
private readonly IEnumerable<IOptionsProvider> _optionsProviders;
private readonly IEnumerable<ExportFactory<ISyntaxFormattingRule, SyntaxRule>> _syntaxRules;
private readonly IEnumerable<ExportFactory<ILocalSemanticFormattingRule, LocalSemanticRule>> _localSemanticRules;
private readonly IEnumerable<ExportFactory<IGlobalSemanticFormattingRule, GlobalSemanticRule>> _globalSemanticRules;
private readonly Stopwatch _watch = new Stopwatch();
private readonly Dictionary<string, bool> _ruleEnabledMap = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private readonly ImmutableDictionary<string, CodeFixProvider> _diagnosticIdToFixerMap;
public ImmutableArray<string> CopyrightHeader
{
get { return _options.CopyrightHeader; }
set { _options.CopyrightHeader = value; }
}
public ImmutableArray<string[]> PreprocessorConfigurations
{
get { return _options.PreprocessorConfigurations; }
set { _options.PreprocessorConfigurations = value; }
}
public ImmutableArray<string> FileNames
{
get { return _options.FileNames; }
set { _options.FileNames = value; }
}
public IFormatLogger FormatLogger
{
get { return _options.FormatLogger; }
set { _options.FormatLogger = value; }
}
public bool AllowTables { get; set; }
public bool Verbose { get; set; }
public string FormattingOptionsFilePath { get; set; }
public ImmutableArray<IRuleMetadata> AllRules
{
get
{
var list = new List<IRuleMetadata>();
list.AddRange(_syntaxRules.Select(x => x.Metadata));
list.AddRange(_localSemanticRules.Select(x => x.Metadata));
list.AddRange(_globalSemanticRules.Select(x => x.Metadata));
return list.ToImmutableArray();
}
}
public ImmutableArray<DiagnosticDescriptor> AllSupportedDiagnostics
=> _analyzers
.SelectMany(a => a.SupportedDiagnostics)
.OrderBy(a => a.Id)
.ToImmutableArray();
public FormattingEngineImplementation(
FormattingOptions options,
IEnumerable<IFormattingFilter> filters,
IEnumerable<DiagnosticAnalyzer> analyzers,
IEnumerable<CodeFixProvider> fixers,
IEnumerable<ExportFactory<ISyntaxFormattingRule, SyntaxRule>> syntaxRules,
IEnumerable<ExportFactory<ILocalSemanticFormattingRule, LocalSemanticRule>> localSemanticRules,
IEnumerable<ExportFactory<IGlobalSemanticFormattingRule, GlobalSemanticRule>> globalSemanticRules,
IEnumerable<IOptionsProvider> optionProviders)
{
_options = options;
_filters = filters;
_analyzers = analyzers;
_fixers = fixers;
_syntaxRules = syntaxRules;
_optionsProviders = optionProviders;
_localSemanticRules = localSemanticRules;
_globalSemanticRules = globalSemanticRules;
Debug.Assert(options.CopyrightHeader != null);
foreach (var rule in AllRules)
{
_ruleEnabledMap[rule.Name] = rule.DefaultRule;
}
_diagnosticIdToFixerMap = CreateDiagnosticIdToFixerMap();
}
private IEnumerable<TRule> GetOrderedRules<TRule, TMetadata>(IEnumerable<ExportFactory<TRule, TMetadata>> rules)
where TRule : IFormattingRule
where TMetadata : IRuleMetadata
{
return rules
.OrderBy(r => r.Metadata.Order)
.Where(r => _ruleEnabledMap[r.Metadata.Name])
.Select(r => r.CreateExport().Value);
}
private ImmutableDictionary<string, CodeFixProvider> CreateDiagnosticIdToFixerMap()
{
var diagnosticIdToFixerMap = ImmutableDictionary.CreateBuilder<string, CodeFixProvider>();
foreach (var fixer in _fixers)
{
var supportedDiagnosticIds = fixer.FixableDiagnosticIds;
foreach (var id in supportedDiagnosticIds)
{
diagnosticIdToFixerMap.Add(id, fixer);
}
}
return diagnosticIdToFixerMap.ToImmutable();
}
public async Task FormatSolutionAsync(Solution solution, bool useAnalyzers, CancellationToken cancellationToken)
{
if (useAnalyzers)
{
await FormatSolutionWithAnalyzersAsync(solution, cancellationToken).ConfigureAwait(false);
}
else
{
await FormatSolutionWithRulesAsync(solution, cancellationToken).ConfigureAwait(false);
}
}
public async Task FormatProjectAsync(Project project, bool useAnalyzers, CancellationToken cancellationToken)
{
if (useAnalyzers)
{
await FormatProjectWithAnalyzersAsync(project, cancellationToken).ConfigureAwait(false);
}
else
{
await FormatProjectWithRulesAsync(project, cancellationToken).ConfigureAwait(false);
}
}
public async Task FormatSolutionWithRulesAsync(Solution solution, CancellationToken cancellationToken)
{
var documentIds = solution.Projects.SelectMany(x => x.DocumentIds).ToList();
await FormatAsync(solution.Workspace, documentIds, cancellationToken).ConfigureAwait(false);
}
public async Task FormatProjectWithRulesAsync(Project project, CancellationToken cancellationToken)
{
await FormatAsync(project.Solution.Workspace, project.DocumentIds, cancellationToken).ConfigureAwait(false);
}
public async Task FormatSolutionWithAnalyzersAsync(Solution solution, CancellationToken cancellationToken)
{
foreach (var project in solution.Projects)
{
await FormatProjectWithAnalyzersAsync(project, cancellationToken).ConfigureAwait(false);
}
}
public async Task FormatProjectWithAnalyzersAsync(Project project, CancellationToken cancellationToken)
{
if (!project.Documents.Any())
{
FormatLogger.WriteLine($"Skipping {project.Name}: no files to format.");
return;
}
var watch = new Stopwatch();
watch.Start();
var diagnostics = await GetDiagnostics(project, cancellationToken).ConfigureAwait(false);
var batchFixer = WellKnownFixAllProviders.BatchFixer;
var context = new FixAllContext(
project.Documents.First(), // TODO: Shouldn't this be the whole project?
new UberCodeFixer(_diagnosticIdToFixerMap),
FixAllScope.Project,
null,
diagnostics.Select(d => d.Id),
new FormattingEngineDiagnosticProvider(project, diagnostics),
cancellationToken);
var fix = await batchFixer.GetFixAsync(context).ConfigureAwait(false);
if (fix != null)
{
foreach (var operation in await fix.GetOperationsAsync(cancellationToken).ConfigureAwait(false))
{
operation.Apply(project.Solution.Workspace, cancellationToken);
}
}
watch.Stop();
FormatLogger.WriteLine("Total time {0}", watch.Elapsed);
}
public void ToggleRuleEnabled(IRuleMetadata ruleMetaData, bool enabled)
{
_ruleEnabledMap[ruleMetaData.Name] = enabled;
}
private async Task FormatAsync(Workspace workspace, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
var watch = new Stopwatch();
watch.Start();
var originalSolution = workspace.CurrentSolution;
var solution = await FormatCoreAsync(originalSolution, documentIds, cancellationToken).ConfigureAwait(false);
watch.Stop();
if (!workspace.TryApplyChanges(solution))
{
FormatLogger.WriteErrorLine("Unable to save changes to disk");
}
FormatLogger.WriteLine("Total time {0}", watch.Elapsed);
}
private Solution AddTablePreprocessorSymbol(Solution solution)
{
var projectIds = solution.ProjectIds;
foreach (var projectId in projectIds)
{
var project = solution.GetProject(projectId);
var parseOptions = project.ParseOptions as CSharpParseOptions;
if (parseOptions != null)
{
var list = new List<string>();
list.AddRange(parseOptions.PreprocessorSymbolNames);
list.Add(TablePreprocessorSymbolName);
parseOptions = parseOptions.WithPreprocessorSymbols(list);
solution = project.WithParseOptions(parseOptions).Solution;
}
}
return solution;
}
/// <summary>
/// Remove the added table preprocessor symbol. Don't want that saved into the project
/// file as a change.
/// </summary>
private Solution RemoveTablePreprocessorSymbol(Solution newSolution, Solution oldSolution)
{
var projectIds = newSolution.ProjectIds;
foreach (var projectId in projectIds)
{
var oldProject = oldSolution.GetProject(projectId);
var newProject = newSolution.GetProject(projectId);
newSolution = newProject.WithParseOptions(oldProject.ParseOptions).Solution;
}
return newSolution;
}
internal async Task<Solution> FormatCoreAsync(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
var solution = originalSolution;
if (AllowTables)
{
solution = AddTablePreprocessorSymbol(originalSolution);
}
solution = await RunSyntaxPass(solution, documentIds, cancellationToken).ConfigureAwait(false);
solution = await RunLocalSemanticPass(solution, documentIds, cancellationToken).ConfigureAwait(false);
solution = await RunGlobalSemanticPass(solution, documentIds, cancellationToken).ConfigureAwait(false);
if (AllowTables)
{
solution = RemoveTablePreprocessorSymbol(solution, originalSolution);
}
return solution;
}
private async Task<ImmutableArray<Diagnostic>> GetDiagnostics(Project project, CancellationToken cancellationToken)
{
AnalyzerOptions analyzerOptions = null;
if (!string.IsNullOrEmpty(FormattingOptionsFilePath))
{
var additionalTextFile = new AdditionalTextFile(FormattingOptionsFilePath);
analyzerOptions = new AnalyzerOptions(new AdditionalText[] { additionalTextFile }.ToImmutableArray());
}
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
IEnumerable<DiagnosticAnalyzer> analyzersToRun = _analyzers.Where(a => a.SupportsLanguage(project.Language));
if (analyzersToRun.Any())
{
var compilationWithAnalyzers = compilation.WithAnalyzers(analyzersToRun.ToImmutableArray(), analyzerOptions);
return await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().ConfigureAwait(false);
}
else
{
return ImmutableArray<Diagnostic>.Empty;
}
}
private bool ShouldBeProcessed(Document document)
{
foreach (var filter in _filters)
{
var shouldBeProcessed = filter.ShouldBeProcessed(document);
if (!shouldBeProcessed)
return false;
}
return true;
}
private Task<SyntaxNode> GetSyntaxRootAndFilter(Document document, CancellationToken cancellationToken)
{
if (!ShouldBeProcessed(document))
{
return Task.FromResult<SyntaxNode>(null);
}
return document.GetSyntaxRootAsync(cancellationToken);
}
private Task<SyntaxNode> GetSyntaxRootAndFilter(IFormattingRule formattingRule, Document document, CancellationToken cancellationToken)
{
if (!formattingRule.SupportsLanguage(document.Project.Language))
{
return Task.FromResult<SyntaxNode>(null);
}
return GetSyntaxRootAndFilter(document, cancellationToken);
}
private void StartDocument()
{
_watch.Restart();
}
private void EndDocument(Document document)
{
_watch.Stop();
if (Verbose)
{
FormatLogger.WriteLine(" {0} {1} seconds", document.Name, _watch.Elapsed.TotalSeconds);
}
}
/// <summary>
/// Semantics is not involved in this pass at all. It is just a straight modification of the
/// parse tree so there are no issues about ensuring the version of <see cref="SemanticModel"/> and
/// the <see cref="SyntaxNode"/> line up. Hence we do this by iterating every <see cref="Document"/>
/// and processing all rules against them at once
/// </summary>
private async Task<Solution> RunSyntaxPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tSyntax Pass");
var currentSolution = originalSolution;
foreach (var documentId in documentIds)
{
var document = originalSolution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(document, cancellationToken).ConfigureAwait(false);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
var newRoot = RunSyntaxPass(syntaxRoot, document.Project.Language);
EndDocument(document);
if (newRoot != syntaxRoot)
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(document.Id, newRoot);
}
}
return currentSolution;
}
private SyntaxNode RunSyntaxPass(SyntaxNode root, string languageName)
{
foreach (var rule in GetOrderedRules(_syntaxRules))
{
if (rule.SupportsLanguage(languageName))
{
root = rule.Process(root, languageName);
}
}
return root;
}
private async Task<Solution> RunLocalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tLocal Semantic Pass");
foreach (var localSemanticRule in GetOrderedRules(_localSemanticRules))
{
solution = await RunLocalSemanticPass(solution, documentIds, localSemanticRule, cancellationToken).ConfigureAwait(false);
}
return solution;
}
private async Task<Solution> RunLocalSemanticPass(Solution originalSolution, IReadOnlyList<DocumentId> documentIds, ILocalSemanticFormattingRule localSemanticRule, CancellationToken cancellationToken)
{
if (Verbose)
{
FormatLogger.WriteLine(" {0}", localSemanticRule.GetType().Name);
}
var currentSolution = originalSolution;
foreach (var documentId in documentIds)
{
var document = originalSolution.GetDocument(documentId);
if (!localSemanticRule.SupportsLanguage(document.Project.Language))
{
continue;
}
var syntaxRoot = await GetSyntaxRootAndFilter(localSemanticRule, document, cancellationToken).ConfigureAwait(false);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
var newRoot = await localSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken).ConfigureAwait(false);
EndDocument(document);
if (syntaxRoot != newRoot)
{
currentSolution = currentSolution.WithDocumentSyntaxRoot(documentId, newRoot);
}
}
return currentSolution;
}
private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, CancellationToken cancellationToken)
{
FormatLogger.WriteLine("\tGlobal Semantic Pass");
foreach (var globalSemanticRule in GetOrderedRules(_globalSemanticRules))
{
solution = await RunGlobalSemanticPass(solution, documentIds, globalSemanticRule, cancellationToken).ConfigureAwait(false);
}
return solution;
}
private async Task<Solution> RunGlobalSemanticPass(Solution solution, IReadOnlyList<DocumentId> documentIds, IGlobalSemanticFormattingRule globalSemanticRule, CancellationToken cancellationToken)
{
if (Verbose)
{
FormatLogger.WriteLine(" {0}", globalSemanticRule.GetType().Name);
}
foreach (var documentId in documentIds)
{
var document = solution.GetDocument(documentId);
var syntaxRoot = await GetSyntaxRootAndFilter(globalSemanticRule, document, cancellationToken).ConfigureAwait(false);
if (syntaxRoot == null)
{
continue;
}
StartDocument();
solution = await globalSemanticRule.ProcessAsync(document, syntaxRoot, cancellationToken).ConfigureAwait(false);
EndDocument(document);
}
return solution;
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// 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.Web;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using gov.va.medora.mdo;
using gov.va.medora.mdo.api;
using gov.va.medora.utils;
using gov.va.medora.mdws.dto;
namespace gov.va.medora.mdws
{
public class SitesLib
{
MySession mySession;
public SitesLib(MySession mySession)
{
this.mySession = mySession;
}
public RegionArray getVHA()
{
return new RegionArray(mySession.SiteTable.Regions);
}
public RegionTO getVISN(string regionId)
{
RegionTO region = new RegionTO();
if (String.IsNullOrEmpty(regionId))
{
region.fault = new FaultTO("No region specified", "Need to supply region ID");
return region;
}
int intRegionId = 0;
try
{
intRegionId = Convert.ToInt32(regionId);
}
catch (Exception exc)
{
region.fault = new FaultTO(exc, "Need to supply a numeric regiod ID");
}
if(region.fault != null)
{
return region;
}
foreach (Region r in mySession.SiteTable.Regions.Values)
{
if (r.Id == intRegionId)
{
return new RegionTO(r);
}
}
region.fault = new FaultTO("No region with specified region ID", "Supply a valid region ID");
return region;
}
public StateArray getVhaByStates()
{
if (mySession.SiteTable.States == null || mySession.SiteTable.States.Count == 0)
{
string filepath = mySession.MdwsConfiguration.ResourcesPath + MdwsConstants.STATES_FILE_NAME;
mySession.SiteTable.parseStateCityFile(filepath);
}
return new StateArray(mySession.SiteTable.States);
}
public SiteTO getSite(string sitecode)
{
SiteTO result = new SiteTO();
if (sitecode == "")
{
result.fault = new FaultTO("No sitecode!");
}
else if (sitecode.Length != 3 || !StringUtils.isNumeric(sitecode))
{
result.fault = new FaultTO("Invalid sitecode");
}
if (result.fault != null)
{
return result;
}
Site s = mySession.SiteTable.getSite(sitecode);
if (s == null)
{
result.fault = new FaultTO("No such site!");
return result;
}
return new SiteTO(s);
}
public StateArray getStates()
{
StateArray result = new StateArray();
try
{
gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao dao =
new gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao(mySession.MdwsConfiguration.SqlConnectionString);
State[] states = dao.getStates();
result = new StateArray(states);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public ZipcodeTO[] getCitiesInState(string stateAbbr)
{
gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao dao =
new gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao(mySession.MdwsConfiguration.SqlConnectionString);
ZipcodeTO[] result = new ZipcodeTO[1];
result[0] = new ZipcodeTO();
if (String.IsNullOrEmpty(stateAbbr))
{
result[0].fault = new FaultTO("Missing state abbreviation");
}
else if (stateAbbr.Length != 2)
{
result[0].fault = new FaultTO("Invalid state abbreviation", "Please supply a valid 2 letter abbreviation");
}
if (result[0].fault != null)
{
return result;
}
try
{
Zipcode[] zips = dao.getCitiesInState(stateAbbr);
IndexedHashtable t = new IndexedHashtable();
for (int i = 0; i < zips.Length; i++)
{
if (!t.ContainsKey(zips[i].City))
{
t.Add(zips[i].City, zips[i]);
}
}
result = new ZipcodeTO[t.Count];
for (int i = 0; i < t.Count; i++)
{
result[i] = new ZipcodeTO((Zipcode)t.GetValue(i));
}
}
catch (Exception exc)
{
result[0].fault = new FaultTO(exc);
}
return result;
}
public TextTO getZipcodeForCity(string city, string stateAbbr)
{
TextTO result = new TextTO();
if (city == "")
{
result.fault = new FaultTO("Missing city");
}
else if (stateAbbr == "")
{
result.fault = new FaultTO("Missing stateAbbr");
}
if (result.fault != null)
{
return result;
}
try
{
gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao dao =
new gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao(mySession.MdwsConfiguration.SqlConnectionString);
string zip = dao.getZipcode(city, stateAbbr);
result = new TextTO(zip);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public ClosestFacilityTO getNearestFacility(string city, string stateAbbr)
{
ClosestFacilityTO result = new ClosestFacilityTO();
if (city == "")
{
result.fault = new FaultTO("Missing city");
}
else if (!State.isValidAbbr(stateAbbr))
{
result.fault = new FaultTO("Invalid stateAbbr");
}
if (result.fault != null)
{
return result;
}
try
{
TextTO zipcode = getZipcodeForCity(city, stateAbbr);
if (zipcode.fault != null)
{
result.fault = zipcode.fault;
return result;
}
result = getNearestFacility(zipcode.text);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public string[] getVisnsForState(string stateAbbr)
{
if (mySession.SiteTable.VisnsByState == null)
{
mySession.SiteTable.parseVisnsByState(mySession.MdwsConfiguration.ResourcesPath + MdwsConstants.VISNS_BY_STATE_FILE_NAME);
}
return ((State)mySession.SiteTable.VisnsByState[stateAbbr.ToUpper()]).VisnIds;
}
public TaggedTextArray matchCityAndState(string city, string stateAbbr)
{
TaggedTextArray result = new TaggedTextArray();
if (city == "")
{
result.fault = new FaultTO("Missing city");
}
else if (stateAbbr == "")
{
result.fault = new FaultTO("Missing stateAbbr");
}
if (result.fault != null)
{
return result;
}
try
{
SitesApi api = new SitesApi();
string[] s = api.matchCityAndState(city, stateAbbr, mySession.MdwsConfiguration.SqlConnectionString);
result.results = new TaggedText[s.Length];
for (int i = 0; i < s.Length; i++)
{
string[] parts = StringUtils.split(s[i],StringUtils.CARET);
result.results[i] = new TaggedText(parts[0], parts[1]);
}
result.count = result.results.Length;
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public SiteArray getSitesForCounty(string fips)
{
SiteArray result = new SiteArray();
if (fips == "")
{
result.fault = new FaultTO("Missing fips");
}
if (result.fault != null)
{
return result;
}
try
{
SitesApi api = new SitesApi();
Site[] sites = api.getClosestFacilities(fips, mySession.MdwsConfiguration.SqlConnectionString);
result = new SiteArray(sites);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public ClosestFacilityTO getNearestFacility(string zipcode)
{
ClosestFacilityTO result = new ClosestFacilityTO();
if (zipcode == "")
{
result.fault = new FaultTO("Missing zipcode");
}
if (result.fault != null)
{
return result;
}
try
{
SitesApi api = new SitesApi();
ClosestFacility fac = api.getNearestFacility(zipcode, mySession.MdwsConfiguration.SqlConnectionString);
result = new ClosestFacilityTO(fac);
}
catch (Exception e)
{
result.fault = new FaultTO(e.Message);
}
return result;
}
public GeographicLocationArray getGeographicLocations(string zipcode)
{
GeographicLocationArray result = new GeographicLocationArray();
if (zipcode.Length != 5 || !StringUtils.isNumeric(zipcode))
{
result.fault = new FaultTO("Invalid zipcode: must be 5 numeric chars");
return result;
}
try
{
gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao dao =
new gov.va.medora.mdo.dao.sql.zipcodeDB.ZipcodeDao(mySession.MdwsConfiguration.SqlConnectionString);
GeographicLocation[] locations = dao.getGeographicLocations(zipcode);
result = new GeographicLocationArray(locations);
}
catch (Exception e)
{
result.fault = new FaultTO(e);
}
return result;
}
public SiteTO addSite(string id, string name, string datasource, string port, string modality, string protocol, string region)
{
SiteTO result = new SiteTO();
Site site = new Site();
DataSource source = new DataSource();
int iPort = 0;
int iRegion = 0;
if (!mySession.MdwsConfiguration.IsProduction)
{
result.fault = new FaultTO("You may not add data sources to non-production MDWS installations");
}
else if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(name) || String.IsNullOrEmpty(datasource) ||
String.IsNullOrEmpty(port) || String.IsNullOrEmpty(modality) || String.IsNullOrEmpty(protocol) ||
String.IsNullOrEmpty(region))
{
result.fault = new FaultTO("Must supply all parameters");
}
else if (mySession.SiteTable.Sites.ContainsKey(id))
{
result.fault = new FaultTO("That site id is in use", "Choose a different site id");
}
else if (!Int32.TryParse(port, out iPort))
{
result.fault = new FaultTO("Non-numeric port", "Provide a numeric value for the port");
}
else if (!Int32.TryParse(region, out iRegion))
{
result.fault = new FaultTO("Non-numeric region", "Provide a numeric value for the region");
}
else if (modality != "HIS")
{
result.fault = new FaultTO("Only HIS modality currently supported", "Use 'HIS' as your modality");
}
else if (protocol != "VISTA")
{
result.fault = new FaultTO("Only VISTA protocol currently supported", "Use 'VISTA' as your protocol");
}
if(result.fault != null)
{
return result;
}
source.Port = iPort;
source.Modality = modality;
source.Protocol = protocol;
source.Provider = datasource;
source.SiteId = new SiteId(id, name);
site.Sources = new DataSource[1];
site.Sources[0] = source;
site.RegionId = region;
site.Name = name;
site.Id = id;
if(!mySession.SiteTable.Regions.ContainsKey(iRegion))
{
Region r = new Region();
r.Id = iRegion;
r.Name = "Region " + region;
r.Sites = new ArrayList();
mySession.SiteTable.Regions.Add(iRegion, r);
}
((Region)mySession.SiteTable.Regions[iRegion]).Sites.Add(site);
mySession.SiteTable.Sites.Add(id, site);
mySession.SiteTable.Sources.Add(site.Sources[0]);
result = new SiteTO(site);
return result;
}
public SiteArray getConnectedSites()
{
if (mySession.ConnectionSet == null || mySession.ConnectionSet.Count == 0)
{
return null;
}
SiteArray result = new SiteArray();
result.sites = new SiteTO[mySession.ConnectionSet.Count];
result.count = mySession.ConnectionSet.Count;
int i = 0;
foreach (KeyValuePair<string, gov.va.medora.mdo.dao.AbstractConnection> cxn in mySession.ConnectionSet.Connections)
{
result.sites[i] = new SiteTO();
result.sites[i].displayName = cxn.Value.DataSource.SiteId.Name;
i++;
}
return result;
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
namespace Axiom.Overlays {
/// <summary>
/// Represents a layer which is rendered on top of the 'normal' scene contents.
/// </summary>
/// <remarks>
/// An overlay is a container for visual components (2D and 3D) which will be
/// rendered after the main scene in order to composite heads-up-displays, menus
/// or other layers on top of the contents of the scene.
/// <p/>
/// An overlay always takes up the entire size of the viewport, although the
/// components attached to it do not have to. An overlay has no visual element
/// in itself, it it merely a container for visual elements.
/// <p/>
/// Overlays are created by calling SceneManager.CreateOverlay, or by defining them
/// in special text scripts (.overlay files). As many overlays
/// as you like can be defined; after creation an overlay is hidden i.e. not
/// visible until you specifically enable it by calling Show(). This allows you to have multiple
/// overlays predefined (menus etc) which you make visible only when you want.
/// It is possible to have multiple overlays enabled at once; in this case the
/// relative ZOrder parameter of the overlays determine which one is displayed
/// on top.
/// <p/>
/// By default overlays are rendered into all viewports. This is fine when you only
/// have fullscreen viewports, but if you have picture-in-picture views, you probably
/// don't want the overlay displayed in the smaller viewports. You turn this off for
/// a specific viewport by calling the Viewport.DisplayOverlays property.
/// </remarks>
public class Overlay : Resource {
#region Member variables
protected int zOrder;
protected bool isVisible;
protected SceneNode rootNode;
/// <summary>2D element list.</summary>
protected ArrayList elementList = new ArrayList();
protected Hashtable elementLookup = new Hashtable();
/// <summary>Degrees of rotation around center.</summary>
protected float rotate;
/// <summary>Scroll values, offsets.</summary>
protected float scrollX, scrollY;
/// <summary>Scale values.</summary>
protected float scaleX, scaleY;
protected Matrix4 transform = Matrix4.Identity;
protected bool isTransformOutOfDate;
#endregion Member variables
#region Constructors
/// <summary>
/// Constructor: do not call direct, use SceneManager.CreateOverlay
/// </summary>
/// <param name="name"></param>
internal Overlay(string name) {
this.name = name;
this.scaleX = 1.0f;
this.scaleY = 1.0f;
this.isTransformOutOfDate = true;
this.zOrder = 100;
rootNode = new SceneNode(null);
}
#endregion Constructors
#region Methods
/// <summary>
/// Adds a 2d element to this overlay.
/// </summary>
/// <remarks>
/// Containers are created and managed using the GuiManager. A container
/// could be as simple as a square panel, or something more complex like
/// a grid or tree view. Containers group collections of other elements,
/// giving them a relative coordinate space and a common z-order.
/// If you want to attach a gui widget to an overlay, you have to do it via
/// a container.
/// </remarks>
/// <param name="element"></param>
public void AddElement(OverlayElementContainer element) {
elementList.Add(element);
elementLookup.Add(element.Name, element);
// notify the parent
element.NotifyParent(null, this);
// Set Z order, scaled to separate overlays
// max 100 container levels per overlay, should be plenty
element.NotifyZOrder(zOrder * 100);
}
/// <summary>
/// Adds a node capable of holding 3D objects to the overlay.
/// </summary>
/// <remarks>
/// Although overlays are traditionally associated with 2D elements, there
/// are reasons why you might want to attach 3D elements to the overlay too.
/// For example, if you wanted to have a 3D cockpit, which was overlaid with a
/// HUD, then you would create 2 overlays, one with a 3D object attached for the
/// cockpit, and one with the HUD elements attached (the zorder of the HUD
/// overlay would be higher than the cockpit to ensure it was always on top).
/// <p/>
/// A SceneNode can have any number of 3D objects attached to it. SceneNodes
/// are created using SceneManager.CreateSceneNode, and are normally attached
/// (directly or indirectly) to the root node of the scene. By attaching them
/// to an overlay, you indicate that:<OL>
/// <LI>You want the contents of this node to only appear when the overlay is active</LI>
/// <LI>You want the node to inherit a coordinate space relative to the camera,
/// rather than relative to the root scene node</LI>
/// <LI>You want these objects to be rendered after the contents of the main scene
/// to ensure they are rendered on top</LI>
/// </OL>
/// One major consideration when using 3D objects in overlays is the behavior of
/// the depth buffer. Overlays are rendered with depth checking off, to ensure
/// that their contents are always displayed on top of the main scene (to do
/// otherwise would result in objects 'poking through' the overlay). The problem
/// with using 3D objects is that if they are concave, or self-overlap, then you
/// can get artifacts because of the lack of depth buffer checking. So you should
/// ensure that any 3D objects you us in the overlay are convex and don't overlap
/// each other. If they must overlap, split them up and put them in 2 overlays.
/// </remarks>
/// <param name="node"></param>
public void AddElement(SceneNode node) {
// add the scene node as a child of the root node
rootNode.AddChild(node);
}
/// <summary>
/// Clears the overlay of all attached items.
/// </summary>
public void Clear() {
rootNode.Clear();
elementList.Clear();
}
/// <summary>
/// Internal method to put the overlay contents onto the render queue.
/// </summary>
/// <param name="camera">Current camera being used in the render loop.</param>
/// <param name="queue">Current render queue.</param>
public void FindVisibleObjects(Camera camera, RenderQueue queue)
{
if(!isVisible) {
return;
}
// add 3d elements
rootNode.Position = camera.DerivedPosition;
rootNode.Orientation = camera.DerivedOrientation;
rootNode.Update(true, false);
// set up the default queue group for the objects about to be added
RenderQueueGroupID oldGroupID = queue.DefaultRenderGroup;
queue.DefaultRenderGroup = RenderQueueGroupID.Overlay;
rootNode.FindVisibleObjects(camera, queue, null, true, false);
// reset the group
queue.DefaultRenderGroup = oldGroupID;
// add 2d elements
for(int i = 0; i < elementList.Count; i++) {
OverlayElementContainer container = (OverlayElementContainer)elementList[i];
container.Update();
container.UpdateRenderQueue(queue);
}
}
/// <summary>
/// Gets a child container of this overlay by name.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public OverlayElementContainer GetChild(string name) {
return (OverlayElementContainer)elementLookup[name];
}
/// <summary>
/// Used to transform the overlay when scrolling, scaling etc.
/// </summary>
/// <param name="xform">Array of Matrix4s to populate with the world
/// transforms of this overlay.
/// </param>
public void GetWorldTransforms(Matrix4[] xform) {
if(isTransformOutOfDate) {
UpdateTransforms();
}
xform[0] = transform;
}
/// <summary>
/// Hides this overlay if it is currently being displayed.
/// </summary>
public void Hide() {
isVisible = false;
}
/// <summary>
/// Adds the passed in angle to the rotation applied to this overlay.
/// </summary>
/// <param name="degress"></param>
public void Rotate(float degrees) {
this.Rotation = (rotate += degrees);
}
/// <summary>
/// Scrolls the overlay by the offsets provided.
/// </summary>
/// <remarks>
/// This method moves the overlay by the amounts provided. As with
/// other methods on this object, a full screen width / height is represented
/// by the value 1.0.
/// </remarks>
/// <param name="xOffset"></param>
/// <param name="yOffset"></param>
public void Scroll(float xOffset, float yOffset) {
scrollX += xOffset;
scrollY += yOffset;
isTransformOutOfDate = true;
}
/// <summary>
/// Sets the scaling factor of this overlay.
/// </summary>
/// <remarks>
/// You can use this to set an scale factor to be used to zoom an overlay.
/// </remarks>
/// <param name="x">Horizontal scale value, where 1.0 = normal, 0.5 = half size etc</param>
/// <param name="y">Vertical scale value, where 1.0 = normal, 0.5 = half size etc</param>
public void SetScale(float x, float y) {
scaleX = x;
scaleY = y;
isTransformOutOfDate = true;
}
/// <summary>
/// Sets the scrolling factor of this overlay.
/// </summary>
/// <remarks>
/// You can use this to set an offset to be used to scroll an
/// overlay around the screen.
/// </remarks>
/// <param name="x">
/// Horizontal scroll value, where 0 = normal, -0.5 = scroll so that only
/// the right half the screen is visible etc
/// </param>
/// <param name="y">
/// Vertical scroll value, where 0 = normal, 0.5 = scroll down by half
/// a screen etc.
/// </param>
public void SetScroll(float x, float y) {
scrollX = x;
scrollY = y;
isTransformOutOfDate = true;
}
/// <summary>
/// Shows this overlay if it is not already visible.
/// </summary>
public void Show() {
isVisible = true;
}
/// <summary>
/// Internal lazy update method.
/// </summary>
protected void UpdateTransforms() {
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
Matrix3 rot3x3 = Matrix3.Identity;
Matrix3 scale3x3 = Matrix3.Zero;
rot3x3.FromEulerAnglesXYZ(0, 0, MathUtil.DegreesToRadians(rotate));
scale3x3.m00 = scaleX;
scale3x3.m11 = scaleY;
scale3x3.m22 = 1.0f;
transform = Matrix4.Identity;
transform = rot3x3 * scale3x3;
transform.Translation = new Vector3(scrollX, scrollY, 0);
isTransformOutOfDate = false;
}
#endregion Methods
#region Properties
/// <summary>
/// Gets whether this overlay is being displayed or not.
/// </summary>
public bool IsVisible {
get {
return isVisible;
}
}
/// <summary>
/// Gets/Sets the rotation applied to this overlay, in degrees.
/// </summary>
public float Rotation {
get {
return rotate;
}
set {
rotate = value;
isTransformOutOfDate = true;
}
}
/// <summary>
/// Gets the current x scale value.
/// </summary>
public float ScaleX {
get {
return scaleX;
}
}
/// <summary>
/// Gets the current y scale value.
/// </summary>
public float ScaleY {
get {
return scaleY;
}
}
/// <summary>
/// Gets the current x scroll value.
/// </summary>
public float ScrollX {
get {
return scrollX;
}
}
/// <summary>
/// Gets the current y scroll value.
/// </summary>
public float ScrollY {
get {
return scrollY;
}
}
/// <summary>
/// Z ordering of this overlay. Valid values are between 0 and 600.
/// </summary>
public int ZOrder {
get {
return zOrder;
}
set {
zOrder = value;
// notify attached 2d elements
for(int i = 0; i < elementList.Count; i++) {
((OverlayElementContainer)elementList[i]).NotifyZOrder(zOrder);
}
}
}
public Quaternion DerivedOrientation {
get {
return Quaternion.Identity;
}
}
public Vector3 DerivedPosition {
get {
return Vector3.Zero;
}
}
#endregion Properties
#region Implementation of Resource
/// <summary>
///
/// </summary>
public override void Preload() {
// do nothing
}
/// <summary>
///
/// </summary>
protected override void LoadImpl() {
// do nothing
}
/// <summary>
///
/// </summary>
protected override void UnloadImpl() {
// do nothing
}
/// <summary>
///
/// </summary>
public override void Dispose() {
// do nothing
}
#endregion
}
}
| |
using System;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Order;
namespace Pingu.Benchmarks
{
[Config(typeof(Config))]
[OrderProvider(SummaryOrderPolicy.FastestToSlowest)]
public class PaethImplementations
{
[Params(5000)]
public int TotalBytes { get; set; }
public bool HasPreviousScanline { private get; set; } = true;
const int BytesPerPixel = 4;
const int TargetOffset = 0;
public byte[] TargetBuffer { get; private set; }
public byte[] RawScanline { get; private set; }
public byte[] PreviousScanline { get; private set; }
static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
[GlobalSetup]
public void Setup()
{
TargetBuffer = new byte[TotalBytes];
RawScanline = new byte[TotalBytes];
PreviousScanline = HasPreviousScanline ? new byte[TotalBytes] : null;
Rng.GetBytes(RawScanline);
if (HasPreviousScanline)
// ReSharper disable once AssignNullToNotNullAttribute
Rng.GetBytes(PreviousScanline);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int Abs(int value)
{
var temp = value >> 31;
value ^= temp;
value += temp & 1;
return value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static int FasterAbs(int value)
{
var mask = value >> 31;
return (value ^ mask) - mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static byte PaethFastAbs(byte a, byte b, byte c)
{
int p = a + b - c,
pa = Abs(p - a),
pb = Abs(p - b),
pc = Abs(p - c);
return pa <= pb && pa <= pc ? a : (pb <= pc ? b : c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static byte PaethFasterAbs(byte a, byte b, byte c)
{
int p = a + b - c,
pa = FasterAbs(p - a),
pb = FasterAbs(p - b),
pc = FasterAbs(p - c);
return pa <= pb && pa <= pc ? a : (pb <= pc ? b : c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static byte PaethFasterAbsLessArithmetic(byte a, byte b, byte c)
{
int pc = c, pa = b - pc, pb = a - pc;
pc = FasterAbs(pa + pb);
pa = FasterAbs(pa);
pb = FasterAbs(pb);
return pa <= pb && pa <= pc ? a : (pb <= pc ? b : c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static byte PaethVec(byte a, byte b, byte c)
{
var p = a + b - c;
var resVec = Vector3.Abs(new Vector3(p, p, p) - new Vector3(a, b, c));
return resVec.X <= resVec.Y && resVec.X <= resVec.Z ? a : (resVec.Y <= resVec.Z ? b : c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static byte Paeth(byte a, byte b, byte c)
{
int p = a + b - c,
pa = Math.Abs(p - a),
pb = Math.Abs(p - b),
pc = Math.Abs(p - c);
return pa <= pb && pa <= pc ? a : (pb <= pc ? b : c);
}
// Skip the nullable access benchmark that we did in AvgImplementations, it's never going to be
// as good as separate loops.
[Benchmark(Baseline = true)]
public void NaiveWithMathAbs()
{
// Paeth(x) = Raw(x) - PaethPredictor(Raw(x-bpp), Prior(x), Prior(x - bpp))
if (PreviousScanline == null) {
// First bpp bytes, a and c values passed to the Paeth predictor are 0. If previous scanline is null,
// then the first 4 bytes just match the first 4 raw, as Paeth(0,0,0) is 0.
Buffer.BlockCopy(RawScanline, 0, TargetBuffer, TargetOffset, BytesPerPixel);
// For the remaining bytes, we have a value for a, but not b and c, as there is no prior scanline.
// Paeth(a,0,0) is a, so Paeth is just the sub filter in this case.
for (var i = BytesPerPixel; i < RawScanline.Length; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - RawScanline[i - BytesPerPixel]));
} else {
var i = 0;
// First BPP bytes, a and c are 0, but b has a value. Paeth(0,b,0) == b, so treat it as such.
for (; i < BytesPerPixel; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - PreviousScanline[i]));
// The remaining bytes, a and c have values!
for (; i < RawScanline.Length; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - Paeth(
RawScanline[i - BytesPerPixel],
PreviousScanline[i],
PreviousScanline[i - BytesPerPixel]
)));
}
}
[Benchmark]
public unsafe void UnrolledWithMathAbs()
{
fixed (byte* targetPreoffset = TargetBuffer)
fixed (byte* previous = PreviousScanline)
fixed (byte* raw = RawScanline) {
var target = targetPreoffset + TargetOffset;
if (previous == null) {
// If the previous scanline is null, Paeth == Sub
Buffer.MemoryCopy(raw, target, RawScanline.Length, BytesPerPixel);
unchecked {
// We start immediately after the first pixel--its bytes are unchanged. We only copied
// bytesPerPixel bytes from the scanline, so we need to read over the raw scanline. Unroll
// the loop a bit, as well.
var x = BytesPerPixel;
for (; RawScanline.Length - x > 8; x += 8) {
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
target[x + 1] = (byte)(raw[x + 1] - raw[x + 1 - BytesPerPixel]);
target[x + 2] = (byte)(raw[x + 2] - raw[x + 2 - BytesPerPixel]);
target[x + 3] = (byte)(raw[x + 3] - raw[x + 3 - BytesPerPixel]);
target[x + 4] = (byte)(raw[x + 4] - raw[x + 4 - BytesPerPixel]);
target[x + 5] = (byte)(raw[x + 5] - raw[x + 5 - BytesPerPixel]);
target[x + 6] = (byte)(raw[x + 6] - raw[x + 6 - BytesPerPixel]);
target[x + 7] = (byte)(raw[x + 7] - raw[x + 7 - BytesPerPixel]);
}
for (; x < RawScanline.Length; x++)
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
}
} else {
var i = 0;
unchecked {
// The first bpp bytes, Paeth = Up
for (; i < BytesPerPixel; i++)
target[i] = (byte)(raw[i] - previous[i]);
// The remaining bytes, a and c have values!
for (; RawScanline.Length - i > 8; i += 8) {
target[i] = (byte)(raw[i] - Paeth(raw[i - BytesPerPixel], previous[i], previous[i - BytesPerPixel]));
target[i + 1] = (byte)(raw[i + 1] - Paeth(raw[i + 1 - BytesPerPixel], previous[i + 1], previous[i + 1 - BytesPerPixel]));
target[i + 2] = (byte)(raw[i + 2] - Paeth(raw[i + 2 - BytesPerPixel], previous[i + 2], previous[i + 2 - BytesPerPixel]));
target[i + 3] = (byte)(raw[i + 3] - Paeth(raw[i + 3 - BytesPerPixel], previous[i + 3], previous[i + 3 - BytesPerPixel]));
target[i + 4] = (byte)(raw[i + 4] - Paeth(raw[i + 4 - BytesPerPixel], previous[i + 4], previous[i + 4 - BytesPerPixel]));
target[i + 5] = (byte)(raw[i + 5] - Paeth(raw[i + 5 - BytesPerPixel], previous[i + 5], previous[i + 5 - BytesPerPixel]));
target[i + 6] = (byte)(raw[i + 6] - Paeth(raw[i + 6 - BytesPerPixel], previous[i + 6], previous[i + 6 - BytesPerPixel]));
target[i + 7] = (byte)(raw[i + 7] - Paeth(raw[i + 7 - BytesPerPixel], previous[i + 7], previous[i + 7 - BytesPerPixel]));
}
for (; i < RawScanline.Length; i++)
target[i] = (byte)(raw[i] - Paeth(raw[i - BytesPerPixel], previous[i], previous[i - BytesPerPixel]));
}
}
}
}
[Benchmark]
public void NaiveWithFastAbs()
{
// Paeth(x) = Raw(x) - PaethPredictor(Raw(x-bpp), Prior(x), Prior(x - bpp))
if (PreviousScanline == null) {
// First bpp bytes, a and c values passed to the Paeth predictor are 0. If previous scanline is null,
// then the first 4 bytes just match the first 4 raw, as Paeth(0,0,0) is 0.
Buffer.BlockCopy(RawScanline, 0, TargetBuffer, TargetOffset, BytesPerPixel);
// For the remaining bytes, we have a value for a, but not b and c, as there is no prior scanline.
// Paeth(a,0,0) is a, so Paeth is just the sub filter in this case.
for (var i = BytesPerPixel; i < RawScanline.Length; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - RawScanline[i - BytesPerPixel]));
} else {
var i = 0;
// First BPP bytes, a and c are 0, but b has a value. Paeth(0,b,0) == b, so treat it as such.
for (; i < BytesPerPixel; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - PreviousScanline[i]));
// The remaining bytes, a and c have values!
for (; i < RawScanline.Length; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - PaethFastAbs(
RawScanline[i - BytesPerPixel],
PreviousScanline[i],
PreviousScanline[i - BytesPerPixel]
)));
}
}
[Benchmark]
public unsafe void UnrolledWithFastAbs()
{
fixed (byte* targetPreoffset = TargetBuffer)
fixed (byte* previous = PreviousScanline)
fixed (byte* raw = RawScanline) {
var target = targetPreoffset + TargetOffset;
if (previous == null) {
// If the previous scanline is null, Paeth == Sub
Buffer.MemoryCopy(raw, target, RawScanline.Length, BytesPerPixel);
unchecked {
// We start immediately after the first pixel--its bytes are unchanged. We only copied
// bytesPerPixel bytes from the scanline, so we need to read over the raw scanline. Unroll
// the loop a bit, as well.
var x = BytesPerPixel;
for (; RawScanline.Length - x > 8; x += 8) {
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
target[x + 1] = (byte)(raw[x + 1] - raw[x + 1 - BytesPerPixel]);
target[x + 2] = (byte)(raw[x + 2] - raw[x + 2 - BytesPerPixel]);
target[x + 3] = (byte)(raw[x + 3] - raw[x + 3 - BytesPerPixel]);
target[x + 4] = (byte)(raw[x + 4] - raw[x + 4 - BytesPerPixel]);
target[x + 5] = (byte)(raw[x + 5] - raw[x + 5 - BytesPerPixel]);
target[x + 6] = (byte)(raw[x + 6] - raw[x + 6 - BytesPerPixel]);
target[x + 7] = (byte)(raw[x + 7] - raw[x + 7 - BytesPerPixel]);
}
for (; x < RawScanline.Length; x++)
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
}
} else {
var i = 0;
unchecked {
// The first bpp bytes, Paeth = Up
for (; i < BytesPerPixel; i++)
target[i] = (byte)(raw[i] - previous[i]);
// The remaining bytes, a and c have values!
for (; RawScanline.Length - i > 8; i += 8) {
target[i] = (byte)(raw[i] - PaethFastAbs(raw[i - BytesPerPixel], previous[i], previous[i - BytesPerPixel]));
target[i + 1] = (byte)(raw[i + 1] - PaethFastAbs(raw[i + 1 - BytesPerPixel], previous[i + 1], previous[i + 1 - BytesPerPixel]));
target[i + 2] = (byte)(raw[i + 2] - PaethFastAbs(raw[i + 2 - BytesPerPixel], previous[i + 2], previous[i + 2 - BytesPerPixel]));
target[i + 3] = (byte)(raw[i + 3] - PaethFastAbs(raw[i + 3 - BytesPerPixel], previous[i + 3], previous[i + 3 - BytesPerPixel]));
target[i + 4] = (byte)(raw[i + 4] - PaethFastAbs(raw[i + 4 - BytesPerPixel], previous[i + 4], previous[i + 4 - BytesPerPixel]));
target[i + 5] = (byte)(raw[i + 5] - PaethFastAbs(raw[i + 5 - BytesPerPixel], previous[i + 5], previous[i + 5 - BytesPerPixel]));
target[i + 6] = (byte)(raw[i + 6] - PaethFastAbs(raw[i + 6 - BytesPerPixel], previous[i + 6], previous[i + 6 - BytesPerPixel]));
target[i + 7] = (byte)(raw[i + 7] - PaethFastAbs(raw[i + 7 - BytesPerPixel], previous[i + 7], previous[i + 7 - BytesPerPixel]));
}
for (; i < RawScanline.Length; i++)
target[i] = (byte)(raw[i] - PaethFastAbs(raw[i - BytesPerPixel], previous[i], previous[i - BytesPerPixel]));
}
}
}
}
[Benchmark]
public unsafe void UnrolledWithFastAbsAndMovingPointers()
{
fixed (byte* targetPreoffset = TargetBuffer)
fixed (byte* previous = PreviousScanline)
fixed (byte* raw = RawScanline) {
var target = targetPreoffset + TargetOffset;
if (previous == null) {
// If the previous scanline is null, Paeth == Sub
Buffer.MemoryCopy(raw, target, RawScanline.Length, BytesPerPixel);
unchecked {
// We start immediately after the first pixel--its bytes are unchanged. We only copied
// bytesPerPixel bytes from the scanline, so we need to read over the raw scanline. Unroll
// the loop a bit, as well.
var x = BytesPerPixel;
for (; RawScanline.Length - x > 8; x += 8) {
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
target[x + 1] = (byte)(raw[x + 1] - raw[x + 1 - BytesPerPixel]);
target[x + 2] = (byte)(raw[x + 2] - raw[x + 2 - BytesPerPixel]);
target[x + 3] = (byte)(raw[x + 3] - raw[x + 3 - BytesPerPixel]);
target[x + 4] = (byte)(raw[x + 4] - raw[x + 4 - BytesPerPixel]);
target[x + 5] = (byte)(raw[x + 5] - raw[x + 5 - BytesPerPixel]);
target[x + 6] = (byte)(raw[x + 6] - raw[x + 6 - BytesPerPixel]);
target[x + 7] = (byte)(raw[x + 7] - raw[x + 7 - BytesPerPixel]);
}
for (; x < RawScanline.Length; x++)
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
}
} else {
var i = 0;
unchecked {
byte* tgt = target, rawm = raw, prev = previous,
rawBpp = raw - BytesPerPixel, prevBpp = previous - BytesPerPixel;
// The first bpp bytes, Paeth = Up
for (; i < BytesPerPixel; i++) {
tgt[0] = (byte)(rawm[0] - prev[0]);
tgt++; rawm++; prev++; rawBpp++; prevBpp++;
}
// The remaining bytes, a and c have values!
for (; RawScanline.Length - i > 8; i += 8) {
tgt[0] = (byte)(rawm[0] - PaethFastAbs(rawBpp[0], prev[0], prevBpp[0]));
tgt[1] = (byte)(rawm[1] - PaethFastAbs(rawBpp[1], prev[1], prevBpp[1]));
tgt[2] = (byte)(rawm[2] - PaethFastAbs(rawBpp[2], prev[2], prevBpp[2]));
tgt[3] = (byte)(rawm[3] - PaethFastAbs(rawBpp[3], prev[3], prevBpp[3]));
tgt[4] = (byte)(rawm[4] - PaethFastAbs(rawBpp[4], prev[4], prevBpp[4]));
tgt[5] = (byte)(rawm[5] - PaethFastAbs(rawBpp[5], prev[5], prevBpp[5]));
tgt[6] = (byte)(rawm[6] - PaethFastAbs(rawBpp[6], prev[6], prevBpp[6]));
tgt[7] = (byte)(rawm[7] - PaethFastAbs(rawBpp[7], prev[7], prevBpp[7]));
tgt += 8; rawm += 8; prev += 8; rawBpp += 8; prevBpp += 8;
}
for (; i < RawScanline.Length; i++) {
tgt[0] = (byte)(rawm[0] - PaethFastAbs(rawBpp[0], prev[0], prevBpp[0]));
tgt++; rawm++; prev++; rawBpp++; prevBpp++;
}
}
}
}
}
[Benchmark]
public unsafe void UnrolledWithFasterAbsAndMovingPointers()
{
fixed (byte* targetPreoffset = TargetBuffer)
fixed (byte* previous = PreviousScanline)
fixed (byte* raw = RawScanline) {
var target = targetPreoffset + TargetOffset;
if (previous == null) {
// If the previous scanline is null, Paeth == Sub
Buffer.MemoryCopy(raw, target, RawScanline.Length, BytesPerPixel);
unchecked {
// We start immediately after the first pixel--its bytes are unchanged. We only copied
// bytesPerPixel bytes from the scanline, so we need to read over the raw scanline. Unroll
// the loop a bit, as well.
var x = BytesPerPixel;
for (; RawScanline.Length - x > 8; x += 8) {
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
target[x + 1] = (byte)(raw[x + 1] - raw[x + 1 - BytesPerPixel]);
target[x + 2] = (byte)(raw[x + 2] - raw[x + 2 - BytesPerPixel]);
target[x + 3] = (byte)(raw[x + 3] - raw[x + 3 - BytesPerPixel]);
target[x + 4] = (byte)(raw[x + 4] - raw[x + 4 - BytesPerPixel]);
target[x + 5] = (byte)(raw[x + 5] - raw[x + 5 - BytesPerPixel]);
target[x + 6] = (byte)(raw[x + 6] - raw[x + 6 - BytesPerPixel]);
target[x + 7] = (byte)(raw[x + 7] - raw[x + 7 - BytesPerPixel]);
}
for (; x < RawScanline.Length; x++)
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
}
} else {
var i = 0;
unchecked {
byte* tgt = target, rawm = raw, prev = previous,
rawBpp = raw - BytesPerPixel, prevBpp = previous - BytesPerPixel;
// The first bpp bytes, Paeth = Up
for (; i < BytesPerPixel; i++) {
tgt[0] = (byte)(rawm[0] - prev[0]);
tgt++; rawm++; prev++; rawBpp++; prevBpp++;
}
// The remaining bytes, a and c have values!
for (; RawScanline.Length - i > 8; i += 8) {
tgt[0] = (byte)(rawm[0] - PaethFasterAbs(rawBpp[0], prev[0], prevBpp[0]));
tgt[1] = (byte)(rawm[1] - PaethFasterAbs(rawBpp[1], prev[1], prevBpp[1]));
tgt[2] = (byte)(rawm[2] - PaethFasterAbs(rawBpp[2], prev[2], prevBpp[2]));
tgt[3] = (byte)(rawm[3] - PaethFasterAbs(rawBpp[3], prev[3], prevBpp[3]));
tgt[4] = (byte)(rawm[4] - PaethFasterAbs(rawBpp[4], prev[4], prevBpp[4]));
tgt[5] = (byte)(rawm[5] - PaethFasterAbs(rawBpp[5], prev[5], prevBpp[5]));
tgt[6] = (byte)(rawm[6] - PaethFasterAbs(rawBpp[6], prev[6], prevBpp[6]));
tgt[7] = (byte)(rawm[7] - PaethFasterAbs(rawBpp[7], prev[7], prevBpp[7]));
tgt += 8; rawm += 8; prev += 8; rawBpp += 8; prevBpp += 8;
}
for (; i < RawScanline.Length; i++) {
tgt[0] = (byte)(rawm[0] - PaethFasterAbs(rawBpp[0], prev[0], prevBpp[0]));
tgt++; rawm++; prev++; rawBpp++; prevBpp++;
}
}
}
}
}
[Benchmark]
public unsafe void UnrolledWithFasterAbsLessArithmeticAndMovingPointers()
{
fixed (byte* targetPreoffset = TargetBuffer)
fixed (byte* previous = PreviousScanline)
fixed (byte* raw = RawScanline) {
var target = targetPreoffset + TargetOffset;
if (previous == null) {
// If the previous scanline is null, Paeth == Sub
Buffer.MemoryCopy(raw, target, RawScanline.Length, BytesPerPixel);
unchecked {
// We start immediately after the first pixel--its bytes are unchanged. We only copied
// bytesPerPixel bytes from the scanline, so we need to read over the raw scanline. Unroll
// the loop a bit, as well.
var x = BytesPerPixel;
for (; RawScanline.Length - x > 8; x += 8) {
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
target[x + 1] = (byte)(raw[x + 1] - raw[x + 1 - BytesPerPixel]);
target[x + 2] = (byte)(raw[x + 2] - raw[x + 2 - BytesPerPixel]);
target[x + 3] = (byte)(raw[x + 3] - raw[x + 3 - BytesPerPixel]);
target[x + 4] = (byte)(raw[x + 4] - raw[x + 4 - BytesPerPixel]);
target[x + 5] = (byte)(raw[x + 5] - raw[x + 5 - BytesPerPixel]);
target[x + 6] = (byte)(raw[x + 6] - raw[x + 6 - BytesPerPixel]);
target[x + 7] = (byte)(raw[x + 7] - raw[x + 7 - BytesPerPixel]);
}
for (; x < RawScanline.Length; x++)
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
}
} else {
var i = 0;
unchecked {
byte* tgt = target, rawm = raw, prev = previous,
rawBpp = raw - BytesPerPixel, prevBpp = previous - BytesPerPixel;
// The first bpp bytes, Paeth = Up
for (; i < BytesPerPixel; i++) {
tgt[0] = (byte)(rawm[0] - prev[0]);
tgt++; rawm++; prev++; rawBpp++; prevBpp++;
}
// The remaining bytes, a and c have values!
for (; RawScanline.Length - i > 8; i += 8) {
tgt[0] = (byte)(rawm[0] - PaethFasterAbsLessArithmetic(rawBpp[0], prev[0], prevBpp[0]));
tgt[1] = (byte)(rawm[1] - PaethFasterAbsLessArithmetic(rawBpp[1], prev[1], prevBpp[1]));
tgt[2] = (byte)(rawm[2] - PaethFasterAbsLessArithmetic(rawBpp[2], prev[2], prevBpp[2]));
tgt[3] = (byte)(rawm[3] - PaethFasterAbsLessArithmetic(rawBpp[3], prev[3], prevBpp[3]));
tgt[4] = (byte)(rawm[4] - PaethFasterAbsLessArithmetic(rawBpp[4], prev[4], prevBpp[4]));
tgt[5] = (byte)(rawm[5] - PaethFasterAbsLessArithmetic(rawBpp[5], prev[5], prevBpp[5]));
tgt[6] = (byte)(rawm[6] - PaethFasterAbsLessArithmetic(rawBpp[6], prev[6], prevBpp[6]));
tgt[7] = (byte)(rawm[7] - PaethFasterAbsLessArithmetic(rawBpp[7], prev[7], prevBpp[7]));
tgt += 8; rawm += 8; prev += 8; rawBpp += 8; prevBpp += 8;
}
for (; i < RawScanline.Length; i++) {
tgt[0] = (byte)(rawm[0] - PaethFasterAbsLessArithmetic(rawBpp[0], prev[0], prevBpp[0]));
tgt++; rawm++; prev++; rawBpp++; prevBpp++;
}
}
}
}
}
[Benchmark]
public void NaiveWithVecAbs()
{
// Paeth(x) = Raw(x) - PaethPredictor(Raw(x-bpp), Prior(x), Prior(x - bpp))
if (PreviousScanline == null) {
// First bpp bytes, a and c values passed to the Paeth predictor are 0. If previous scanline is null,
// then the first 4 bytes just match the first 4 raw, as Paeth(0,0,0) is 0.
Buffer.BlockCopy(RawScanline, 0, TargetBuffer, TargetOffset, BytesPerPixel);
// For the remaining bytes, we have a value for a, but not b and c, as there is no prior scanline.
// Paeth(a,0,0) is a, so Paeth is just the sub filter in this case.
for (var i = BytesPerPixel; i < RawScanline.Length; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - RawScanline[i - BytesPerPixel]));
} else {
var i = 0;
// First BPP bytes, a and c are 0, but b has a value. Paeth(0,b,0) == b, so treat it as such.
for (; i < BytesPerPixel; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - PreviousScanline[i]));
// The remaining bytes, a and c have values!
for (; i < RawScanline.Length; i++)
TargetBuffer[i + TargetOffset] = unchecked((byte)(RawScanline[i] - PaethVec(
RawScanline[i - BytesPerPixel],
PreviousScanline[i],
PreviousScanline[i - BytesPerPixel]
)));
}
}
[Benchmark]
public unsafe void UnrolledWithVecAbs()
{
fixed (byte* targetPreoffset = TargetBuffer)
fixed (byte* previous = PreviousScanline)
fixed (byte* raw = RawScanline) {
var target = targetPreoffset + TargetOffset;
if (previous == null) {
// If the previous scanline is null, Paeth == Sub
Buffer.MemoryCopy(raw, target, RawScanline.Length, BytesPerPixel);
unchecked {
// We start immediately after the first pixel--its bytes are unchanged. We only copied
// bytesPerPixel bytes from the scanline, so we need to read over the raw scanline. Unroll
// the loop a bit, as well.
var x = BytesPerPixel;
for (; RawScanline.Length - x > 8; x += 8) {
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
target[x + 1] = (byte)(raw[x + 1] - raw[x + 1 - BytesPerPixel]);
target[x + 2] = (byte)(raw[x + 2] - raw[x + 2 - BytesPerPixel]);
target[x + 3] = (byte)(raw[x + 3] - raw[x + 3 - BytesPerPixel]);
target[x + 4] = (byte)(raw[x + 4] - raw[x + 4 - BytesPerPixel]);
target[x + 5] = (byte)(raw[x + 5] - raw[x + 5 - BytesPerPixel]);
target[x + 6] = (byte)(raw[x + 6] - raw[x + 6 - BytesPerPixel]);
target[x + 7] = (byte)(raw[x + 7] - raw[x + 7 - BytesPerPixel]);
}
for (; x < RawScanline.Length; x++)
target[x] = (byte)(raw[x] - raw[x - BytesPerPixel]);
}
} else {
var i = 0;
unchecked {
// The first bpp bytes, Paeth = Up
for (; i < BytesPerPixel; i++)
target[i] = (byte)(raw[i] - previous[i]);
// The remaining bytes, a and c have values!
for (; RawScanline.Length - i > 8; i += 8) {
target[i] = (byte)(raw[i] - PaethVec(raw[i - BytesPerPixel], previous[i], previous[i - BytesPerPixel]));
target[i + 1] = (byte)(raw[i + 1] - PaethVec(raw[i + 1 - BytesPerPixel], previous[i + 1], previous[i + 1 - BytesPerPixel]));
target[i + 2] = (byte)(raw[i + 2] - PaethVec(raw[i + 2 - BytesPerPixel], previous[i + 2], previous[i + 2 - BytesPerPixel]));
target[i + 3] = (byte)(raw[i + 3] - PaethVec(raw[i + 3 - BytesPerPixel], previous[i + 3], previous[i + 3 - BytesPerPixel]));
target[i + 4] = (byte)(raw[i + 4] - PaethVec(raw[i + 4 - BytesPerPixel], previous[i + 4], previous[i + 4 - BytesPerPixel]));
target[i + 5] = (byte)(raw[i + 5] - PaethVec(raw[i + 5 - BytesPerPixel], previous[i + 5], previous[i + 5 - BytesPerPixel]));
target[i + 6] = (byte)(raw[i + 6] - PaethVec(raw[i + 6 - BytesPerPixel], previous[i + 6], previous[i + 6 - BytesPerPixel]));
target[i + 7] = (byte)(raw[i + 7] - PaethVec(raw[i + 7 - BytesPerPixel], previous[i + 7], previous[i + 7 - BytesPerPixel]));
}
for (; i < RawScanline.Length; i++)
target[i] = (byte)(raw[i] - PaethVec(raw[i - BytesPerPixel], previous[i], previous[i - BytesPerPixel]));
}
}
}
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
namespace Pictor
{
public static class ClipLiangBarsky
{
//------------------------------------------------------------------------
private enum ClippingFlags
{
x1Clipped = 4,
x2Clipped = 1,
y1Clipped = 8,
y2Clipped = 2,
xClipped = x1Clipped | x2Clipped,
yClipped = y1Clipped | y2Clipped
};
//----------------------------------------------------------GetClippingFlags
// Determine the clipping code of the Vertex according to the
// Cyrus-Beck Line clipping algorithm
//
// | |
// 0110 | 0010 | 0011
// | |
// -------+--------+-------- ClipBox.y2
// | |
// 0100 | 0000 | 0001
// | |
// -------+--------+-------- ClipBox.y1
// | |
// 1100 | 1000 | 1001
// | |
// ClipBox.x1 ClipBox.x2
//
//
//template<class T>
public static uint GetClippingFlags(int x, int y, RectI clip_box)
{
return (uint)(((x > clip_box.x2) ? 1 : 0)
| ((y > clip_box.y2) ? 1 << 1 : 0)
| ((x < clip_box.x1) ? 1 << 2 : 0)
| ((y < clip_box.y1) ? 1 << 3 : 0));
}
//--------------------------------------------------------ClippingFlagsX
//template<class T>
public static uint ClippingFlagsX(int x, RectI clip_box)
{
return (uint)((x > clip_box.x2 ? 1 : 0) | ((x < clip_box.x1 ? 1 : 0) << 2));
}
//--------------------------------------------------------ClippingFlagsY
//template<class T>
public static uint ClippingFlagsY(int y, RectI clip_box)
{
return (uint)(((y > clip_box.y2 ? 1 : 0) << 1) | ((y < clip_box.y1 ? 1 : 0) << 3));
}
//-------------------------------------------------------ClipLiangbarsky
//template<class T>
public static uint ClipLiangbarsky(int x1, int y1, int x2, int y2,
RectI clip_box,
int[] x, int[] y)
{
uint XIndex = 0;
uint YIndex = 0;
double nearzero = 1e-30;
double deltax = x2 - x1;
double deltay = y2 - y1;
double xin;
double xout;
double yin;
double yout;
double tinx;
double tiny;
double toutx;
double touty;
double tin1;
double tin2;
double tout1;
uint np = 0;
if (deltax == 0.0)
{
// bump off of the vertical
deltax = (x1 > clip_box.x1) ? -nearzero : nearzero;
}
if (deltay == 0.0)
{
// bump off of the horizontal
deltay = (y1 > clip_box.y1) ? -nearzero : nearzero;
}
if (deltax > 0.0)
{
// points to right
xin = clip_box.x1;
xout = clip_box.x2;
}
else
{
xin = clip_box.x2;
xout = clip_box.x1;
}
if (deltay > 0.0)
{
// points up
yin = clip_box.y1;
yout = clip_box.y2;
}
else
{
yin = clip_box.y2;
yout = clip_box.y1;
}
tinx = (xin - x1) / deltax;
tiny = (yin - y1) / deltay;
if (tinx < tiny)
{
// hits x first
tin1 = tinx;
tin2 = tiny;
}
else
{
// hits y first
tin1 = tiny;
tin2 = tinx;
}
if (tin1 <= 1.0)
{
if (0.0 < tin1)
{
x[XIndex++] = (int)xin;
y[YIndex++] = (int)yin;
++np;
}
if (tin2 <= 1.0)
{
toutx = (xout - x1) / deltax;
touty = (yout - y1) / deltay;
tout1 = (toutx < touty) ? toutx : touty;
if (tin2 > 0.0 || tout1 > 0.0)
{
if (tin2 <= tout1)
{
if (tin2 > 0.0)
{
if (tinx > tiny)
{
x[XIndex++] = (int)xin;
y[YIndex++] = (int)(y1 + tinx * deltay);
}
else
{
x[XIndex++] = (int)(x1 + tiny * deltax);
y[YIndex++] = (int)yin;
}
++np;
}
if (tout1 < 1.0)
{
if (toutx < touty)
{
x[XIndex++] = (int)xout;
y[YIndex++] = (int)(y1 + toutx * deltay);
}
else
{
x[XIndex++] = (int)(x1 + touty * deltax);
y[YIndex++] = (int)yout;
}
}
else
{
x[XIndex++] = x2;
y[YIndex++] = y2;
}
++np;
}
else
{
if (tinx > tiny)
{
x[XIndex++] = (int)xin;
y[YIndex++] = (int)yout;
}
else
{
x[XIndex++] = (int)xout;
y[YIndex++] = (int)yin;
}
++np;
}
}
}
}
return np;
}
//----------------------------------------------------------------------------
//template<class T>
public static bool ClipMovePoint(int x1, int y1, int x2, int y2,
RectI clip_box,
ref int x, ref int y, uint flags)
{
int bound;
if ((flags & (uint)ClippingFlags.xClipped) != 0)
{
if (x1 == x2)
{
return false;
}
bound = ((flags & (uint)ClippingFlags.x1Clipped) != 0) ? clip_box.x1 : clip_box.x2;
y = (int)((double)(bound - x1) * (y2 - y1) / (x2 - x1) + y1);
x = bound;
}
flags = ClippingFlagsY(y, clip_box);
if ((flags & (uint)ClippingFlags.yClipped) != 0)
{
if (y1 == y2)
{
return false;
}
bound = ((flags & (uint)ClippingFlags.x1Clipped) != 0) ? clip_box.y1 : clip_box.y2;
x = (int)((double)(bound - y1) * (x2 - x1) / (y2 - y1) + x1);
y = bound;
}
return true;
}
//-------------------------------------------------------ClipLineSegment
// Returns: ret >= 4 - Fully clipped
// (ret & 1) != 0 - First point has been moved
// (ret & 2) != 0 - Second point has been moved
//
//template<class T>
public static uint ClipLineSegment(ref int x1, ref int y1, ref int x2, ref int y2,
RectI clip_box)
{
uint f1 = GetClippingFlags(x1, y1, clip_box);
uint f2 = GetClippingFlags(x2, y2, clip_box);
uint ret = 0;
if ((f2 | f1) == 0)
{
// Fully visible
return 0;
}
if ((f1 & (uint)ClippingFlags.xClipped) != 0 &&
(f1 & (uint)ClippingFlags.xClipped) == (f2 & (uint)ClippingFlags.xClipped))
{
// Fully clipped
return 4;
}
if ((f1 & (uint)ClippingFlags.yClipped) != 0 &&
(f1 & (uint)ClippingFlags.yClipped) == (f2 & (uint)ClippingFlags.yClipped))
{
// Fully clipped
return 4;
}
int tx1 = x1;
int ty1 = y1;
int tx2 = x2;
int ty2 = y2;
if (f1 != 0)
{
if (!ClipMovePoint(tx1, ty1, tx2, ty2, clip_box, ref x1, ref y1, f1))
{
return 4;
}
if (x1 == x2 && y1 == y2)
{
return 4;
}
ret |= 1;
}
if (f2 != 0)
{
if (!ClipMovePoint(tx1, ty1, tx2, ty2, clip_box, ref x2, ref y2, f2))
{
return 4;
}
if (x1 == x2 && y1 == y2)
{
return 4;
}
ret |= 2;
}
return ret;
}
}
}
//#endif
| |
// Copyright 2016 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 Google.Api;
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Apis.Auth.OAuth2;
using Google.Cloud.DevTools.Source.V1;
using Google.Cloud.Logging.Type;
using Google.Cloud.Logging.V2;
using Google.Protobuf;
using log4net.Appender;
using log4net.Core;
using log4net.Layout;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Logging.Log4Net
{
/// <summary>
/// Appends logging events to Google Stackdriver Logging.
/// </summary>
/// <remarks>
/// <para>
/// Logging events are sent to Google Stackdriver Logging asychronously,
/// via a local buffer. This is to ensure that server errors or increased
/// network/server latency don't cause slow-downs in the program being logged.
/// </para>
/// <para>
/// <c>GoogleStackdriverAppender</c> provides two methods of flushing this local buffer.
/// <list type="bullet">
/// <item><description>
/// The <see cref="Flush(TimeSpan, CancellationToken)"/> and <see cref="FlushAsync(TimeSpan, CancellationToken)"/>
/// flush local buffer entries to Google Stackdriver, waiting a maximum of the specified
/// <see cref="TimeSpan"/>. These methods return <c>true</c> if all locally buffered
/// entries were successfully flushed, or <c>false</c> otherwise.
/// </description></item>
/// <item><description>
/// <c>GoogleStackdriverAppender</c> implements <see cref="IDisposable"/>. This calls
/// <see cref="Flush(TimeSpan, CancellationToken)"/> with the timeout configured in
/// <see cref="DisposeTimeoutSeconds"/>, then closes the appender so no further logging
/// can be performed. It is not generally necessary to call <see cref="Dispose"/>.
/// </description></item>
/// </list>
/// </para>
/// </remarks>
public sealed partial class GoogleStackdriverAppender : AppenderSkeleton, IDisposable
{
// TODO:
// * Various argument validations
// * Send unsent logs on program exit? Using AppDomain.ProcessExit
// - Note this only allows 2 seconds
private struct CustomLabelPattern
{
public CustomLabelPattern(string key, PatternLayout layout)
{
Key = key;
Layout = layout;
}
public string Key { get; }
public PatternLayout Layout { get; }
}
internal const string s_logsLostWarningMessage = "Logs lost due to insufficient process-local storage: {0} -> {1}";
internal const string s_lostDateTimeFmt = "yyyy-MM-dd' 'HH:mm:ss'Z'";
internal const string s_mismatchedProjectIdMessage = "Detected project ID does not match configured project ID; using detected project ID.";
internal static readonly string[] s_oAuthScopes = new string[]
{
"https://www.googleapis.com/auth/logging.write"
};
/// <summary>
/// Construct a Google Stackdriver appender.
/// </summary>
public GoogleStackdriverAppender() { }
// For testing only.
internal GoogleStackdriverAppender(LoggingServiceV2Client client,
IScheduler scheduler, IClock clock, Platform platform = null)
{
_client = GaxPreconditions.CheckNotNull(client, nameof(client));
_scheduler = GaxPreconditions.CheckNotNull(scheduler, nameof(scheduler));
_clock = GaxPreconditions.CheckNotNull(clock, nameof(clock));
_platform = platform;
}
private static readonly Dictionary<Level, LogSeverity> s_levelMap = new Dictionary<Level, LogSeverity>
{
// Map Log4net levels to Stackdriver LogSeveritys.
// The following levels are missing from the map:
// Level.Off => This is not for use as a logging level
// Level.All => This is not for use as a logging level
// Level.Log4Net_Debug => Duplicate of Level.Emergency
// Level.Fine => Duplicate of Level.Debug
// Level.Finer => Duplicate of Level.Trace
// Level.Finest => Duplicate of Level.Verbose
{ Level.Emergency, LogSeverity.Emergency },
{ Level.Fatal, LogSeverity.Emergency },
{ Level.Alert, LogSeverity.Alert },
{ Level.Critical, LogSeverity.Critical },
{ Level.Severe, LogSeverity.Critical },
{ Level.Error, LogSeverity.Error },
{ Level.Warn, LogSeverity.Warning },
{ Level.Notice, LogSeverity.Notice },
{ Level.Info, LogSeverity.Info },
{ Level.Debug, LogSeverity.Debug },
{ Level.Trace, LogSeverity.Debug },
{ Level.Verbose, LogSeverity.Debug },
};
private readonly object _lock = new object();
private readonly string _instanceId = Guid.NewGuid().ToString();
private LoggingServiceV2Client _client;
private IScheduler _scheduler;
private IClock _clock;
private Platform _platform;
private MonitoredResource _resource;
private CustomLabelPattern[] _customLabelsPatterns;
private string _logName;
private ILogQueue _logQ;
private LogUploader _logUploader;
private Task<long?> _initIdTask;
private bool _isActivated;
private long _currentId = -1; // Initialised here, in case Flush() is called before any log entries written.
private readonly List<Label> _resourceLabels = new List<Label>();
private readonly List<Label> _customLabels = new List<Label>();
private readonly HashSet<MetaDataType> _withMetaData = new HashSet<MetaDataType>();
private readonly LruCache<string, System.Type> _typeCache = new LruCache<string, System.Type>(1000);
private List<Func<LogEntry>> _preLogs = new List<Func<LogEntry>>();
/// <inheritdoc/>
public override void ActivateOptions()
{
// Validate configuration
GaxPreconditions.CheckState(string.IsNullOrWhiteSpace(CredentialFile) || string.IsNullOrWhiteSpace(CredentialJson),
$"{nameof(CredentialFile)} and {nameof(CredentialJson)} must not both be set.");
GaxPreconditions.CheckState(LogId != null, $"{nameof(LogId)} must be set.");
GaxPreconditions.CheckState(MaxUploadBatchSize > 0, $"{nameof(MaxUploadBatchSize)} must be > 0");
GaxPreconditions.CheckEnumValue<LocalQueueType>(LocalQueueType, nameof(LocalQueueType));
base.ActivateOptions();
// Initialise services if not already initialised for testing
_client = _client ?? BuildLoggingServiceClient();
_scheduler = _scheduler ?? SystemScheduler.Instance;
_clock = _clock ?? SystemClock.Instance;
_platform = _platform ?? Platform.Instance();
// Normalize string configuration
ResourceType = string.IsNullOrWhiteSpace(ResourceType) ? null : ResourceType;
ProjectId = string.IsNullOrWhiteSpace(ProjectId) ? null : ProjectId;
LogId = string.IsNullOrWhiteSpace(LogId) ? null : LogId;
switch (LocalQueueType)
{
case LocalQueueType.Memory:
GaxPreconditions.CheckState(MaxMemoryCount > 0 || MaxMemorySize > 0,
$"Either {nameof(MaxMemoryCount)} or {nameof(MaxMemorySize)} must be configured to be > 0");
break;
default:
throw new InvalidOperationException($"Invalid {nameof(Log4Net.LocalQueueType)}: '{LocalQueueType}'");
}
GaxPreconditions.CheckState(ServerErrorBackoffDelaySeconds >= 1,
$"{nameof(ServerErrorBackoffDelaySeconds)} must be >= 1 second.");
GaxPreconditions.CheckState(ServerErrorBackoffMultiplier > 1.1999999,
$"{nameof(ServerErrorBackoffMultiplier)} must be >= 1.2");
GaxPreconditions.CheckState(ServerErrorBackoffMaxDelaySeconds >= 20,
$"{nameof(ServerErrorBackoffMaxDelaySeconds)} must be >= 20 seconds.");
ActivateLogIdAndResource();
switch (LocalQueueType)
{
case LocalQueueType.Memory:
_logQ = new MemoryLogQueue(MaxMemorySize, MaxMemoryCount);
break;
default:
throw new InvalidOperationException($"Invalid {nameof(Log4Net.LocalQueueType)}: '{LocalQueueType}'");
}
_initIdTask = Task.Run(_logQ.GetPreviousExecutionIdAsync);
var logsLostWarningEntry = new LogEntry
{
TextPayload = s_logsLostWarningMessage,
Severity = LogSeverity.Warning,
LogName = _logName,
Resource = _resource,
// Patterns included in custom labels will not be used in this "logs lost" entry.
// The pattern itself will be logged, regardless of the "UsePatternWithinCustomLabels" setting.
// This is acceptable as most patterns will be irrelevant in this context.
Labels = { _customLabels.ToDictionary(x => x.Key, x => x.Value) },
};
var serverErrorRetrySettings = RetrySettings.FromExponentialBackoff(maxAttempts: int.MaxValue,
initialBackoff: TimeSpan.FromSeconds(ServerErrorBackoffDelaySeconds),
maxBackoff: TimeSpan.FromSeconds(ServerErrorBackoffMaxDelaySeconds),
backoffMultiplier: ServerErrorBackoffMultiplier,
retryFilter: _ => true); // Ignored
_logUploader = new LogUploader(
_client, _scheduler, _clock,
_logQ, logsLostWarningEntry, MaxUploadBatchSize,
serverErrorRetrySettings);
if (_usePatternWithinCustomLabels)
{
// Initialize a pattern layout for each custom label.
_customLabelsPatterns = _customLabels.Select(x => new CustomLabelPattern(x.Key, new PatternLayout(x.Value))).ToArray();
}
_isActivated = true;
}
private LoggingServiceV2Client BuildLoggingServiceClient() =>
new LoggingServiceV2ClientBuilder
{
ChannelCredentials = GetCredentialFromConfiguration()?.ToChannelCredential()
}.Build();
private GoogleCredential GetCredentialFromConfiguration()
{
var credential =
!string.IsNullOrWhiteSpace(CredentialFile) ? GoogleCredential.FromFile(CredentialFile) :
!string.IsNullOrWhiteSpace(CredentialJson) ? GoogleCredential.FromJson(CredentialJson) :
null;
if (credential == null)
{
return null;
}
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped(s_oAuthScopes);
}
return credential;
}
private void ActivateLogIdAndResource()
{
string projectId = null;
MonitoredResource resource = null;
if (!DisableResourceTypeDetection)
{
resource = MonitoredResourceBuilder.FromPlatform(_platform);
resource.Labels.TryGetValue("project_id", out projectId);
}
if (projectId == null)
{
// Either platform detection is disabled, or it detected an unknown platform
// So use the manually configured projectId and override the resource
projectId = GaxPreconditions.CheckNotNull(ProjectId, nameof(ProjectId));
if (ResourceType == null)
{
resource = new MonitoredResource { Type = "global", Labels = { { "project_id", projectId } } };
}
else
{
resource = new MonitoredResource { Type = ResourceType, Labels = { _resourceLabels.ToDictionary(x => x.Key, x => x.Value) } };
}
}
else
{
if (ProjectId != null && projectId != ProjectId)
{
_preLogs.Add(() => BuildLogEntry(new LoggingEvent(new LoggingEventData
{
Level = Level.Warn,
LoggerName = "",
Message = s_mismatchedProjectIdMessage,
TimeStampUtc = _clock.GetCurrentDateTimeUtc()
})));
}
}
_resource = resource;
_logName = new LogName(projectId, LogId).ToString();
}
private LogEntry BuildLogEntry(LoggingEvent loggingEvent)
{
const string unknown = "[unknown]";
var labels = new Dictionary<string, string>();
LogEntrySourceLocation sourceLocation = null;
if (_withMetaData.Contains(MetaDataType.Location))
{
sourceLocation = BuildLogEntryLocation(loggingEvent);
}
if (_withMetaData.Contains(MetaDataType.Identity))
{
labels.Add(nameof(MetaDataType.Identity), loggingEvent.Identity ?? unknown);
}
if (_withMetaData.Contains(MetaDataType.ThreadName))
{
labels.Add(nameof(MetaDataType.ThreadName), loggingEvent.ThreadName ?? unknown);
}
if (_withMetaData.Contains(MetaDataType.UserName))
{
labels.Add(nameof(MetaDataType.UserName), loggingEvent.UserName ?? unknown);
}
if (_withMetaData.Contains(MetaDataType.Domain))
{
labels.Add(nameof(MetaDataType.Domain), loggingEvent.Domain ?? unknown);
}
if (_withMetaData.Contains(MetaDataType.LoggerName))
{
labels.Add(nameof(MetaDataType.LoggerName), loggingEvent.LoggerName ?? unknown);
}
if (_withMetaData.Contains(MetaDataType.Level))
{
labels.Add(nameof(MetaDataType.Level), loggingEvent.Level?.Name ?? unknown);
}
TryAddGitRevisionId(labels);
if (_customLabelsPatterns != null)
{
foreach (var pattern in _customLabelsPatterns)
{
labels.Add(pattern.Key, pattern.Layout.Format(loggingEvent));
}
}
else
{
foreach (var customLabel in _customLabels)
{
labels.Add(customLabel.Key, customLabel.Value);
}
}
var logEntry = new LogEntry
{
Severity = s_levelMap[loggingEvent.Level],
Timestamp = loggingEvent.TimeStamp.ToTimestamp(),
LogName = _logName,
Resource = _resource,
Labels = { labels },
};
// Note that we can't just unconditionally set both TextPayload and JsonPayload, as they're items in a oneof in the proto.
var jsonPayload = JsonLayout?.Format(loggingEvent);
if (jsonPayload is null)
{
logEntry.TextPayload = RenderLoggingEvent(loggingEvent);
}
else
{
logEntry.JsonPayload = jsonPayload;
}
if (sourceLocation != null)
{
logEntry.SourceLocation = sourceLocation;
}
return logEntry;
}
private void TryAddGitRevisionId(Dictionary<string, string> labels)
{
try
{
var gitId = SourceContext.AppSourceContext?.Git?.RevisionId;
if (!String.IsNullOrWhiteSpace(gitId))
{
labels.Add(SourceContext.GitRevisionIdLogLabel, gitId);
}
}
catch (Exception ex) when (
ex is SecurityException
|| ex is InvalidProtocolBufferException
|| ex is InvalidJsonException
|| ex is UnauthorizedAccessException)
{
// This is best-effort only, exceptions from reading/parsing the source_context.json are ignored.
}
}
private LogEntrySourceLocation BuildLogEntryLocation(LoggingEvent loggingEvent)
{
string file = null;
long? line = null;
string function = null;
if (loggingEvent.LocationInformation?.FileName != null)
{
file = loggingEvent.LocationInformation?.FileName;
if (file == "?")
{
file = null;
}
}
if (long.TryParse(loggingEvent.LocationInformation?.LineNumber, out long lineNumber))
{
line = lineNumber;
}
string function0 = null;
string fullTypeName = loggingEvent.LocationInformation?.ClassName;
if (fullTypeName != null)
{
var type = _typeCache.GetOrAdd(fullTypeName, () =>
{
try
{
return AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(a => a.GetTypes())
.FirstOrDefault(t => t.FullName == fullTypeName);
}
catch
{
// Ignore exceptions. This is best-effort only, and expected to fail in some situations.
// Returning null caches the failure.
return null;
}
});
if (type != null)
{
function0 = type.AssemblyQualifiedName;
}
}
string function1 = loggingEvent.LocationInformation?.MethodName;
if (function1 == "?")
{
function1 = null;
}
if (function0 != null || function1 != null)
{
function = $"[{function0 ?? ""}].{function1 ?? ""}";
}
if (file != null || line != null || function != null)
{
var sourceLocation = new LogEntrySourceLocation();
if (file != null)
{
sourceLocation.File = file;
}
if (line != null)
{
sourceLocation.Line = line.Value;
}
if (function != null)
{
// Format of "function" is:
// "[<assembly-qualified type name>].<method name>"
// E.g. "[Google.Cloud.Logging.Log4Net.Tests.Log4NetTest, Google.Cloud.Logging.Log4Net.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=185c282632e132a0].LogInfo"
sourceLocation.Function = function;
}
return sourceLocation;
}
return null;
}
private void Write(IEnumerable<LogEntry> logEntries)
{
lock (_lock)
{
if (_initIdTask != null)
{
_currentId = _initIdTask.Result ?? -1;
_initIdTask = null;
}
if (_preLogs != null)
{
logEntries = _preLogs.Select(x => x()).Concat(logEntries);
_preLogs = null;
}
var logEntriesExtra = logEntries
.Select(entry =>
{
long id = ++_currentId;
entry.InsertId = $"{_instanceId}:{id}";
return new LogEntryExtra(id, entry);
})
.ToList();
_logQ.Enqueue(logEntriesExtra);
}
_logUploader.TriggerUpload();
}
/// <inheritdoc/>
protected override void Append(LoggingEvent loggingEvent)
{
if (!_isActivated)
{
throw new InvalidOperationException($"{nameof(ActivateOptions)}() must be called before using this appender.");
}
var entries = new[] { BuildLogEntry(loggingEvent) };
Write(entries);
}
/// <inheritdoc/>
protected override void Append(LoggingEvent[] loggingEvents)
{
if (!_isActivated)
{
throw new InvalidOperationException($"{nameof(ActivateOptions)}() must be called before using this appender.");
}
var entries = loggingEvents.Select(x => BuildLogEntry(x)).ToList();
Write(entries);
}
/// <summary>
/// Flush locally buffered log entries to the server.
/// </summary>
/// <param name="timeout">The maxmimum time to spend waiting for the flush to complete.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.
/// The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task representing whether the flush completed within the timeout.</returns>
public Task<bool> FlushAsync(TimeSpan timeout, CancellationToken cancellationToken = default)
{
if (!_isActivated)
{
throw new InvalidOperationException($"{nameof(ActivateOptions)}() must be called before using this appender.");
}
long untilId;
lock (_lock)
{
untilId = _currentId;
}
return _logUploader.FlushAsync(untilId, timeout, cancellationToken);
}
/// <summary>
/// Flush locally buffered log entries to the server.
/// </summary>
/// <param name="timeout">The maxmimum time to spend waiting for the flush to complete.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.
/// The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>Whether the flush completed within the timeout.</returns>
public bool Flush(TimeSpan timeout, CancellationToken cancellationToken = default)
{
if (!_isActivated)
{
throw new InvalidOperationException($"{nameof(ActivateOptions)}() must be called before using this appender.");
}
return Task.Run(async () => await FlushAsync(timeout, cancellationToken).ConfigureAwait(false)).Result;
}
/// <summary>
/// Flush locally buffered log entries to the server.
/// </summary>
/// <param name="millisecondsTimeout">The maxmimum time in milliseconds to spend waiting for the flush to complete.</param>
/// <returns>Whether the flush completed within the timeout.</returns>
public override bool Flush(int millisecondsTimeout) => Flush(TimeSpan.FromMilliseconds(millisecondsTimeout), default);
/// <summary>
/// Dispose of this appender, by flushing locally buffer entries then closing the appender.
/// </summary>
/// <remarks>
/// The flush timeout is configured using the <c>DisposeTimeoutSeconds</c> configuration option.
/// This defaults to 30 seconds if not set.
/// </remarks>
public void Dispose()
{
if (!_isActivated)
{
// Appender not activated, so Dispose is a nop.
return;
}
bool flushSucceeded = Flush(TimeSpan.FromSeconds(DisposeTimeoutSeconds));
if (!flushSucceeded)
{
log4net.Util.LogLog.Warn(typeof(LogUploader), "Dispose() failed to flush log.");
}
Close();
}
/// <inheritdoc/>
protected override void OnClose()
{
base.OnClose();
if (!_isActivated)
{
// Appender not activated, so Close is a nop.
return;
}
_logUploader.Close();
}
}
}
| |
using System.Threading.Tasks;
using Microsoft.Kinect;
using Microsoft.Kinect.Tools;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Threading;
namespace NodeKinect2
{
public class Startup
{
private static NodeKinect instance;
public async Task<object> Invoke(dynamic input)
{
if (instance == null)
{
instance = new NodeKinect(input);
}
return true;
}
public async Task<object> Open(dynamic input)
{
return instance.Open(input);
}
public async Task<object> Replay(dynamic input)
{
return instance.Replay(input);
}
public async Task<object> OpenDepthReader(dynamic input)
{
return instance.OpenDepthReader(input);
}
public async Task<object> OpenBodyReader(dynamic input)
{
return instance.OpenBodyReader(input);
}
public async Task<object> OpenColorReader(dynamic input)
{
return instance.OpenColorReader(input);
}
public async Task<object> OpenInfraredReader(dynamic input)
{
return instance.OpenInfraredReader(input);
}
public async Task<object> OpenLongExposureInfraredReader(dynamic input)
{
return instance.OpenLongExposureInfraredReader(input);
}
public async Task<object> Close(dynamic input)
{
return instance.Close(input);
}
}
public class NodeKinect
{
const int LedWidth = 192;
const int LedHeight = 320;
private KinectSensor kinectSensor = null;
private FrameDescription depthFrameDescription = null;
private DepthFrameReader depthFrameReader = null;
/// <summary>
/// Map depth range to byte range
/// </summary>
private const int MapDepthToByte = 8000 / 256;
private byte[] depthPixels = null;
private byte[] truncatedDepthPixels = null;
private bool processingDepthFrame = false;
private ColorFrameReader colorFrameReader = null;
private FrameDescription colorFrameDescription = null;
private byte[] colorPixels = null;
private byte[] truncatedColorPixels = null;
private bool processingColorFrame = false;
private InfraredFrameReader infraredFrameReader = null;
private FrameDescription infraredFrameDescription = null;
private byte[] infraredPixels = null;
private byte[] truncatedInfraredPixels = null;
private bool processingInfraredFrame = false;
private LongExposureInfraredFrameReader longExposureInfraredFrameReader = null;
private FrameDescription longExposureInfraredFrameDescription = null;
private byte[] longExposureInfraredPixels = null;
private byte[] truncatedLongExposureInfraredPixels = null;
private bool processingLongExposureInfraredFrame = false;
/// <summary>
/// Maximum value (as a float) that can be returned by the InfraredFrame
/// </summary>
private const float InfraredSourceValueMaximum = (float)ushort.MaxValue;
/// <summary>
/// The value by which the infrared source data will be scaled
/// </summary>
private const float InfraredSourceScale = 0.75f;
/// <summary>
/// Smallest value to display when the infrared data is normalized
/// </summary>
private const float InfraredOutputValueMinimum = 0.01f;
/// <summary>
/// Largest value to display when the infrared data is normalized
/// </summary>
private const float InfraredOutputValueMaximum = 1.0f;
private CoordinateMapper coordinateMapper = null;
private BodyFrameReader bodyFrameReader = null;
private Body[] bodies = null;
private Func<object, Task<object>> logCallback;
private Func<object, Task<object>> bodyFrameCallback;
private Func<object, Task<object>> depthFrameCallback;
private Func<object, Task<object>> colorFrameCallback;
private Func<object, Task<object>> infraredFrameCallback;
private Func<object, Task<object>> longExposureInfraredFrameCallback;
private bool isReplaying = false;
private String replayFilePath = null;
public NodeKinect(dynamic input)
{
this.logCallback = (Func<object, Task<object>>)input.logCallback;
this.logCallback("Created NodeKinect Instance");
}
public async Task<object> Open(dynamic input)
{
this.logCallback("Open");
this.kinectSensor = KinectSensor.GetDefault();
if (this.kinectSensor != null)
{
this.coordinateMapper = this.kinectSensor.CoordinateMapper;
this.kinectSensor.Open();
return true;
}
return false;
}
public void ReplayForever()
{
try
{
using (KStudioClient client = KStudio.CreateClient())
{
client.ConnectToService();
while (true)
{
KStudioPlayback playback = client.CreatePlayback(this.replayFilePath);
playback.LoopCount = 0;
playback.Start();
this.isReplaying = true;
while (playback.State == KStudioPlaybackState.Playing)
{
Thread.Sleep(500);
}
}
client.DisconnectFromService();
}
} catch (Exception e) {
logCallback("ReplayForever exception: " + e.Message);
}
}
public async Task<object> Replay(dynamic input)
{
this.replayFilePath = (String)input.filePath;
this.logCallback("Replay " + this.replayFilePath);
ThreadStart work = this.ReplayForever;
Thread thread = new Thread(work);
thread.Start();
return true;
}
public async Task<object> OpenDepthReader(dynamic input)
{
this.logCallback("OpenDepthReader");
if (this.depthFrameReader != null)
{
return false;
}
this.depthFrameCallback = (Func<object, Task<object>>)input.depthFrameCallback;
this.depthFrameDescription = this.kinectSensor.DepthFrameSource.FrameDescription;
this.logCallback("depth: " + this.depthFrameDescription.Width + "x" + this.depthFrameDescription.Height);
//depth data
this.depthFrameReader = this.kinectSensor.DepthFrameSource.OpenReader();
this.depthFrameReader.FrameArrived += this.DepthReader_FrameArrived;
this.depthPixels = new byte[this.depthFrameDescription.Width * this.depthFrameDescription.Height];
this.truncatedDepthPixels = new byte[NodeKinect.LedWidth * NodeKinect.LedHeight];
return true;
}
public async Task<object> OpenColorReader(dynamic input)
{
this.logCallback("OpenColorReader");
if (this.colorFrameReader != null)
{
return false;
}
this.colorFrameCallback = (Func<object, Task<object>>)input.colorFrameCallback;
this.colorFrameDescription = this.kinectSensor.ColorFrameSource.CreateFrameDescription(ColorImageFormat.Rgba);
this.logCallback("color: " + this.colorFrameDescription.Width + "x" + this.colorFrameDescription.Height);
this.colorFrameReader = this.kinectSensor.ColorFrameSource.OpenReader();
this.colorFrameReader.FrameArrived += this.ColorReader_ColorFrameArrived;
this.colorPixels = new byte[4 * this.colorFrameDescription.Width * this.colorFrameDescription.Height];
this.truncatedColorPixels = new byte[4 * NodeKinect.LedWidth * NodeKinect.LedHeight];
return true;
}
public async Task<object> OpenInfraredReader(dynamic input)
{
this.logCallback("OpenInfraredReader");
if (this.infraredFrameReader != null)
{
return false;
}
this.infraredFrameCallback = (Func<object, Task<object>>)input.infraredFrameCallback;
this.infraredFrameDescription = this.kinectSensor.InfraredFrameSource.FrameDescription;
this.logCallback("infrared: " + this.infraredFrameDescription.Width + "x" + this.infraredFrameDescription.Height);
//depth data
this.infraredFrameReader = this.kinectSensor.InfraredFrameSource.OpenReader();
this.infraredFrameReader.FrameArrived += this.InfraredReader_FrameArrived;
this.infraredPixels = new byte[this.infraredFrameDescription.Width * this.infraredFrameDescription.Height];
this.truncatedInfraredPixels = new byte[NodeKinect.LedWidth * NodeKinect.LedHeight];
return true;
}
public async Task<object> OpenLongExposureInfraredReader(dynamic input)
{
this.logCallback("OpenLongExposureInfraredReader");
if (this.longExposureInfraredFrameReader != null)
{
return false;
}
this.longExposureInfraredFrameCallback = (Func<object, Task<object>>)input.longExposureInfraredFrameCallback;
this.longExposureInfraredFrameDescription = this.kinectSensor.LongExposureInfraredFrameSource.FrameDescription;
this.logCallback("longExposureInfrared: " + this.longExposureInfraredFrameDescription.Width + "x" + this.longExposureInfraredFrameDescription.Height);
//depth data
this.longExposureInfraredFrameReader = this.kinectSensor.LongExposureInfraredFrameSource.OpenReader();
this.longExposureInfraredFrameReader.FrameArrived += this.LongExposureInfraredReader_FrameArrived;
this.longExposureInfraredPixels = new byte[this.longExposureInfraredFrameDescription.Width * this.longExposureInfraredFrameDescription.Height];
this.truncatedLongExposureInfraredPixels = new byte[NodeKinect.LedWidth * NodeKinect.LedHeight];
return true;
}
public async Task<object> OpenBodyReader(dynamic input)
{
this.logCallback("OpenBodyReader");
if (this.bodyFrameReader != null)
{
return false;
}
this.bodyFrameCallback = (Func<object, Task<object>>)input.bodyFrameCallback;
this.bodies = new Body[this.kinectSensor.BodyFrameSource.BodyCount];
this.bodyFrameReader = this.kinectSensor.BodyFrameSource.OpenReader();
this.bodyFrameReader.FrameArrived += this.BodyReader_FrameArrived;
return true;
}
public async Task<object> Close(object input)
{
if (this.depthFrameReader != null)
{
this.depthFrameReader.Dispose();
this.depthFrameReader = null;
}
if (this.colorFrameReader != null)
{
this.colorFrameReader.Dispose();
this.colorFrameReader = null;
}
if (this.infraredFrameReader != null)
{
this.infraredFrameReader.Dispose();
this.infraredFrameReader = null;
}
if (this.longExposureInfraredFrameReader != null)
{
this.longExposureInfraredFrameReader.Dispose();
this.longExposureInfraredFrameReader = null;
}
if (this.bodyFrameReader != null)
{
this.bodyFrameReader.Dispose();
this.bodyFrameReader = null;
}
if (this.kinectSensor != null)
{
this.kinectSensor.Close();
this.kinectSensor = null;
}
return true;
}
// given a 512x424 buffer, resize to LED dimensions
private void Rescale(byte[] originalBuffer, byte[] outBuffer)
{
// if we downscale 512x424 3x, the resulting resolution is
// 170.66x141.33 -- this 'covers' 640x360 (3.75x, 2.55y).
var downscaledX = 171;
var downscaledY = 142;
var outExtents = downscaledX * downscaledY;
var downscaled = new byte[outExtents];
var originalBufferWidth = 512; // hard coded for now
try
{
var y2 = 0;
var compression = 3;
for(var y = 0; y < downscaledY * compression; y += compression) {
var x2 = 0;
for(var x = 0; x < (downscaledX * compression); x += compression) {
var i = (y * originalBufferWidth + x);
var j = (y2 * downscaledX + x2);
if(i >= originalBuffer.Length || j >= outExtents)
{
continue;
}
// NB. averaging looks ugly. do not do this.
downscaled[j+0] = originalBuffer[i+0];
// outBuffer[j+0] = originalBuffer[i+0];
x2++;
}
y2++;
}
}
catch (Exception exc)
{
this.logCallback("Rescale exception (downsizing): " + exc.Message);
}
// now that we have a downscaled buffer, we want to
// 'truncate' to the equivalent of 192x320. the result is
// a 52x126 buffer.
var realX = 52;
var realY = 126;
var offsetWidth = 60;
var offsetHeight = 0;
var maxExtents = NodeKinect.LedHeight * NodeKinect.LedWidth;
var line = 0;
try
{
for(var j=0; j<realY; j++)
{
// 2,3,2,3,2,3,2,3... for height
var extraH = (j%2)==0 ? 2 : 3;
for(var m=0; m<extraH; m++)
{
var index = line * NodeKinect.LedWidth;
var obi = (j * downscaledX) + offsetWidth;
for(var i=0; i<realX; i++)
{
// 3,4,4,4,3,4,4,4... for width
var extraW = (i%4)==0 ? 3 : 4;
for(var n=0; n<extraW; n++)
{
if(index >= maxExtents)
{
// we may be slightly over due to uneven sampling.
continue;
}
outBuffer[index+0] = downscaled[obi+0];
index++;
}
obi++;
}
line++;
}
}
}
catch (Exception exc2)
{
this.logCallback("Rescale exception (truncating): " + exc2.Message);
}
}
private void DepthReader_FrameArrived(object sender, DepthFrameArrivedEventArgs e)
{
if (this.processingDepthFrame)
{
return;
}
this.processingDepthFrame = true;
bool depthFrameProcessed = false;
using (DepthFrame depthFrame = e.FrameReference.AcquireFrame())
{
if (depthFrame != null)
{
// the fastest way to process the body index data is to directly access
// the underlying buffer
using (Microsoft.Kinect.KinectBuffer depthBuffer = depthFrame.LockImageBuffer())
{
// verify data and write the color data to the display bitmap
if (((this.depthFrameDescription.Width * this.depthFrameDescription.Height) == (depthBuffer.Size / this.depthFrameDescription.BytesPerPixel)))
{
// Note: In order to see the full range of depth (including the less reliable far field depth)
// we are setting maxDepth to the extreme potential depth threshold
//ushort maxDepth = ushort.MaxValue;
// If you wish to filter by reliable depth distance, uncomment the following line:
ushort maxDepth = depthFrame.DepthMaxReliableDistance;
this.ProcessDepthFrameData(depthBuffer.UnderlyingBuffer, depthBuffer.Size, depthFrame.DepthMinReliableDistance, maxDepth);
depthFrameProcessed = true;
}
}
}
}
if (depthFrameProcessed)
{
this.Rescale(this.depthPixels, this.truncatedDepthPixels);
this.depthFrameCallback(this.truncatedDepthPixels);
//this.RenderDepthPixels();
}
this.processingDepthFrame = false;
}
/// <summary>
/// Directly accesses the underlying image buffer of the DepthFrame to
/// create a displayable bitmap.
/// This function requires the /unsafe compiler option as we make use of direct
/// access to the native memory pointed to by the depthFrameData pointer.
/// </summary>
/// <param name="depthFrameData">Pointer to the DepthFrame image data</param>
/// <param name="depthFrameDataSize">Size of the DepthFrame image data</param>
/// <param name="minDepth">The minimum reliable depth value for the frame</param>
/// <param name="maxDepth">The maximum reliable depth value for the frame</param>
private unsafe void ProcessDepthFrameData(IntPtr depthFrameData, uint depthFrameDataSize, ushort minDepth, ushort maxDepth)
{
// depth frame data is a 16 bit value
ushort* frameData = (ushort*)depthFrameData;
// convert depth to a visual representation
for (int i = 0; i < (int)(depthFrameDataSize / this.depthFrameDescription.BytesPerPixel); ++i)
{
// Get the depth for this pixel
ushort depth = frameData[i];
// To convert to a byte, we're mapping the depth value to the byte range.
// Values outside the reliable depth range are mapped to 0 (black).
this.depthPixels[i] = (byte)(depth >= minDepth && depth <= maxDepth ? (depth / MapDepthToByte) : 0);
}
}
private void ColorReader_ColorFrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
if (this.processingColorFrame)
{
return;
}
this.processingColorFrame = true;
bool colorFrameProcessed = false;
// ColorFrame is IDisposable
using (ColorFrame colorFrame = e.FrameReference.AcquireFrame())
{
if (colorFrame != null)
{
FrameDescription colorFrameDescription = colorFrame.FrameDescription;
using (KinectBuffer colorBuffer = colorFrame.LockRawImageBuffer())
{
colorFrame.CopyConvertedFrameDataToArray(this.colorPixels, ColorImageFormat.Rgba);
colorFrameProcessed = true;
}
// convert to LED dimensions (mostly ripped from the old js code)
try
{
var y2 = 0;
var compression = 3;
var offset = (((this.colorFrameDescription.Width / compression) - NodeKinect.LedWidth) / 2) * compression;
for(var y = 0; y < NodeKinect.LedHeight * compression; y += compression) {
var x2 = 0;
for(var x = offset; x < (NodeKinect.LedWidth * compression) + offset; x += compression) {
var i = 4 * (y * this.colorFrameDescription.Width + x);
var j = 4 * (y2 * NodeKinect.LedWidth + x2);
this.truncatedColorPixels[j+0] = this.colorPixels[i+0];
this.truncatedColorPixels[j+1] = this.colorPixels[i+1];
this.truncatedColorPixels[j+2] = this.colorPixels[i+2];
this.truncatedColorPixels[j+3] = this.colorPixels[i+3];
x2++;
}
y2++;
}
}
catch (Exception exc)
{
this.logCallback("colorFrame exception: " + exc.Message);
}
}
}
if (colorFrameProcessed)
{
this.colorFrameCallback(this.truncatedColorPixels);
}
this.processingColorFrame = false;
}
private void InfraredReader_FrameArrived(object sender, InfraredFrameArrivedEventArgs e)
{
if (this.processingInfraredFrame)
{
return;
}
this.processingInfraredFrame = true;
bool infraredFrameProcessed = false;
using (InfraredFrame infraredFrame = e.FrameReference.AcquireFrame())
{
if (infraredFrame != null)
{
// the fastest way to process the body index data is to directly access
// the underlying buffer
using (Microsoft.Kinect.KinectBuffer infraredBuffer = infraredFrame.LockImageBuffer())
{
// verify data and write the color data to the display bitmap
if (((this.infraredFrameDescription.Width * this.infraredFrameDescription.Height) == (infraredBuffer.Size / this.infraredFrameDescription.BytesPerPixel)))
{
this.ProcessInfraredFrameData(infraredBuffer.UnderlyingBuffer, infraredBuffer.Size, this.infraredFrameDescription.BytesPerPixel);
infraredFrameProcessed = true;
}
}
}
}
if (infraredFrameProcessed)
{
this.Rescale(this.infraredPixels, this.truncatedInfraredPixels);
this.infraredFrameCallback(this.truncatedInfraredPixels);
}
this.processingInfraredFrame = false;
}
private void LongExposureInfraredReader_FrameArrived(object sender, LongExposureInfraredFrameArrivedEventArgs e)
{
if (this.processingLongExposureInfraredFrame)
{
return;
}
this.processingLongExposureInfraredFrame = true;
bool longExposureInfraredFrameProcessed = false;
using (LongExposureInfraredFrame longExposureInfraredFrame = e.FrameReference.AcquireFrame())
{
if (longExposureInfraredFrame != null)
{
using (Microsoft.Kinect.KinectBuffer longExposureInfraredBuffer = longExposureInfraredFrame.LockImageBuffer())
{
// verify data and write the color data to the display bitmap
if (((this.longExposureInfraredFrameDescription.Width * this.longExposureInfraredFrameDescription.Height) == (longExposureInfraredBuffer.Size / this.longExposureInfraredFrameDescription.BytesPerPixel)))
{
this.ProcessLongExposureInfraredFrameData(longExposureInfraredBuffer.UnderlyingBuffer, longExposureInfraredBuffer.Size, this.longExposureInfraredFrameDescription.BytesPerPixel);
longExposureInfraredFrameProcessed = true;
}
}
}
}
if (longExposureInfraredFrameProcessed)
{
this.Rescale(this.longExposureInfraredPixels, this.truncatedLongExposureInfraredPixels);
this.longExposureInfraredFrameCallback(this.truncatedLongExposureInfraredPixels);
}
this.processingLongExposureInfraredFrame = false;
}
private unsafe void ProcessInfraredFrameData(IntPtr frameData, uint frameDataSize, uint bytesPerPixel)
{
ushort* lframeData = (ushort*)frameData;
int len = (int)(frameDataSize / bytesPerPixel);
for (int i = 0; i < len; ++i)
{
this.infraredPixels[i] = (byte) (0xff * Math.Min(InfraredOutputValueMaximum, (((float)lframeData[i] / InfraredSourceValueMaximum * InfraredSourceScale) * (1.0f - InfraredOutputValueMinimum)) + InfraredOutputValueMinimum));
}
}
private unsafe void ProcessLongExposureInfraredFrameData(IntPtr frameData, uint frameDataSize, uint bytesPerPixel)
{
ushort* lframeData = (ushort*)frameData;
int len = (int)(frameDataSize / bytesPerPixel);
for (int i = 0; i < len; ++i)
{
this.longExposureInfraredPixels[i] = (byte)(0xff * Math.Min(InfraredOutputValueMaximum, (((float)lframeData[i] / InfraredSourceValueMaximum * InfraredSourceScale) * (1.0f - InfraredOutputValueMinimum)) + InfraredOutputValueMinimum));
}
}
private void BodyReader_FrameArrived(object sender, BodyFrameArrivedEventArgs e)
{
bool dataReceived = false;
using (BodyFrame bodyFrame = e.FrameReference.AcquireFrame())
{
if (bodyFrame != null)
{
if (this.bodies == null)
{
this.bodies = new Body[bodyFrame.BodyCount];
}
bodyFrame.GetAndRefreshBodyData(this.bodies);
dataReceived = true;
}
}
if (dataReceived)
{
var jsBodies = new ArrayList();
foreach (Body body in this.bodies)
{
if (body.IsTracked)
{
IReadOnlyDictionary<JointType, Joint> joints = body.Joints;
// convert the joint points to depth (display) space
IDictionary<String, Object> jsJoints = new Dictionary<String, Object>();
foreach (JointType jointType in joints.Keys)
{
DepthSpacePoint depthSpacePoint = this.coordinateMapper.MapCameraPointToDepthSpace(joints[jointType].Position);
jsJoints[jointType.ToString()] = new
{
x = depthSpacePoint.X,
y = depthSpacePoint.Y
};
}
var jsBody = new
{
trackingId = body.TrackingId,
handLeftState = body.HandLeftState,
handRightState = body.HandRightState,
joints = jsJoints
};
jsBodies.Add(jsBody);
}
}
this.bodyFrameCallback(jsBodies);
}
}
}
}
| |
// 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 OLEDB.Test.ModuleCore;
using Xunit;
namespace System.Xml.Tests
{
public partial class CharCheckingReaderTest : CGenericTestModule
{
private static void RunTestCaseAsync(Func<CTestBase> testCaseGenerator)
{
CModInfo.CommandLine = "/async";
RunTestCase(testCaseGenerator);
}
private static void RunTestCase(Func<CTestBase> testCaseGenerator)
{
var module = new CharCheckingReaderTest();
module.Init(null);
module.AddChild(testCaseGenerator());
module.Execute();
Assert.Equal(0, module.FailCount);
}
private static void RunTest(Func<CTestBase> testCaseGenerator)
{
RunTestCase(testCaseGenerator);
RunTestCaseAsync(testCaseGenerator);
}
[Fact]
[OuterLoop]
public static void ErrorConditionReader()
{
RunTest(() => new TCErrorConditionReader() { Attribute = new TestCase() { Name = "ErrorCondition", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void DepthReader()
{
RunTest(() => new TCDepthReader() { Attribute = new TestCase() { Name = "Depth", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void NamespaceReader()
{
RunTest(() => new TCNamespaceReader() { Attribute = new TestCase() { Name = "Namespace", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void IsEmptyElementReader()
{
RunTest(() => new TCIsEmptyElementReader() { Attribute = new TestCase() { Name = "IsEmptyElement", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void XmlSpaceReader()
{
RunTest(() => new TCXmlSpaceReader() { Attribute = new TestCase() { Name = "XmlSpace", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void XmlLangReader()
{
RunTest(() => new TCXmlLangReader() { Attribute = new TestCase() { Name = "XmlLang", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void SkipReader()
{
RunTest(() => new TCSkipReader() { Attribute = new TestCase() { Name = "Skip", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void InvalidXMLReader()
{
RunTest(() => new TCInvalidXMLReader() { Attribute = new TestCase() { Name = "InvalidXML", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadOuterXmlReader()
{
RunTest(() => new TCReadOuterXmlReader() { Attribute = new TestCase() { Name = "ReadOuterXml", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeAccessReader()
{
RunTest(() => new TCAttributeAccessReader() { Attribute = new TestCase() { Name = "AttributeAccess", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ThisNameReader()
{
RunTest(() => new TCThisNameReader() { Attribute = new TestCase() { Name = "This(Name) and This(Name, Namespace)", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeReader()
{
RunTest(() => new TCMoveToAttributeReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeOrdinalReader()
{
RunTest(() => new TCGetAttributeOrdinalReader() { Attribute = new TestCase() { Name = "GetAttribute (Ordinal)", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void GetAttributeNameReader()
{
RunTest(() => new TCGetAttributeNameReader() { Attribute = new TestCase() { Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ThisOrdinalReader()
{
RunTest(() => new TCThisOrdinalReader() { Attribute = new TestCase() { Name = "This [Ordinal]", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToAttributeOrdinalReader()
{
RunTest(() => new TCMoveToAttributeOrdinalReader() { Attribute = new TestCase() { Name = "MoveToAttribute(Ordinal)", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToFirstAttributeReader()
{
RunTest(() => new TCMoveToFirstAttributeReader() { Attribute = new TestCase() { Name = "MoveToFirstAttribute()", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToNextAttributeReader()
{
RunTest(() => new TCMoveToNextAttributeReader() { Attribute = new TestCase() { Name = "MoveToNextAttribute()", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeTestReader()
{
RunTest(() => new TCAttributeTestReader() { Attribute = new TestCase() { Name = "Attribute Test when NodeType != Attributes", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void AttributeXmlDeclarationReader()
{
RunTest(() => new TCAttributeXmlDeclarationReader() { Attribute = new TestCase() { Name = "Attributes test on XmlDeclaration", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsReader()
{
RunTest(() => new TCXmlnsReader() { Attribute = new TestCase() { Name = "xmlns as local name", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void XmlnsPrefixReader()
{
RunTest(() => new TCXmlnsPrefixReader() { Attribute = new TestCase() { Name = "bounded namespace to xmlns prefix", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadInnerXmlReader()
{
RunTest(() => new TCReadInnerXmlReader() { Attribute = new TestCase() { Name = "ReadInnerXml", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToContentReader()
{
RunTest(() => new TCMoveToContentReader() { Attribute = new TestCase() { Name = "MoveToContent", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void IsStartElementReader()
{
RunTest(() => new TCIsStartElementReader() { Attribute = new TestCase() { Name = "IsStartElement", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadStartElementReader()
{
RunTest(() => new TCReadStartElementReader() { Attribute = new TestCase() { Name = "ReadStartElement", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadEndElementReader()
{
RunTest(() => new TCReadEndElementReader() { Attribute = new TestCase() { Name = "ReadEndElement", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ResolveEntityReader()
{
RunTest(() => new TCResolveEntityReader() { Attribute = new TestCase() { Name = "ResolveEntity and ReadAttributeValue", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void HasValueReader()
{
RunTest(() => new TCHasValueReader() { Attribute = new TestCase() { Name = "HasValue", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadAttributeValueReader()
{
RunTest(() => new TCReadAttributeValueReader() { Attribute = new TestCase() { Name = "ReadAttributeValue", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadReader()
{
RunTest(() => new TCReadReader() { Attribute = new TestCase() { Name = "Read", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void MoveToElementReader()
{
RunTest(() => new TCMoveToElementReader() { Attribute = new TestCase() { Name = "MoveToElement", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void DisposeReader()
{
RunTest(() => new TCDisposeReader() { Attribute = new TestCase() { Name = "Dispose", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void BufferBoundariesReader()
{
RunTest(() => new TCBufferBoundariesReader() { Attribute = new TestCase() { Name = "Buffer Boundaries", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileBeforeRead()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "BeforeRead", Desc = "BeforeRead" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterCloseInMiddle()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterCloseInTheMiddle", Desc = "AfterCloseInTheMiddle" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterClose()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterClose", Desc = "AfterClose" } });
}
[Fact]
[OuterLoop]
public static void XmlNodeIntegrityTestFileAfterReadIsFalse()
{
RunTest(() => new TCXmlNodeIntegrityTestFile() { Attribute = new TestCase() { Name = "AfterReadIsFalse", Desc = "AfterReadIsFalse" } });
}
[Fact]
[OuterLoop]
public static void ReadSubtreeReader()
{
RunTest(() => new TCReadSubtreeReader() { Attribute = new TestCase() { Name = "Read Subtree", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToDescendantReader()
{
RunTest(() => new TCReadToDescendantReader() { Attribute = new TestCase() { Name = "ReadToDescendant", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToNextSiblingReader()
{
RunTest(() => new TCReadToNextSiblingReader() { Attribute = new TestCase() { Name = "ReadToNextSibling", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadValueReader()
{
RunTest(() => new TCReadValueReader() { Attribute = new TestCase() { Name = "ReadValue", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBase64Reader()
{
RunTest(() => new TCReadContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadContentAsBase64", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBase64Reader()
{
RunTest(() => new TCReadElementContentAsBase64Reader() { Attribute = new TestCase() { Name = "ReadElementContentAsBase64", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadContentAsBinHexReader()
{
RunTest(() => new TCReadContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadContentAsBinHex", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadElementContentAsBinHexReader()
{
RunTest(() => new TCReadElementContentAsBinHexReader() { Attribute = new TestCase() { Name = "ReadElementContentAsBinHex", Desc = "CharCheckingReader" } });
}
[Fact]
[OuterLoop]
public static void ReadToFollowingReader()
{
RunTest(() => new TCReadToFollowingReader() { Attribute = new TestCase() { Name = "ReadToFollowing", Desc = "CharCheckingReader" } });
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using ExampleGallery.Direct3DInterop;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI;
using Microsoft.Graphics.Canvas.UI.Xaml;
using System;
using System.Numerics;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace ExampleGallery
{
public sealed partial class Direct3DInteropExample : Page
{
public bool SpinEnabled { get; set; }
public bool BloomEnabled { get; set; }
public float BloomIntensity { get; set; }
public float BloomThreshold { get; set; }
public float BloomBlur { get; set; }
// The TeapotRenderer class is provided by the ExampleGallery.Direct3DInterop project,
// which is written in C++/CX. It uses interop to combine Direct3D rendering with Win2D.
TeapotRenderer teapot;
float spinTheTeapot;
// Scrolling text is drawn into a rendertarget (by Win2D).
const string scrollingText = "This demo shows interop between Win2D and Direct3D.\n\n" +
"This scrolling text is drawn into a render target by Win2D.\n\n" +
"The teapot is drawn by Direct3D (via the DirectX Tool Kit).\n\n" +
"Bloom post processing uses Win2D image effects.";
const float textRenderTargetSize = 256;
const float textMargin = 8;
const float textScrollSpeed = 96;
const float fontSize = 42;
CanvasTextLayout textLayout;
CanvasRenderTarget textRenderTarget;
// Bloom postprocess uses Win2D image effects to create a glow around bright parts of the 3D model.
CanvasRenderTarget bloomRenderTarget;
LinearTransferEffect extractBrightAreas;
GaussianBlurEffect blurBrightAreas;
LinearTransferEffect adjustBloomIntensity;
BlendEffect bloomResult;
public Direct3DInteropExample()
{
SpinEnabled = true;
InitializeBloomFilter();
this.InitializeComponent();
}
void canvas_CreateResources(CanvasAnimatedControl sender, CanvasCreateResourcesEventArgs args)
{
// Create the Direct3D teapot model.
teapot = new TeapotRenderer(sender);
// Create Win2D resources for drawing the scrolling text.
var textFormat = new CanvasTextFormat
{
FontSize = fontSize,
HorizontalAlignment = CanvasHorizontalAlignment.Center
};
textLayout = new CanvasTextLayout(sender, scrollingText, textFormat, textRenderTargetSize - textMargin * 2, float.MaxValue);
textRenderTarget = new CanvasRenderTarget(sender, textRenderTargetSize, textRenderTargetSize);
// Set the scrolling text rendertarget (a Win2D object) as
// source texture for our 3D teapot model (which uses Direct3D).
teapot.SetTexture(textRenderTarget);
}
void canvas_Update(ICanvasAnimatedControl sender, CanvasAnimatedUpdateEventArgs args)
{
if (ThumbnailGenerator.IsDrawingThumbnail)
{
spinTheTeapot = 5.7f;
}
else if (SpinEnabled)
{
spinTheTeapot += (float)args.Timing.ElapsedTime.TotalSeconds;
}
}
void canvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args)
{
// Update the scrolling text rendertarget.
DrawScrollingText(args.Timing);
if (BloomEnabled && !ThumbnailGenerator.IsDrawingThumbnail)
{
// If the bloom filter is turned on, draw the teapot into a rendertarget.
DemandCreateBloomRenderTarget(sender);
using (var drawingSession = bloomRenderTarget.CreateDrawingSession())
{
drawingSession.Clear(Colors.Black);
DrawTeapot(sender, drawingSession);
}
// Apply the bloom filter, which uses the rendertarget containing the teapot as input,
// adds a glow effect, and draws the combined result to our CanvasAnimatedControl.
ApplyBloomFilter(args.DrawingSession);
}
else
{
// If not blooming, draw the teapot directly to the CanvasAnimatedControl swapchain.
DrawTeapot(sender, args.DrawingSession);
}
}
void DrawTeapot(ICanvasAnimatedControl sender, CanvasDrawingSession drawingSession)
{
Vector2 size = sender.Size.ToVector2();
// Draw some text (using Win2D) to make sure this appears behind the teapot.
if (!ThumbnailGenerator.IsDrawingThumbnail)
{
drawingSession.DrawText("Text drawn before the teapot", size * new Vector2(0.5f, 0.1f), Colors.Gray);
}
// Draw the teapot (using Direct3D).
teapot.SetWorld(Matrix4x4.CreateFromYawPitchRoll(-spinTheTeapot, spinTheTeapot / 23, spinTheTeapot / 42));
teapot.SetView(Matrix4x4.CreateLookAt(new Vector3(1.5f, 1, 0), Vector3.Zero, Vector3.UnitY));
teapot.SetProjection(Matrix4x4.CreatePerspectiveFieldOfView(1, size.X / size.Y, 0.1f, 10f));
teapot.Draw(drawingSession);
// Draw more text (using Win2D) to make sure this appears above the teapot.
if (!ThumbnailGenerator.IsDrawingThumbnail)
{
drawingSession.DrawText("\nText drawn after the teapot", size * new Vector2(0.5f, 0.1f), Colors.Gray);
}
}
void DrawScrollingText(CanvasTimingInformation timing)
{
// We draw the text into a rendertarget, and update this every frame to make it scroll.
// The resulting rendertarget is then mapped as a texture onto the Direct3D teapot model.
using (var drawingSession = textRenderTarget.CreateDrawingSession())
{
drawingSession.Clear(Colors.Firebrick);
drawingSession.DrawRectangle(0, 0, textRenderTargetSize - 1, textRenderTargetSize - 1, Colors.DarkRed);
float wrapPosition = (float)textLayout.LayoutBounds.Height + textRenderTargetSize;
float scrollOffset = textRenderTargetSize - ((float)timing.TotalTime.TotalSeconds * textScrollSpeed) % wrapPosition;
drawingSession.DrawTextLayout(textLayout, new Vector2(textMargin, scrollOffset), Colors.Black);
}
}
void InitializeBloomFilter()
{
BloomEnabled = true;
// A bloom filter makes graphics appear to be bright and glowing by adding blur around only
// the brightest parts of the image. This approximates the look of HDR (high dynamic range)
// rendering, in which the color of the brightest light sources spills over onto surrounding
// pixels.
//
// Many different visual styles can be achieved by adjusting these settings:
//
// Intensity = how much bloom is added
// 0 = none
//
// Threshold = how bright does a pixel have to be in order for it to bloom
// 0 = the entire image blooms equally
//
// Blur = how much the glow spreads sideways around bright areas
BloomIntensity = 200;
BloomThreshold = 80;
BloomBlur = 48;
// Before drawing, properties of these effects will be adjusted to match the
// current settings (see ApplyBloomFilter), and an input image connected to
// extractBrightAreas.Source and bloomResult.Background (see DemandCreateBloomRenderTarget).
// Step 1: use a transfer effect to extract only pixels brighter than the threshold.
extractBrightAreas = new LinearTransferEffect
{
ClampOutput = true,
};
// Step 2: blur these bright pixels.
blurBrightAreas = new GaussianBlurEffect
{
Source = extractBrightAreas,
};
// Step 3: adjust how much bloom is wanted.
adjustBloomIntensity = new LinearTransferEffect
{
Source = blurBrightAreas,
};
// Step 4: blend the bloom over the top of the original image.
bloomResult = new BlendEffect
{
Foreground = adjustBloomIntensity,
Mode = BlendEffectMode.Screen,
};
}
void ApplyBloomFilter(CanvasDrawingSession drawingSession)
{
// Configure effects to use the latest threshold, blur, and intensity settings.
extractBrightAreas.RedSlope =
extractBrightAreas.GreenSlope =
extractBrightAreas.BlueSlope = 1 / (1 - BloomThreshold / 100);
extractBrightAreas.RedOffset =
extractBrightAreas.GreenOffset =
extractBrightAreas.BlueOffset = -BloomThreshold / 100 / (1 - BloomThreshold / 100);
blurBrightAreas.BlurAmount = BloomBlur;
adjustBloomIntensity.RedSlope =
adjustBloomIntensity.GreenSlope =
adjustBloomIntensity.BlueSlope = BloomIntensity / 100;
// Apply the bloom effect.
drawingSession.DrawImage(bloomResult);
}
int DipsToPixelSize(ICanvasAnimatedControl sender, float dips)
{
System.Diagnostics.Debug.Assert(dips > 0);
return Math.Max(sender.ConvertDipsToPixels(dips, CanvasDpiRounding.Round), 1);
}
void DemandCreateBloomRenderTarget(ICanvasAnimatedControl sender)
{
// Early-out if we already have a rendertarget of the correct size.
// Compare sizes as pixels rather than DIPs to avoid rounding artifacts.
if (bloomRenderTarget != null &&
bloomRenderTarget.SizeInPixels.Width == DipsToPixelSize(sender, (float)sender.Size.Width) &&
bloomRenderTarget.SizeInPixels.Height == DipsToPixelSize(sender, (float)sender.Size.Height))
{
return;
}
// Destroy the old rendertarget.
if (bloomRenderTarget != null)
{
bloomRenderTarget.Dispose();
}
// Create the new rendertarget.
bloomRenderTarget = new CanvasRenderTarget(sender, sender.Size);
// Configure the bloom effect to use this new rendertarget.
extractBrightAreas.Source = bloomRenderTarget;
bloomResult.Background = bloomRenderTarget;
}
private void control_Unloaded(object sender, RoutedEventArgs e)
{
// Explicitly remove references to allow the Win2D controls to get garbage collected
canvas.RemoveFromVisualTree();
canvas = null;
}
}
}
| |
namespace android.inputmethodservice
{
[global::MonoJavaBridge.JavaClass()]
public partial class KeyboardView : android.view.View, android.view.View.OnClickListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static KeyboardView()
{
InitJNI();
}
protected KeyboardView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_))]
public interface OnKeyboardActionListener : global::MonoJavaBridge.IJavaObject
{
void onKey(int arg0, int[] arg1);
void onPress(int arg0);
void onRelease(int arg0);
void onText(java.lang.CharSequence arg0);
void swipeLeft();
void swipeRight();
void swipeDown();
void swipeUp();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener))]
public sealed partial class OnKeyboardActionListener_ : java.lang.Object, OnKeyboardActionListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnKeyboardActionListener_()
{
InitJNI();
}
internal OnKeyboardActionListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onKey4611;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onKey(int arg0, int[] arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onKey4611, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onKey4611, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _onPress4612;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onPress(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onPress4612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onPress4612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onRelease4613;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onRelease(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onRelease4613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onRelease4613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onText4614;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onText(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onText4614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onText4614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _swipeLeft4615;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeLeft()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeLeft4615);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeLeft4615);
}
internal static global::MonoJavaBridge.MethodId _swipeRight4616;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeRight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeRight4616);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeRight4616);
}
internal static global::MonoJavaBridge.MethodId _swipeDown4617;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeDown()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeDown4617);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeDown4617);
}
internal static global::MonoJavaBridge.MethodId _swipeUp4618;
void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeUp()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeUp4618);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeUp4618);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/inputmethodservice/KeyboardView$OnKeyboardActionListener"));
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onKey4611 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onKey", "(I[I)V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onPress4612 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onPress", "(I)V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onRelease4613 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onRelease", "(I)V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._onText4614 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onText", "(Ljava/lang/CharSequence;)V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeLeft4615 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeLeft", "()V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeRight4616 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeRight", "()V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeDown4617 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeDown", "()V");
global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._swipeUp4618 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeUp", "()V");
}
}
internal static global::MonoJavaBridge.MethodId _closing4619;
public virtual void closing()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._closing4619);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._closing4619);
}
internal static global::MonoJavaBridge.MethodId _onClick4620;
public virtual void onClick(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onClick4620, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onClick4620, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onTouchEvent4621;
public override bool onTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onTouchEvent4621, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onTouchEvent4621, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onDetachedFromWindow4622;
public virtual new void onDetachedFromWindow()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onDetachedFromWindow4622);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onDetachedFromWindow4622);
}
internal static global::MonoJavaBridge.MethodId _onSizeChanged4623;
public virtual new void onSizeChanged(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onSizeChanged4623, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onSizeChanged4623, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _onDraw4624;
public virtual new void onDraw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onDraw4624, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onDraw4624, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onMeasure4625;
public virtual new void onMeasure(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onMeasure4625, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onMeasure4625, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setShifted4626;
public virtual bool setShifted(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setShifted4626, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setShifted4626, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isShifted4627;
public virtual bool isShifted()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._isShifted4627);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._isShifted4627);
}
internal static global::MonoJavaBridge.MethodId _swipeLeft4628;
protected virtual void swipeLeft()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._swipeLeft4628);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._swipeLeft4628);
}
internal static global::MonoJavaBridge.MethodId _swipeRight4629;
protected virtual void swipeRight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._swipeRight4629);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._swipeRight4629);
}
internal static global::MonoJavaBridge.MethodId _swipeDown4630;
protected virtual void swipeDown()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._swipeDown4630);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._swipeDown4630);
}
internal static global::MonoJavaBridge.MethodId _swipeUp4631;
protected virtual void swipeUp()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._swipeUp4631);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._swipeUp4631);
}
internal static global::MonoJavaBridge.MethodId _setOnKeyboardActionListener4632;
public virtual void setOnKeyboardActionListener(android.inputmethodservice.KeyboardView.OnKeyboardActionListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setOnKeyboardActionListener4632, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setOnKeyboardActionListener4632, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOnKeyboardActionListener4633;
protected virtual global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener getOnKeyboardActionListener()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener>(@__env.CallObjectMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._getOnKeyboardActionListener4633)) as android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._getOnKeyboardActionListener4633)) as android.inputmethodservice.KeyboardView.OnKeyboardActionListener;
}
internal static global::MonoJavaBridge.MethodId _setKeyboard4634;
public virtual void setKeyboard(android.inputmethodservice.Keyboard arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setKeyboard4634, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setKeyboard4634, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getKeyboard4635;
public virtual global::android.inputmethodservice.Keyboard getKeyboard()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._getKeyboard4635)) as android.inputmethodservice.Keyboard;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._getKeyboard4635)) as android.inputmethodservice.Keyboard;
}
internal static global::MonoJavaBridge.MethodId _setPreviewEnabled4636;
public virtual void setPreviewEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setPreviewEnabled4636, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setPreviewEnabled4636, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isPreviewEnabled4637;
public virtual bool isPreviewEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._isPreviewEnabled4637);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._isPreviewEnabled4637);
}
internal static global::MonoJavaBridge.MethodId _setVerticalCorrection4638;
public virtual void setVerticalCorrection(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setVerticalCorrection4638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setVerticalCorrection4638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPopupParent4639;
public virtual void setPopupParent(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setPopupParent4639, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setPopupParent4639, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPopupOffset4640;
public virtual void setPopupOffset(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setPopupOffset4640, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setPopupOffset4640, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setProximityCorrectionEnabled4641;
public virtual void setProximityCorrectionEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._setProximityCorrectionEnabled4641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._setProximityCorrectionEnabled4641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isProximityCorrectionEnabled4642;
public virtual bool isProximityCorrectionEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._isProximityCorrectionEnabled4642);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._isProximityCorrectionEnabled4642);
}
internal static global::MonoJavaBridge.MethodId _invalidateAllKeys4643;
public virtual void invalidateAllKeys()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._invalidateAllKeys4643);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._invalidateAllKeys4643);
}
internal static global::MonoJavaBridge.MethodId _invalidateKey4644;
public virtual void invalidateKey(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._invalidateKey4644, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._invalidateKey4644, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onLongPress4645;
protected virtual bool onLongPress(android.inputmethodservice.Keyboard.Key arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._onLongPress4645, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._onLongPress4645, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _handleBack4646;
public virtual bool handleBack()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView._handleBack4646);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._handleBack4646);
}
internal static global::MonoJavaBridge.MethodId _KeyboardView4647;
public KeyboardView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._KeyboardView4647, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _KeyboardView4648;
public KeyboardView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._KeyboardView4648, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.inputmethodservice.KeyboardView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/inputmethodservice/KeyboardView"));
global::android.inputmethodservice.KeyboardView._closing4619 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "closing", "()V");
global::android.inputmethodservice.KeyboardView._onClick4620 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onClick", "(Landroid/view/View;)V");
global::android.inputmethodservice.KeyboardView._onTouchEvent4621 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.inputmethodservice.KeyboardView._onDetachedFromWindow4622 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onDetachedFromWindow", "()V");
global::android.inputmethodservice.KeyboardView._onSizeChanged4623 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onSizeChanged", "(IIII)V");
global::android.inputmethodservice.KeyboardView._onDraw4624 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onDraw", "(Landroid/graphics/Canvas;)V");
global::android.inputmethodservice.KeyboardView._onMeasure4625 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onMeasure", "(II)V");
global::android.inputmethodservice.KeyboardView._setShifted4626 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setShifted", "(Z)Z");
global::android.inputmethodservice.KeyboardView._isShifted4627 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "isShifted", "()Z");
global::android.inputmethodservice.KeyboardView._swipeLeft4628 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "swipeLeft", "()V");
global::android.inputmethodservice.KeyboardView._swipeRight4629 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "swipeRight", "()V");
global::android.inputmethodservice.KeyboardView._swipeDown4630 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "swipeDown", "()V");
global::android.inputmethodservice.KeyboardView._swipeUp4631 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "swipeUp", "()V");
global::android.inputmethodservice.KeyboardView._setOnKeyboardActionListener4632 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setOnKeyboardActionListener", "(Landroid/inputmethodservice/KeyboardView$OnKeyboardActionListener;)V");
global::android.inputmethodservice.KeyboardView._getOnKeyboardActionListener4633 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "getOnKeyboardActionListener", "()Landroid/inputmethodservice/KeyboardView$OnKeyboardActionListener;");
global::android.inputmethodservice.KeyboardView._setKeyboard4634 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setKeyboard", "(Landroid/inputmethodservice/Keyboard;)V");
global::android.inputmethodservice.KeyboardView._getKeyboard4635 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "getKeyboard", "()Landroid/inputmethodservice/Keyboard;");
global::android.inputmethodservice.KeyboardView._setPreviewEnabled4636 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setPreviewEnabled", "(Z)V");
global::android.inputmethodservice.KeyboardView._isPreviewEnabled4637 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "isPreviewEnabled", "()Z");
global::android.inputmethodservice.KeyboardView._setVerticalCorrection4638 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setVerticalCorrection", "(I)V");
global::android.inputmethodservice.KeyboardView._setPopupParent4639 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setPopupParent", "(Landroid/view/View;)V");
global::android.inputmethodservice.KeyboardView._setPopupOffset4640 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setPopupOffset", "(II)V");
global::android.inputmethodservice.KeyboardView._setProximityCorrectionEnabled4641 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "setProximityCorrectionEnabled", "(Z)V");
global::android.inputmethodservice.KeyboardView._isProximityCorrectionEnabled4642 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "isProximityCorrectionEnabled", "()Z");
global::android.inputmethodservice.KeyboardView._invalidateAllKeys4643 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "invalidateAllKeys", "()V");
global::android.inputmethodservice.KeyboardView._invalidateKey4644 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "invalidateKey", "(I)V");
global::android.inputmethodservice.KeyboardView._onLongPress4645 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "onLongPress", "(Landroid/inputmethodservice/Keyboard$Key;)Z");
global::android.inputmethodservice.KeyboardView._handleBack4646 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "handleBack", "()Z");
global::android.inputmethodservice.KeyboardView._KeyboardView4647 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::android.inputmethodservice.KeyboardView._KeyboardView4648 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using ASP.NET_WebAPI.Areas.HelpPage.ModelDescriptions;
using ASP.NET_WebAPI.Areas.HelpPage.Models;
namespace ASP.NET_WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A day spa.
/// </summary>
public class DaySpa_Core : TypeCore, IHealthAndBeautyBusiness
{
public DaySpa_Core()
{
this._TypeId = 82;
this._Id = "DaySpa";
this._Schema_Org_Url = "http://schema.org/DaySpa";
string label = "";
GetLabel(out label, "DaySpa", typeof(DaySpa_Core));
this._Label = label;
this._Ancestors = new int[]{266,193,155,123};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{123};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The larger organization that this local business is a branch of, if any.
/// </summary>
private BranchOf_Core branchOf;
public BranchOf_Core BranchOf
{
get
{
return branchOf;
}
set
{
branchOf = value;
SetPropertyInstance(branchOf);
}
}
/// <summary>
/// A contact point for a person or organization.
/// </summary>
private ContactPoints_Core contactPoints;
public ContactPoints_Core ContactPoints
{
get
{
return contactPoints;
}
set
{
contactPoints = value;
SetPropertyInstance(contactPoints);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>).
/// </summary>
private CurrenciesAccepted_Core currenciesAccepted;
public CurrenciesAccepted_Core CurrenciesAccepted
{
get
{
return currenciesAccepted;
}
set
{
currenciesAccepted = value;
SetPropertyInstance(currenciesAccepted);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Email address.
/// </summary>
private Email_Core email;
public Email_Core Email
{
get
{
return email;
}
set
{
email = value;
SetPropertyInstance(email);
}
}
/// <summary>
/// People working for this organization.
/// </summary>
private Employees_Core employees;
public Employees_Core Employees
{
get
{
return employees;
}
set
{
employees = value;
SetPropertyInstance(employees);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// A person who founded this organization.
/// </summary>
private Founders_Core founders;
public Founders_Core Founders
{
get
{
return founders;
}
set
{
founders = value;
SetPropertyInstance(founders);
}
}
/// <summary>
/// The date that this organization was founded.
/// </summary>
private FoundingDate_Core foundingDate;
public FoundingDate_Core FoundingDate
{
get
{
return foundingDate;
}
set
{
foundingDate = value;
SetPropertyInstance(foundingDate);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// A member of this organization.
/// </summary>
private Members_Core members;
public Members_Core Members
{
get
{
return members;
}
set
{
members = value;
SetPropertyInstance(members);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Cash, credit card, etc.
/// </summary>
private PaymentAccepted_Core paymentAccepted;
public PaymentAccepted_Core PaymentAccepted
{
get
{
return paymentAccepted;
}
set
{
paymentAccepted = value;
SetPropertyInstance(paymentAccepted);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// The price range of the business, for example <code>$$$</code>.
/// </summary>
private PriceRange_Core priceRange;
public PriceRange_Core PriceRange
{
get
{
return priceRange;
}
set
{
priceRange = value;
SetPropertyInstance(priceRange);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Loader;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.Logging;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Infrastructure.ModelsBuilder;
using Umbraco.Cms.Infrastructure.ModelsBuilder.Building;
using Umbraco.Extensions;
using File = System.IO.File;
namespace Umbraco.Cms.Web.Common.ModelsBuilder
{
internal class InMemoryModelFactory : IAutoPublishedModelFactory, IRegisteredObject, IDisposable
{
private Infos _infos = new Infos { ModelInfos = null, ModelTypeMap = new Dictionary<string, Type>() };
private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();
private volatile bool _hasModels; // volatile 'cos reading outside lock
private bool _pendingRebuild;
private readonly IProfilingLogger _profilingLogger;
private readonly ILogger<InMemoryModelFactory> _logger;
private readonly FileSystemWatcher _watcher;
private int _ver;
private int _skipver;
private readonly int _debugLevel;
private RoslynCompiler _roslynCompiler;
private UmbracoAssemblyLoadContext _currentAssemblyLoadContext;
private readonly Lazy<UmbracoServices> _umbracoServices; // fixme: this is because of circular refs :(
private static readonly Regex s_assemblyVersionRegex = new Regex("AssemblyVersion\\(\"[0-9]+.[0-9]+.[0-9]+.[0-9]+\"\\)", RegexOptions.Compiled);
private static readonly string[] s_ourFiles = { "models.hash", "models.generated.cs", "all.generated.cs", "all.dll.path", "models.err", "Compiled" };
private readonly ModelsBuilderSettings _config;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IApplicationShutdownRegistry _hostingLifetime;
private readonly ModelsGenerationError _errors;
private readonly IPublishedValueFallback _publishedValueFallback;
private readonly ApplicationPartManager _applicationPartManager;
private static readonly Regex s_usingRegex = new Regex("^using(.*);", RegexOptions.Compiled | RegexOptions.Multiline);
private static readonly Regex s_aattrRegex = new Regex("^\\[assembly:(.*)\\]", RegexOptions.Compiled | RegexOptions.Multiline);
private readonly Lazy<string> _pureLiveDirectory;
private bool _disposedValue;
public InMemoryModelFactory(
Lazy<UmbracoServices> umbracoServices,
IProfilingLogger profilingLogger,
ILogger<InMemoryModelFactory> logger,
IOptions<ModelsBuilderSettings> config,
IHostingEnvironment hostingEnvironment,
IApplicationShutdownRegistry hostingLifetime,
IPublishedValueFallback publishedValueFallback,
ApplicationPartManager applicationPartManager)
{
_umbracoServices = umbracoServices;
_profilingLogger = profilingLogger;
_logger = logger;
_config = config.Value;
_hostingEnvironment = hostingEnvironment;
_hostingLifetime = hostingLifetime;
_publishedValueFallback = publishedValueFallback;
_applicationPartManager = applicationPartManager;
_errors = new ModelsGenerationError(config, _hostingEnvironment);
_ver = 1; // zero is for when we had no version
_skipver = -1; // nothing to skip
if (!hostingEnvironment.IsHosted)
{
return;
}
_pureLiveDirectory = new Lazy<string>(PureLiveDirectoryAbsolute);
if (!Directory.Exists(_pureLiveDirectory.Value))
{
Directory.CreateDirectory(_pureLiveDirectory.Value);
}
// BEWARE! if the watcher is not properly released then for some reason the
// BuildManager will start confusing types - using a 'registered object' here
// though we should probably plug into Umbraco's MainDom - which is internal
_hostingLifetime.RegisterObject(this);
_watcher = new FileSystemWatcher(_pureLiveDirectory.Value);
_watcher.Changed += WatcherOnChanged;
_watcher.EnableRaisingEvents = true;
// get it here, this need to be fast
_debugLevel = _config.DebugLevel;
AssemblyLoadContext.Default.Resolving += OnResolvingDefaultAssemblyLoadContext;
}
public event EventHandler ModelsChanged;
private UmbracoServices UmbracoServices => _umbracoServices.Value;
/// <summary>
/// Gets the currently loaded Live models assembly
/// </summary>
/// <remarks>
/// Can be null
/// </remarks>
public Assembly CurrentModelsAssembly { get; private set; }
/// <inheritdoc />
public object SyncRoot { get; } = new object();
/// <summary>
/// Gets the RoslynCompiler
/// </summary>
private RoslynCompiler RoslynCompiler
{
get
{
if (_roslynCompiler != null)
{
return _roslynCompiler;
}
_roslynCompiler = new RoslynCompiler();
return _roslynCompiler;
}
}
/// <inheritdoc />
public bool Enabled => _config.ModelsMode == ModelsMode.InMemoryAuto;
/// <summary>
/// Handle the event when a reference cannot be resolved from the default context and return our custom MB assembly reference if we have one
/// </summary>
/// <remarks>
/// This is required because the razor engine will only try to load things from the default context, it doesn't know anything
/// about our context so we need to proxy.
/// </remarks>
private Assembly OnResolvingDefaultAssemblyLoadContext(AssemblyLoadContext assemblyLoadContext, AssemblyName assemblyName)
=> assemblyName.Name == RoslynCompiler.GeneratedAssemblyName
? _currentAssemblyLoadContext?.LoadFromAssemblyName(assemblyName)
: null;
public IPublishedElement CreateModel(IPublishedElement element)
{
// get models, rebuilding them if needed
Dictionary<string, ModelInfo> infos = EnsureModels()?.ModelInfos;
if (infos == null)
{
return element;
}
// be case-insensitive
var contentTypeAlias = element.ContentType.Alias;
// lookup model constructor (else null)
infos.TryGetValue(contentTypeAlias, out var info);
// create model
return info == null ? element : info.Ctor(element, _publishedValueFallback);
}
// this runs only once the factory is ready
// NOT when building models
public Type MapModelType(Type type)
{
Infos infos = EnsureModels();
return ModelType.Map(type, infos.ModelTypeMap);
}
// this runs only once the factory is ready
// NOT when building models
public IList CreateModelList(string alias)
{
Infos infos = EnsureModels();
// fail fast
if (infos == null)
{
return new List<IPublishedElement>();
}
if (!infos.ModelInfos.TryGetValue(alias, out ModelInfo modelInfo))
{
return new List<IPublishedElement>();
}
Func<IList> ctor = modelInfo.ListCtor;
if (ctor != null)
{
return ctor();
}
Type listType = typeof(List<>).MakeGenericType(modelInfo.ModelType);
ctor = modelInfo.ListCtor = ReflectionUtilities.EmitConstructor<Func<IList>>(declaring: listType);
return ctor();
}
/// <inheritdoc />
public void Reset()
{
if (Enabled)
{
ResetModels();
}
}
// tells the factory that it should build a new generation of models
private void ResetModels()
{
_logger.LogDebug("Resetting models.");
try
{
_locker.EnterWriteLock();
_hasModels = false;
_pendingRebuild = true;
if (!Directory.Exists(_pureLiveDirectory.Value))
{
Directory.CreateDirectory(_pureLiveDirectory.Value);
}
// clear stuff
var modelsHashFile = Path.Combine(_pureLiveDirectory.Value, "models.hash");
var dllPathFile = Path.Combine(_pureLiveDirectory.Value, "all.dll.path");
if (File.Exists(dllPathFile))
{
File.Delete(dllPathFile);
}
if (File.Exists(modelsHashFile))
{
File.Delete(modelsHashFile);
}
}
finally
{
if (_locker.IsWriteLockHeld)
{
_locker.ExitWriteLock();
}
}
}
// ensure that the factory is running with the lastest generation of models
internal Infos EnsureModels()
{
if (_debugLevel > 0)
{
_logger.LogDebug("Ensuring models.");
}
// don't use an upgradeable lock here because only 1 thread at a time could enter it
try
{
_locker.EnterReadLock();
if (_hasModels)
{
return _infos;
}
}
finally
{
if (_locker.IsReadLockHeld)
{
_locker.ExitReadLock();
}
}
try
{
_locker.EnterUpgradeableReadLock();
if (_hasModels)
{
return _infos;
}
_locker.EnterWriteLock();
// we don't have models,
// either they haven't been loaded from the cache yet
// or they have been reseted and are pending a rebuild
using (_profilingLogger.DebugDuration<InMemoryModelFactory>("Get models.", "Got models."))
{
try
{
Assembly assembly = GetModelsAssembly(_pendingRebuild);
CurrentModelsAssembly = assembly;
// Raise the model changing event.
// NOTE: That on first load, if there is content, this will execute before the razor view engine
// has loaded which means it hasn't yet bound to this event so there's no need to worry about if
// it will be eagerly re-generated unecessarily on first render. BUT we should be aware that if we
// change this to use the event aggregator that will no longer be the case.
ModelsChanged?.Invoke(this, new EventArgs());
IEnumerable<Type> types = assembly.ExportedTypes.Where(x => x.Inherits<PublishedContentModel>() || x.Inherits<PublishedElementModel>());
_infos = RegisterModels(types);
_errors.Clear();
}
catch (Exception e)
{
try
{
_logger.LogError(e, "Failed to build models.");
_logger.LogWarning("Running without models."); // be explicit
_errors.Report("Failed to build InMemory models.", e);
}
finally
{
CurrentModelsAssembly = null;
_infos = new Infos { ModelInfos = null, ModelTypeMap = new Dictionary<string, Type>() };
}
}
// don't even try again
_hasModels = true;
}
return _infos;
}
finally
{
if (_locker.IsWriteLockHeld)
{
_locker.ExitWriteLock();
}
if (_locker.IsUpgradeableReadLockHeld)
{
_locker.ExitUpgradeableReadLock();
}
}
}
public string PureLiveDirectoryAbsolute() => _hostingEnvironment.MapPathContentRoot(Core.Constants.SystemDirectories.TempData+"/InMemoryAuto");
// This is NOT thread safe but it is only called from within a lock
private Assembly ReloadAssembly(string pathToAssembly)
{
// If there's a current AssemblyLoadContext, unload it before creating a new one.
if (!(_currentAssemblyLoadContext is null))
{
_currentAssemblyLoadContext.Unload();
// we need to remove the current part too
ApplicationPart currentPart = _applicationPartManager.ApplicationParts.FirstOrDefault(x => x.Name == RoslynCompiler.GeneratedAssemblyName);
if (currentPart != null)
{
_applicationPartManager.ApplicationParts.Remove(currentPart);
}
}
// We must create a new assembly load context
// as long as theres a reference to the assembly load context we can't delete the assembly it loaded
_currentAssemblyLoadContext = new UmbracoAssemblyLoadContext();
// NOTE: We cannot use in-memory assemblies due to the way the razor engine works which must use
// application parts in order to add references to it's own CSharpCompiler.
// These parts must have real paths since that is how the references are loaded. In that
// case we'll need to work on temp files so that the assembly isn't locked.
// Get a temp file path
// NOTE: We cannot use Path.GetTempFileName(), see this issue:
// https://github.com/dotnet/AspNetCore.Docs/issues/3589 which can cause issues, this is recommended instead
var tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
File.Copy(pathToAssembly, tempFile, true);
// Load it in
Assembly assembly = _currentAssemblyLoadContext.LoadFromAssemblyPath(tempFile);
// Add the assembly to the application parts - this is required because this is how
// the razor ReferenceManager resolves what to load, see
// https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Razor.RuntimeCompilation/src/RazorReferenceManager.cs#L53
var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly);
foreach (ApplicationPart applicationPart in partFactory.GetApplicationParts(assembly))
{
_applicationPartManager.ApplicationParts.Add(applicationPart);
}
return assembly;
}
// This is NOT thread safe but it is only called from within a lock
private Assembly GetModelsAssembly(bool forceRebuild)
{
if (!Directory.Exists(_pureLiveDirectory.Value))
{
Directory.CreateDirectory(_pureLiveDirectory.Value);
}
IList<TypeModel> typeModels = UmbracoServices.GetAllTypes();
var currentHash = TypeModelHasher.Hash(typeModels);
var modelsHashFile = Path.Combine(_pureLiveDirectory.Value, "models.hash");
var modelsSrcFile = Path.Combine(_pureLiveDirectory.Value, "models.generated.cs");
var projFile = Path.Combine(_pureLiveDirectory.Value, "all.generated.cs");
var dllPathFile = Path.Combine(_pureLiveDirectory.Value, "all.dll.path");
// caching the generated models speeds up booting
// currentHash hashes both the types & the user's partials
if (!forceRebuild)
{
_logger.LogDebug("Looking for cached models.");
if (File.Exists(modelsHashFile) && File.Exists(projFile))
{
var cachedHash = File.ReadAllText(modelsHashFile);
if (currentHash != cachedHash)
{
_logger.LogDebug("Found obsolete cached models.");
forceRebuild = true;
}
// else cachedHash matches currentHash, we can try to load an existing dll
}
else
{
_logger.LogDebug("Could not find cached models.");
forceRebuild = true;
}
}
Assembly assembly;
if (!forceRebuild)
{
// try to load the dll directly (avoid rebuilding)
//
// ensure that the .dll file does not have a corresponding .dll.delete file
// as that would mean the the .dll file is going to be deleted and should not
// be re-used - that should not happen in theory, but better be safe
if (File.Exists(dllPathFile))
{
var dllPath = File.ReadAllText(dllPathFile);
_logger.LogDebug($"Cached models dll at {dllPath}.");
if (File.Exists(dllPath) && !File.Exists(dllPath + ".delete"))
{
assembly = ReloadAssembly(dllPath);
ModelsBuilderAssemblyAttribute attr = assembly.GetCustomAttribute<ModelsBuilderAssemblyAttribute>();
if (attr != null && attr.IsInMemory && attr.SourceHash == currentHash)
{
// if we were to resume at that revision, then _ver would keep increasing
// and that is probably a bad idea - so, we'll always rebuild starting at
// ver 1, but we remember we want to skip that one - so we never end up
// with the "same but different" version of the assembly in memory
_skipver = assembly.GetName().Version.Revision;
_logger.LogDebug("Loading cached models (dll).");
return assembly;
}
_logger.LogDebug("Cached models dll cannot be loaded (invalid assembly).");
}
else if (!File.Exists(dllPath))
{
_logger.LogDebug("Cached models dll does not exist.");
}
else if (File.Exists(dllPath + ".delete"))
{
_logger.LogDebug("Cached models dll is marked for deletion.");
}
else
{
_logger.LogDebug("Cached models dll cannot be loaded (why?).");
}
}
// must reset the version in the file else it would keep growing
// loading cached modules only happens when the app restarts
var text = File.ReadAllText(projFile);
Match match = s_assemblyVersionRegex.Match(text);
if (match.Success)
{
text = text.Replace(match.Value, "AssemblyVersion(\"0.0.0." + _ver + "\")");
File.WriteAllText(projFile, text);
}
_ver++;
try
{
var assemblyPath = GetOutputAssemblyPath(currentHash);
RoslynCompiler.CompileToFile(projFile, assemblyPath);
assembly = ReloadAssembly(assemblyPath);
File.WriteAllText(dllPathFile, assembly.Location);
File.WriteAllText(modelsHashFile, currentHash);
TryDeleteUnusedAssemblies(dllPathFile);
}
catch
{
ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile);
throw;
}
_logger.LogDebug("Loading cached models (source).");
return assembly;
}
// need to rebuild
_logger.LogDebug("Rebuilding models.");
// generate code, save
var code = GenerateModelsCode(typeModels);
// add extra attributes,
// IsLive=true helps identifying Assemblies that contain live models
// AssemblyVersion is so that we have a different version for each rebuild
var ver = _ver == _skipver ? ++_ver : _ver;
_ver++;
string mbAssemblyDirective = $@"[assembly:ModelsBuilderAssembly(IsInMemory = true, SourceHash = ""{currentHash}"")]
[assembly:System.Reflection.AssemblyVersion(""0.0.0.{ver}"")]";
code = code.Replace("//ASSATTR", mbAssemblyDirective);
File.WriteAllText(modelsSrcFile, code);
// generate proj, save
var projFiles = new Dictionary<string, string>
{
{ "models.generated.cs", code }
};
var proj = GenerateModelsProj(projFiles);
File.WriteAllText(projFile, proj);
// compile and register
try
{
var assemblyPath = GetOutputAssemblyPath(currentHash);
RoslynCompiler.CompileToFile(projFile, assemblyPath);
assembly = ReloadAssembly(assemblyPath);
File.WriteAllText(dllPathFile, assemblyPath);
File.WriteAllText(modelsHashFile, currentHash);
TryDeleteUnusedAssemblies(dllPathFile);
}
catch
{
ClearOnFailingToCompile(dllPathFile, modelsHashFile, projFile);
throw;
}
_logger.LogDebug("Done rebuilding.");
return assembly;
}
private void TryDeleteUnusedAssemblies(string dllPathFile)
{
if (File.Exists(dllPathFile))
{
var dllPath = File.ReadAllText(dllPathFile);
DirectoryInfo dirInfo = new DirectoryInfo(dllPath).Parent;
IEnumerable<FileInfo> files = dirInfo.GetFiles().Where(f => f.FullName != dllPath);
foreach (FileInfo file in files)
{
try
{
File.Delete(file.FullName);
}
catch (UnauthorizedAccessException)
{
// The file is in use, we'll try again next time...
// This shouldn't happen anymore.
}
}
}
}
private string GetOutputAssemblyPath(string currentHash)
{
var dirInfo = new DirectoryInfo(Path.Combine(_pureLiveDirectory.Value, "Compiled"));
if (!dirInfo.Exists)
{
Directory.CreateDirectory(dirInfo.FullName);
}
return Path.Combine(dirInfo.FullName, $"generated.cs{currentHash}.dll");
}
private void ClearOnFailingToCompile(string dllPathFile, string modelsHashFile, string projFile)
{
_logger.LogDebug("Failed to compile.");
// the dll file reference still points to the previous dll, which is obsolete
// now and will be deleted by ASP.NET eventually, so better clear that reference.
// also touch the proj file to force views to recompile - don't delete as it's
// useful to have the source around for debugging.
try
{
if (File.Exists(dllPathFile))
{
File.Delete(dllPathFile);
}
if (File.Exists(modelsHashFile))
{
File.Delete(modelsHashFile);
}
if (File.Exists(projFile))
{
File.SetLastWriteTime(projFile, DateTime.Now);
}
}
catch { /* enough */ }
}
private static Infos RegisterModels(IEnumerable<Type> types)
{
Type[] ctorArgTypes = new[] { typeof(IPublishedElement), typeof(IPublishedValueFallback) };
var modelInfos = new Dictionary<string, ModelInfo>(StringComparer.InvariantCultureIgnoreCase);
var map = new Dictionary<string, Type>();
foreach (Type type in types)
{
ConstructorInfo constructor = null;
Type parameterType = null;
foreach (ConstructorInfo ctor in type.GetConstructors())
{
ParameterInfo[] parms = ctor.GetParameters();
if (parms.Length == 2 && typeof(IPublishedElement).IsAssignableFrom(parms[0].ParameterType) && typeof(IPublishedValueFallback).IsAssignableFrom(parms[1].ParameterType))
{
if (constructor != null)
{
throw new InvalidOperationException($"Type {type.FullName} has more than one public constructor with one argument of type, or implementing, IPropertySet.");
}
constructor = ctor;
parameterType = parms[0].ParameterType;
}
}
if (constructor == null)
{
throw new InvalidOperationException($"Type {type.FullName} is missing a public constructor with one argument of type, or implementing, IPropertySet.");
}
PublishedModelAttribute attribute = type.GetCustomAttribute<PublishedModelAttribute>(false);
var typeName = attribute == null ? type.Name : attribute.ContentTypeAlias;
if (modelInfos.TryGetValue(typeName, out var modelInfo))
{
throw new InvalidOperationException($"Both types {type.FullName} and {modelInfo.ModelType.FullName} want to be a model type for content type with alias \"{typeName}\".");
}
// TODO: use Core's ReflectionUtilities.EmitCtor !!
// Yes .. DynamicMethod is uber slow
// TODO: But perhaps https://docs.microsoft.com/en-us/dotnet/api/system.reflection.emit.constructorbuilder?view=netcore-3.1 is better still?
// See CtorInvokeBenchmarks
var meth = new DynamicMethod(string.Empty, typeof(IPublishedElement), ctorArgTypes, type.Module, true);
ILGenerator gen = meth.GetILGenerator();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldarg_1);
gen.Emit(OpCodes.Newobj, constructor);
gen.Emit(OpCodes.Ret);
var func = (Func<IPublishedElement, IPublishedValueFallback, IPublishedElement>)meth.CreateDelegate(typeof(Func<IPublishedElement, IPublishedValueFallback, IPublishedElement>));
modelInfos[typeName] = new ModelInfo { ParameterType = parameterType, Ctor = func, ModelType = type };
map[typeName] = type;
}
return new Infos { ModelInfos = modelInfos.Count > 0 ? modelInfos : null, ModelTypeMap = map };
}
private string GenerateModelsCode(IList<TypeModel> typeModels)
{
if (!Directory.Exists(_pureLiveDirectory.Value))
{
Directory.CreateDirectory(_pureLiveDirectory.Value);
}
foreach (var file in Directory.GetFiles(_pureLiveDirectory.Value, "*.generated.cs"))
{
File.Delete(file);
}
var builder = new TextBuilder(_config, typeModels);
var codeBuilder = new StringBuilder();
builder.Generate(codeBuilder, builder.GetModelsToGenerate());
var code = codeBuilder.ToString();
return code;
}
private static string GenerateModelsProj(IDictionary<string, string> files)
{
// ideally we would generate a CSPROJ file but then we'd need a BuildProvider for csproj
// trying to keep things simple for the time being, just write everything to one big file
// group all 'using' at the top of the file (else fails)
var usings = new List<string>();
foreach (string k in files.Keys.ToList())
{
files[k] = s_usingRegex.Replace(files[k], m =>
{
usings.Add(m.Groups[1].Value);
return string.Empty;
});
}
// group all '[assembly:...]' at the top of the file (else fails)
var aattrs = new List<string>();
foreach (string k in files.Keys.ToList())
{
files[k] = s_aattrRegex.Replace(files[k], m =>
{
aattrs.Add(m.Groups[1].Value);
return string.Empty;
});
}
var text = new StringBuilder();
foreach (var u in usings.Distinct())
{
text.Append("using ");
text.Append(u);
text.Append(";\r\n");
}
foreach (var a in aattrs)
{
text.Append("[assembly:");
text.Append(a);
text.Append("]\r\n");
}
text.Append("\r\n\r\n");
foreach (KeyValuePair<string, string> f in files)
{
text.Append("// FILE: ");
text.Append(f.Key);
text.Append("\r\n\r\n");
text.Append(f.Value);
text.Append("\r\n\r\n\r\n");
}
text.Append("// EOF\r\n");
return text.ToString();
}
private void WatcherOnChanged(object sender, FileSystemEventArgs args)
{
var changed = args.Name;
// don't reset when our files change because we are building!
//
// comment it out, and always ignore our files, because it seems that some
// race conditions can occur on slow Cloud filesystems and then we keep
// rebuilding
//if (_building && OurFiles.Contains(changed))
//{
// //_logger.LogInformation<InMemoryModelFactory>("Ignoring files self-changes.");
// return;
//}
// always ignore our own file changes
if (s_ourFiles.Contains(changed))
{
return;
}
_logger.LogInformation("Detected files changes.");
lock (SyncRoot) // don't reset while being locked
{
ResetModels();
}
}
public void Stop(bool immediate)
{
Dispose();
_hostingLifetime.UnregisterObject(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
_locker.Dispose();
}
_disposedValue = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
}
internal class Infos
{
public Dictionary<string, Type> ModelTypeMap { get; set; }
public Dictionary<string, ModelInfo> ModelInfos { get; set; }
}
internal class ModelInfo
{
public Type ParameterType { get; set; }
public Func<IPublishedElement, IPublishedValueFallback, IPublishedElement> Ctor { get; set; }
public Type ModelType { get; set; }
public Func<IList> ListCtor { get; set; }
}
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: api@oanda.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// A DailyFinancingTransaction represents the daily payment/collection of financing for an Account.
/// </summary>
[DataContract]
public partial class DailyFinancingTransaction : IEquatable<DailyFinancingTransaction>, IValidatableObject
{
/// <summary>
/// The Type of the Transaction. Always set to \"DAILY_FINANCING\" for a DailyFinancingTransaction.
/// </summary>
/// <value>The Type of the Transaction. Always set to \"DAILY_FINANCING\" for a DailyFinancingTransaction.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum CREATE for "CREATE"
/// </summary>
[EnumMember(Value = "CREATE")]
CREATE,
/// <summary>
/// Enum CLOSE for "CLOSE"
/// </summary>
[EnumMember(Value = "CLOSE")]
CLOSE,
/// <summary>
/// Enum REOPEN for "REOPEN"
/// </summary>
[EnumMember(Value = "REOPEN")]
REOPEN,
/// <summary>
/// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE"
/// </summary>
[EnumMember(Value = "CLIENT_CONFIGURE")]
CLIENTCONFIGURE,
/// <summary>
/// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT"
/// </summary>
[EnumMember(Value = "CLIENT_CONFIGURE_REJECT")]
CLIENTCONFIGUREREJECT,
/// <summary>
/// Enum TRANSFERFUNDS for "TRANSFER_FUNDS"
/// </summary>
[EnumMember(Value = "TRANSFER_FUNDS")]
TRANSFERFUNDS,
/// <summary>
/// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT"
/// </summary>
[EnumMember(Value = "TRANSFER_FUNDS_REJECT")]
TRANSFERFUNDSREJECT,
/// <summary>
/// Enum MARKETORDER for "MARKET_ORDER"
/// </summary>
[EnumMember(Value = "MARKET_ORDER")]
MARKETORDER,
/// <summary>
/// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "MARKET_ORDER_REJECT")]
MARKETORDERREJECT,
/// <summary>
/// Enum LIMITORDER for "LIMIT_ORDER"
/// </summary>
[EnumMember(Value = "LIMIT_ORDER")]
LIMITORDER,
/// <summary>
/// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "LIMIT_ORDER_REJECT")]
LIMITORDERREJECT,
/// <summary>
/// Enum STOPORDER for "STOP_ORDER"
/// </summary>
[EnumMember(Value = "STOP_ORDER")]
STOPORDER,
/// <summary>
/// Enum STOPORDERREJECT for "STOP_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "STOP_ORDER_REJECT")]
STOPORDERREJECT,
/// <summary>
/// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER"
/// </summary>
[EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")]
MARKETIFTOUCHEDORDER,
/// <summary>
/// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")]
MARKETIFTOUCHEDORDERREJECT,
/// <summary>
/// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER"
/// </summary>
[EnumMember(Value = "TAKE_PROFIT_ORDER")]
TAKEPROFITORDER,
/// <summary>
/// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")]
TAKEPROFITORDERREJECT,
/// <summary>
/// Enum STOPLOSSORDER for "STOP_LOSS_ORDER"
/// </summary>
[EnumMember(Value = "STOP_LOSS_ORDER")]
STOPLOSSORDER,
/// <summary>
/// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "STOP_LOSS_ORDER_REJECT")]
STOPLOSSORDERREJECT,
/// <summary>
/// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER"
/// </summary>
[EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")]
TRAILINGSTOPLOSSORDER,
/// <summary>
/// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT"
/// </summary>
[EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")]
TRAILINGSTOPLOSSORDERREJECT,
/// <summary>
/// Enum ORDERFILL for "ORDER_FILL"
/// </summary>
[EnumMember(Value = "ORDER_FILL")]
ORDERFILL,
/// <summary>
/// Enum ORDERCANCEL for "ORDER_CANCEL"
/// </summary>
[EnumMember(Value = "ORDER_CANCEL")]
ORDERCANCEL,
/// <summary>
/// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT"
/// </summary>
[EnumMember(Value = "ORDER_CANCEL_REJECT")]
ORDERCANCELREJECT,
/// <summary>
/// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY"
/// </summary>
[EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")]
ORDERCLIENTEXTENSIONSMODIFY,
/// <summary>
/// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT"
/// </summary>
[EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")]
ORDERCLIENTEXTENSIONSMODIFYREJECT,
/// <summary>
/// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY"
/// </summary>
[EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")]
TRADECLIENTEXTENSIONSMODIFY,
/// <summary>
/// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT"
/// </summary>
[EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")]
TRADECLIENTEXTENSIONSMODIFYREJECT,
/// <summary>
/// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER"
/// </summary>
[EnumMember(Value = "MARGIN_CALL_ENTER")]
MARGINCALLENTER,
/// <summary>
/// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND"
/// </summary>
[EnumMember(Value = "MARGIN_CALL_EXTEND")]
MARGINCALLEXTEND,
/// <summary>
/// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT"
/// </summary>
[EnumMember(Value = "MARGIN_CALL_EXIT")]
MARGINCALLEXIT,
/// <summary>
/// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE"
/// </summary>
[EnumMember(Value = "DELAYED_TRADE_CLOSURE")]
DELAYEDTRADECLOSURE,
/// <summary>
/// Enum DAILYFINANCING for "DAILY_FINANCING"
/// </summary>
[EnumMember(Value = "DAILY_FINANCING")]
DAILYFINANCING,
/// <summary>
/// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL"
/// </summary>
[EnumMember(Value = "RESET_RESETTABLE_PL")]
RESETRESETTABLEPL
}
/// <summary>
/// The account financing mode at the time of the daily financing.
/// </summary>
/// <value>The account financing mode at the time of the daily financing.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum AccountFinancingModeEnum
{
/// <summary>
/// Enum NOFINANCING for "NO_FINANCING"
/// </summary>
[EnumMember(Value = "NO_FINANCING")]
NOFINANCING,
/// <summary>
/// Enum SECONDBYSECOND for "SECOND_BY_SECOND"
/// </summary>
[EnumMember(Value = "SECOND_BY_SECOND")]
SECONDBYSECOND,
/// <summary>
/// Enum DAILY for "DAILY"
/// </summary>
[EnumMember(Value = "DAILY")]
DAILY
}
/// <summary>
/// The Type of the Transaction. Always set to \"DAILY_FINANCING\" for a DailyFinancingTransaction.
/// </summary>
/// <value>The Type of the Transaction. Always set to \"DAILY_FINANCING\" for a DailyFinancingTransaction.</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// The account financing mode at the time of the daily financing.
/// </summary>
/// <value>The account financing mode at the time of the daily financing.</value>
[DataMember(Name="accountFinancingMode", EmitDefaultValue=false)]
public AccountFinancingModeEnum? AccountFinancingMode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="DailyFinancingTransaction" /> class.
/// </summary>
/// <param name="Id">The Transaction's Identifier..</param>
/// <param name="Time">The date/time when the Transaction was created..</param>
/// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param>
/// <param name="AccountID">The ID of the Account the Transaction was created for..</param>
/// <param name="BatchID">The ID of the \"batch\" that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param>
/// <param name="RequestID">The Request ID of the request which generated the transaction..</param>
/// <param name="Type">The Type of the Transaction. Always set to \"DAILY_FINANCING\" for a DailyFinancingTransaction..</param>
/// <param name="Financing">The amount of financing paid/collected for the Account..</param>
/// <param name="AccountBalance">The Account's balance after daily financing..</param>
/// <param name="AccountFinancingMode">The account financing mode at the time of the daily financing..</param>
/// <param name="PositionFinancings">The financing paid/collected for each Position in the Account..</param>
public DailyFinancingTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?), string Financing = default(string), string AccountBalance = default(string), AccountFinancingModeEnum? AccountFinancingMode = default(AccountFinancingModeEnum?), List<PositionFinancing> PositionFinancings = default(List<PositionFinancing>))
{
this.Id = Id;
this.Time = Time;
this.UserID = UserID;
this.AccountID = AccountID;
this.BatchID = BatchID;
this.RequestID = RequestID;
this.Type = Type;
this.Financing = Financing;
this.AccountBalance = AccountBalance;
this.AccountFinancingMode = AccountFinancingMode;
this.PositionFinancings = PositionFinancings;
}
/// <summary>
/// The Transaction's Identifier.
/// </summary>
/// <value>The Transaction's Identifier.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// The date/time when the Transaction was created.
/// </summary>
/// <value>The date/time when the Transaction was created.</value>
[DataMember(Name="time", EmitDefaultValue=false)]
public string Time { get; set; }
/// <summary>
/// The ID of the user that initiated the creation of the Transaction.
/// </summary>
/// <value>The ID of the user that initiated the creation of the Transaction.</value>
[DataMember(Name="userID", EmitDefaultValue=false)]
public int? UserID { get; set; }
/// <summary>
/// The ID of the Account the Transaction was created for.
/// </summary>
/// <value>The ID of the Account the Transaction was created for.</value>
[DataMember(Name="accountID", EmitDefaultValue=false)]
public string AccountID { get; set; }
/// <summary>
/// The ID of the \"batch\" that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.
/// </summary>
/// <value>The ID of the \"batch\" that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value>
[DataMember(Name="batchID", EmitDefaultValue=false)]
public string BatchID { get; set; }
/// <summary>
/// The Request ID of the request which generated the transaction.
/// </summary>
/// <value>The Request ID of the request which generated the transaction.</value>
[DataMember(Name="requestID", EmitDefaultValue=false)]
public string RequestID { get; set; }
/// <summary>
/// The amount of financing paid/collected for the Account.
/// </summary>
/// <value>The amount of financing paid/collected for the Account.</value>
[DataMember(Name="financing", EmitDefaultValue=false)]
public string Financing { get; set; }
/// <summary>
/// The Account's balance after daily financing.
/// </summary>
/// <value>The Account's balance after daily financing.</value>
[DataMember(Name="accountBalance", EmitDefaultValue=false)]
public string AccountBalance { get; set; }
/// <summary>
/// The financing paid/collected for each Position in the Account.
/// </summary>
/// <value>The financing paid/collected for each Position in the Account.</value>
[DataMember(Name="positionFinancings", EmitDefaultValue=false)]
public List<PositionFinancing> PositionFinancings { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DailyFinancingTransaction {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Time: ").Append(Time).Append("\n");
sb.Append(" UserID: ").Append(UserID).Append("\n");
sb.Append(" AccountID: ").Append(AccountID).Append("\n");
sb.Append(" BatchID: ").Append(BatchID).Append("\n");
sb.Append(" RequestID: ").Append(RequestID).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Financing: ").Append(Financing).Append("\n");
sb.Append(" AccountBalance: ").Append(AccountBalance).Append("\n");
sb.Append(" AccountFinancingMode: ").Append(AccountFinancingMode).Append("\n");
sb.Append(" PositionFinancings: ").Append(PositionFinancings).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DailyFinancingTransaction);
}
/// <summary>
/// Returns true if DailyFinancingTransaction instances are equal
/// </summary>
/// <param name="other">Instance of DailyFinancingTransaction to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DailyFinancingTransaction other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.Time == other.Time ||
this.Time != null &&
this.Time.Equals(other.Time)
) &&
(
this.UserID == other.UserID ||
this.UserID != null &&
this.UserID.Equals(other.UserID)
) &&
(
this.AccountID == other.AccountID ||
this.AccountID != null &&
this.AccountID.Equals(other.AccountID)
) &&
(
this.BatchID == other.BatchID ||
this.BatchID != null &&
this.BatchID.Equals(other.BatchID)
) &&
(
this.RequestID == other.RequestID ||
this.RequestID != null &&
this.RequestID.Equals(other.RequestID)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.Financing == other.Financing ||
this.Financing != null &&
this.Financing.Equals(other.Financing)
) &&
(
this.AccountBalance == other.AccountBalance ||
this.AccountBalance != null &&
this.AccountBalance.Equals(other.AccountBalance)
) &&
(
this.AccountFinancingMode == other.AccountFinancingMode ||
this.AccountFinancingMode != null &&
this.AccountFinancingMode.Equals(other.AccountFinancingMode)
) &&
(
this.PositionFinancings == other.PositionFinancings ||
this.PositionFinancings != null &&
this.PositionFinancings.SequenceEqual(other.PositionFinancings)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.Time != null)
hash = hash * 59 + this.Time.GetHashCode();
if (this.UserID != null)
hash = hash * 59 + this.UserID.GetHashCode();
if (this.AccountID != null)
hash = hash * 59 + this.AccountID.GetHashCode();
if (this.BatchID != null)
hash = hash * 59 + this.BatchID.GetHashCode();
if (this.RequestID != null)
hash = hash * 59 + this.RequestID.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.Financing != null)
hash = hash * 59 + this.Financing.GetHashCode();
if (this.AccountBalance != null)
hash = hash * 59 + this.AccountBalance.GetHashCode();
if (this.AccountFinancingMode != null)
hash = hash * 59 + this.AccountFinancingMode.GetHashCode();
if (this.PositionFinancings != null)
hash = hash * 59 + this.PositionFinancings.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System;
using System.Diagnostics.Contracts;
namespace System.Text
{
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
// calls to the GetBytes method. The encoder maintains state between the
// conversions, allowing it to correctly encode character sequences that span
// adjacent blocks.
//
// Instances of specific implementations of the Encoder abstract base
// class are typically obtained through calls to the GetEncoder method
// of Encoding objects.
//
internal class EncoderNLS : Encoder
{
// Need a place for the last left over character, most of our encodings use this
internal char charLeftOver;
protected Encoding m_encoding;
protected bool m_mustFlush;
internal bool m_throwOnOverflow;
internal int m_charsUsed;
internal EncoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.EncoderFallback;
this.Reset();
}
// This one is used when deserializing (like UTF7Encoding.Encoder)
internal EncoderNLS()
{
this.m_encoding = null;
this.Reset();
}
public override void Reset()
{
this.charLeftOver = (char)0;
if (m_fallbackBuffer != null)
m_fallbackBuffer.Reset();
}
public override unsafe int GetByteCount(char[] chars, int index, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (index < 0 || count < 0)
throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
// Just call the pointer version
int result = -1;
fixed (char* pChars = &chars[0])
{
result = GetByteCount(pChars + index, count, flush);
}
return result;
}
public unsafe override int GetByteCount(char* chars, int count, bool flush)
{
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetByteCount(chars, count, this);
}
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex),
SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (chars.Length == 0)
chars = new char[1];
int byteCount = bytes.Length - byteIndex;
if (bytes.Length == 0)
bytes = new byte[1];
// Just call pointer version
fixed (char* pChars = &chars[0])
fixed (byte* pBytes = &bytes[0])
// Remember that charCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount,
pBytes + byteIndex, byteCount, flush);
}
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
this.m_throwOnOverflow = true;
return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
}
// This method is used when your output buffer might not be large enough for the entire result.
// Just call the pointer version. (This gets bytes)
public override unsafe void Convert(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
SR.ArgumentOutOfRange_IndexCountBuffer);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
if (chars.Length == 0)
chars = new char[1];
if (bytes.Length == 0)
bytes = new byte[1];
// Just call the pointer version (can't do this for non-msft encoders)
fixed (char* pChars = &chars[0])
{
fixed (byte* pBytes = &bytes[0])
{
Convert(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, flush,
out charsUsed, out bytesUsed, out completed);
}
}
}
// This is the version that uses pointers. We call the base encoding worker function
// after setting our appropriate internal variables. This is getting bytes
public override unsafe void Convert(char* chars, int charCount,
byte* bytes, int byteCount, bool flush,
out int charsUsed, out int bytesUsed, out bool completed)
{
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
this.m_mustFlush = flush;
this.m_throwOnOverflow = false;
this.m_charsUsed = 0;
// Do conversion
bytesUsed = this.m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
charsUsed = this.m_charsUsed;
// Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed
completed = (charsUsed == charCount) && (!flush || !this.HasState) &&
(m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
// Our data thingys are now full, we can return
}
public Encoding Encoding
{
get
{
return m_encoding;
}
}
public bool MustFlush
{
get
{
return m_mustFlush;
}
}
// Anything left in our encoder?
internal virtual bool HasState
{
get
{
return (this.charLeftOver != (char)0);
}
}
// Allow encoding to clear our must flush instead of throwing (in ThrowBytesOverflow)
internal void ClearMustFlush()
{
m_mustFlush = false;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.