context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Text;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Encryption.RC2.Tests
{
using RC2 = System.Security.Cryptography.RC2;
public static class RC2CipherTests
{
// These are the expected output of many decryptions. Changing these values requires re-generating test input.
private static readonly string s_multiBlockString = new ASCIIEncoding().GetBytes(
"This is a sentence that is longer than a block, it ensures that multi-block functions work.").ByteArrayToHex();
private static readonly string s_multiBlockString_8 = new ASCIIEncoding().GetBytes(
"This is a sentence that is longer than a block,but exactly an even block multiplier of 8").ByteArrayToHex();
private static readonly string s_multiBlockStringPaddedZeros =
"5468697320697320612073656E74656E63652074686174206973206C6F6E676572207468616E206120626C6F636B2C20" +
"697420656E73757265732074686174206D756C74692D626C6F636B2066756E6374696F6E7320776F726B2E0000000000";
private static readonly string s_randomKey_64 = "87FF0737F868378F";
private static readonly string s_randomIv_64 = "E531E789E3E1BB6F";
public static IEnumerable<object[]> RC2TestData
{
get
{
// RFC 2268 test
yield return new object[]
{
CipherMode.ECB,
PaddingMode.None,
"3000000000000000",
null,
"1000000000000001",
null,
"30649EDF9BE7D2C2"
};
// RFC 2268 test
yield return new object[]
{
CipherMode.ECB,
PaddingMode.None,
"FFFFFFFFFFFFFFFF",
null,
"FFFFFFFFFFFFFFFF",
null,
"278B27E42E2F0D49"
};
// RFC 2268 test
yield return new object[]
{
CipherMode.ECB,
PaddingMode.None,
"88bca90e90875a7f0f79c384627bafb2",
null,
"0000000000000000",
null,
"2269552ab0f85ca6"
};
yield return new object[]
{
CipherMode.ECB,
PaddingMode.None,
s_randomKey_64,
null,
s_multiBlockString_8,
null,
"F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A13BC850E32BB598F" +
"1AC96E96401EBBCDAEEF21D6C05B8DF2637B938CFDB8814B3CC47E30640BD0396B2AC6D7D9977499"
};
yield return new object[]
{
CipherMode.ECB,
PaddingMode.PKCS7,
s_randomKey_64,
null,
s_multiBlockString,
null,
"F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" +
"620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721AEB21E183555CE07"
};
yield return new object[]
{
CipherMode.ECB,
PaddingMode.Zeros,
s_randomKey_64,
null,
s_multiBlockString,
s_multiBlockStringPaddedZeros,
"F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" +
"620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721C669B2B62A6BF492"
};
yield return new object[]
{
CipherMode.CBC,
PaddingMode.None,
s_randomKey_64,
s_randomIv_64,
s_multiBlockString_8,
null,
"85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67F6056044F15B5C7ED" +
"4FAB086053D7DC458C206145AE9655F1590C590FBDE76365FA488CADBCDA67B325A35E7CCBC1B9A1"
};
yield return new object[]
{
CipherMode.CBC,
PaddingMode.PKCS7,
s_randomKey_64,
s_randomIv_64,
s_multiBlockString,
null,
"85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" +
"13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733"
};
yield return new object[]
{
CipherMode.CBC,
PaddingMode.Zeros,
s_randomKey_64,
s_randomIv_64,
s_multiBlockString,
s_multiBlockStringPaddedZeros,
"85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" +
"13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6A1BB012ED20DADA"
};
}
}
[Theory, MemberData(nameof(RC2TestData))]
public static void RC2RoundTrip(CipherMode cipherMode, PaddingMode paddingMode, string key, string iv, string textHex, string expectedDecrypted, string expectedEncrypted)
{
byte[] expectedDecryptedBytes = expectedDecrypted == null ? textHex.HexToByteArray() : expectedDecrypted.HexToByteArray();
byte[] expectedEncryptedBytes = expectedEncrypted.HexToByteArray();
byte[] keyBytes = key.HexToByteArray();
using (RC2 alg = RC2Factory.Create())
{
alg.Key = keyBytes;
alg.Padding = paddingMode;
alg.Mode = cipherMode;
if (iv != null)
alg.IV = iv.HexToByteArray();
byte[] cipher = alg.Encrypt(textHex.HexToByteArray());
Assert.Equal<byte>(expectedEncryptedBytes, cipher);
byte[] decrypted = alg.Decrypt(cipher);
Assert.Equal<byte>(expectedDecryptedBytes, decrypted);
}
}
[Fact]
public static void RC2ReuseEncryptorDecryptor()
{
using (RC2 alg = RC2Factory.Create())
{
alg.Key = s_randomKey_64.HexToByteArray();
alg.IV = s_randomIv_64.HexToByteArray();
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
using (ICryptoTransform encryptor = alg.CreateEncryptor())
using (ICryptoTransform decryptor = alg.CreateDecryptor())
{
for (int i = 0; i < 2; i++)
{
byte[] plainText1 = s_multiBlockString.HexToByteArray();
byte[] cipher1 = encryptor.Transform(plainText1);
byte[] expectedCipher1 = (
"85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" +
"13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733").HexToByteArray();
Assert.Equal<byte>(expectedCipher1, cipher1);
byte[] decrypted1 = decryptor.Transform(cipher1);
byte[] expectedDecrypted1 = s_multiBlockString.HexToByteArray();
Assert.Equal<byte>(expectedDecrypted1, decrypted1);
byte[] plainText2 = s_multiBlockString_8.HexToByteArray();
byte[] cipher2 = encryptor.Transform(plainText2);
byte[] expectedCipher2 = (
"85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67F6056044F15B5C7ED" +
"4FAB086053D7DC458C206145AE9655F1590C590FBDE76365FA488CADBCDA67B325A35E7CCBC1B9A15E5EBE2879C7AEC2").HexToByteArray();
Assert.Equal<byte>(expectedCipher2, cipher2);
byte[] decrypted2 = decryptor.Transform(cipher2);
byte[] expectedDecrypted2 = s_multiBlockString_8.HexToByteArray();
Assert.Equal<byte>(expectedDecrypted2, decrypted2);
}
}
}
}
[Fact]
public static void RC2ExplicitEncryptorDecryptor_WithIV()
{
using (RC2 alg = RC2Factory.Create())
{
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), s_randomIv_64.HexToByteArray()))
{
byte[] plainText1 = s_multiBlockString.HexToByteArray();
byte[] cipher1 = encryptor.Transform(plainText1);
byte[] expectedCipher1 = (
"85B5D998F35ECD98DB886798170F64BA2DBA4FE902791CDE900EEB0B35728FEE35FB6CADC41DF67FBB691B45D92B876A" +
"13FD18229E5ACB797D21D7B257520910360E00FEECDE3433FDC6F15233AE6B5CAC01289AC8B57A9A6B5DA734C2E7E733").HexToByteArray();
Assert.Equal<byte>(expectedCipher1, cipher1);
}
}
}
[Fact]
public static void RC2ExplicitEncryptorDecryptor_NoIV()
{
using (RC2 alg = RC2Factory.Create())
{
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.ECB;
using (ICryptoTransform encryptor = alg.CreateEncryptor(s_randomKey_64.HexToByteArray(), null))
{
byte[] plainText1 = s_multiBlockString.HexToByteArray();
byte[] cipher1 = encryptor.Transform(plainText1);
byte[] expectedCipher1 = (
"F6DF2E83811D6CB0C8A5830069D16F6A51C985D7003852539051FABC3C6EA7CF46BD3DBD5527003A789B76CBE4D40A73" +
"620F04ED9F0AA1AEC7FEC90E7934F69E0568F6DF1F38B2198821D0A771D68A3F8220C8822E387721AEB21E183555CE07").HexToByteArray();
Assert.Equal<byte>(expectedCipher1, cipher1);
}
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void EncryptWithLargeOutputBuffer(bool blockAlignedOutput)
{
using (RC2 alg = RC2Factory.Create())
using (ICryptoTransform xform = alg.CreateEncryptor())
{
// 8 blocks, plus maybe three bytes
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] output = new byte[alg.BlockSize + outputPadding];
// 2 blocks of 0x00
byte[] input = new byte[alg.BlockSize / 4];
int outputOffset = 0;
outputOffset += xform.TransformBlock(input, 0, input.Length, output, outputOffset);
byte[] overflow = xform.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Buffer.BlockCopy(overflow, 0, output, outputOffset, overflow.Length);
outputOffset += overflow.Length;
Assert.Equal(3 * (alg.BlockSize / 8), outputOffset);
string outputAsHex = output.ByteArrayToHex();
Assert.NotEqual(new string('0', outputOffset * 2), outputAsHex.Substring(0, outputOffset * 2));
Assert.Equal(new string('0', (output.Length - outputOffset) * 2), outputAsHex.Substring(outputOffset * 2));
}
}
[Theory]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public static void TransformWithTooShortOutputBuffer(bool encrypt, bool blockAlignedOutput)
{
using (RC2 alg = RC2Factory.Create())
using (ICryptoTransform xform = encrypt ? alg.CreateEncryptor() : alg.CreateDecryptor())
{
// 1 block, plus maybe three bytes
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] output = new byte[alg.BlockSize / 8 + outputPadding];
// 3 blocks of 0x00
byte[] input = new byte[3 * (alg.BlockSize / 8)];
Assert.Throws<ArgumentOutOfRangeException>(
() => xform.TransformBlock(input, 0, input.Length, output, 0));
Assert.Equal(new byte[output.Length], output);
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void MultipleBlockDecryptTransform(bool blockAlignedOutput)
{
const string ExpectedOutput = "This is a test";
int outputPadding = blockAlignedOutput ? 0 : 3;
byte[] key = "0123456789ABCDEF".HexToByteArray();
byte[] iv = "0123456789ABCDEF".HexToByteArray();
byte[] outputBytes = new byte[iv.Length * 2 + outputPadding];
byte[] input = "DB5400368C7E67FF5F9E1FA99641EB69".HexToByteArray();
int outputOffset = 0;
using (RC2 alg = RC2Factory.Create())
using (ICryptoTransform xform = alg.CreateDecryptor(key, iv))
{
Assert.Equal(2 * alg.BlockSize, (outputBytes.Length - outputPadding) * 8);
outputOffset += xform.TransformBlock(input, 0, input.Length, outputBytes, outputOffset);
byte[] overflow = xform.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
Buffer.BlockCopy(overflow, 0, outputBytes, outputOffset, overflow.Length);
outputOffset += overflow.Length;
}
string decrypted = Encoding.ASCII.GetString(outputBytes, 0, outputOffset);
Assert.Equal(ExpectedOutput, decrypted);
}
}
}
| |
/*
* ScrollBar.cs - Implementation of the "System.Windows.Forms.ScrollBar" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
* Copyright (C) 2003 Free Software Foundation, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Windows.Forms
{
using System.Drawing;
using System.Windows.Forms.Themes;
public abstract class ScrollBar : Control
{
// Fields
private int minimum = 0;
private int maximum = 100;
private int value = 0;
private int largeChange = 10;
private int smallChange = 1;
private Rectangle bar = Rectangle.Empty;
private Rectangle track = Rectangle.Empty;
private Rectangle increment = Rectangle.Empty;
private Rectangle decrement = Rectangle.Empty;
private bool incDown = false;
private bool decDown = false;
private bool trackDown = false;
private int barDown = -1;
private int minBarDown;
private int maxBarDown;
private bool keyDown = false;
private Timer timer;
private int mouseX;
private int mouseY;
private Timer keyTimer;
internal bool vertical;
private const int repeatDelay = 50;
private const int startDelay = 300;
private Timer idleTimer;
private MouseEventArgs idleMouse;
private const int minThumbSize = 8;
// Constructors
public ScrollBar() : base()
{
base.TabStop = false;
timer = new Timer();
keyTimer = new Timer(); // keep key and mouse events from stepping on each others toes
idleTimer = new Timer();
idleTimer.Tick += new EventHandler(idleTimer_Tick);
idleTimer.Interval = 1;
BackColor = SystemColors.ScrollBar;
}
// Properties
public override Color BackColor
{
get { return base.BackColor; }
set
{
if (value == base.backColor) { return; }
base.BackColor = value;
Invalidate();
}
}
public override Image BackgroundImage
{
get { return base.BackgroundImage; }
set
{
if (value == base.BackgroundImage) { return; }
base.BackgroundImage = value;
Invalidate();
}
}
protected override CreateParams CreateParams
{
get { return base.CreateParams; }
}
// Get or set whether the Decrement button is down, start the timer
private bool DecrementDown
{
get { return decDown; }
set
{
if (value == decDown) { return; }
decDown = value;
Invalidate(decrement);
if (value)
{
timer.Tick += new EventHandler(Decrement);
timer.Interval = startDelay;
timer.Start();
}
else
{
timer.Stop();
timer.Tick -= new EventHandler(Decrement);
}
}
}
protected override ImeMode DefaultImeMode
{
get { return ImeMode.Disable; }
}
public override Font Font
{
get { return base.Font; }
set { base.Font = value; }
}
public override Color ForeColor
{
get { return base.ForeColor; }
set
{
if (value == base.foreColor) { return; }
base.ForeColor = value;
Invalidate();
}
}
public new ImeMode ImeMode
{
get { return base.ImeMode; }
set { base.ImeMode = value; }
}
// Get or set whether the Increment button is down, start the timer
private bool IncrementDown
{
get { return incDown; }
set
{
if (value == incDown) { return; }
incDown = value;
Invalidate(increment);
if (value)
{
timer.Tick += new EventHandler(Increment);
timer.Interval = startDelay;
timer.Start();
}
else
{
timer.Stop();
timer.Tick -= new EventHandler(Increment);
}
}
}
// Value for large scroll jumps
public int LargeChange
{
get { return largeChange; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(/* TODO */);
}
if(value == largeChange)
return;
largeChange = value;
if (largeChange > maximum - minimum)
largeChange = (maximum - minimum + 1);// /2
LayoutScrollBar();
Invalidate();
}
}
// Maximum value of scroll
public int Maximum
{
get { return maximum; }
set
{
if (value < minimum)
{
throw new ArgumentOutOfRangeException(/* TODO */);
}
if (value == maximum) { return; }
maximum = value;
if (value > maximum)
Value = maximum;
LayoutScrollBar();
Invalidate();
}
}
// Minimum value of scroll
public int Minimum
{
get { return minimum; }
set
{
if (value > maximum)
{
throw new ArgumentOutOfRangeException(/* TODO */);
}
if (value == minimum) { return; }
minimum = value;
if (value < minimum)
Value = minimum;
LayoutScrollBar();
Invalidate();
}
}
public int SmallChange
{
get { return smallChange; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(/* TODO */);
}
smallChange = value;
}
}
public override string Text
{
get { return base.Text; }
set { base.Text = value; }
}
public int Value
{
get { return value; }
set
{
if (value > maximum || value < minimum)
{
throw new ArgumentOutOfRangeException(/* TODO */);
}
if (value == this.value) { return; }
Rectangle oldBounds = bar;
this.value = value;
LayoutScrollBar();
RedrawTrackBar(oldBounds);
OnValueChanged(new EventArgs());
}
}
// Called when decrement button is pushed and called from timer
private void Decrement(Object sender, EventArgs e)
{
timer.Interval = repeatDelay;
int newValue = value - smallChange;
if (newValue < minimum)
newValue = minimum;
Rectangle oldBounds = bar;
GenerateManualScrollEvents( newValue, ScrollEventType.SmallDecrement);
RedrawTrackBar(oldBounds);
}
// Called when the trackbar is clicked to decrement big and called from the timer
private void DecrementBig(Object sender, EventArgs e)
{
timer.Interval = repeatDelay;
int newValue = value - largeChange;
if (newValue < minimum)
newValue = minimum;
if (trackDown)
{
if (vertical)
{
if (mouseY > bar.Y)
{
TrackPressed(false,false);
return;
}
}
else
{
if (mouseX > bar.X)
{
TrackPressed(false,false);
return;
}
}
}
Rectangle oldBounds = bar;
GenerateManualScrollEvents(newValue, ScrollEventType.LargeDecrement);
RedrawTrackBar(oldBounds);
}
// Draw if visible and created
private void Draw(Graphics g, Rectangle drawBounds)
{
if (!Visible || !IsHandleCreated) { return; }
ThemeManager.MainPainter.DrawScrollBar(g,
ClientRectangle,
drawBounds,
ForeColor,BackColor,
vertical,Enabled,
bar, track,
decrement,decDown,
increment,incDown);
}
// Called when the increment button is pressed and called from the timer
private void Increment(Object sender, EventArgs e)
{
timer.Interval = repeatDelay;
int v = value + smallChange;
int v1 = maximum - largeChange + 1;
if (v1 < minimum)
v1 = minimum;
if (v > v1)
v = v1;
Rectangle oldBounds = bar;
GenerateManualScrollEvents(v, ScrollEventType.SmallIncrement);
RedrawTrackBar(oldBounds);
}
// Called when the trackbar is clicked to increment big and called from the timer
private void IncrementBig(Object sender, EventArgs e)
{
timer.Interval = repeatDelay;
int newValue = value + largeChange;
int maxValue = maximum - largeChange + 1;
if (maxValue < minimum)
maxValue = minimum;
if (newValue > maxValue)
newValue = maxValue;
if (trackDown)
{
if (vertical)
{
if (mouseY - bar.Height < bar.Y)
{
TrackPressed(false,false);
return;
}
}
else
{
if (mouseX - bar.Width < bar.X)
{
TrackPressed(false,false);
return;
}
}
}
Rectangle oldBounds = bar;
GenerateManualScrollEvents(newValue, ScrollEventType.LargeIncrement);
RedrawTrackBar(oldBounds);
}
// Sets up the layout rectangles for a HScrollBar's elements
private void LayoutElementsH(Size s)
{
LayoutElementsV(new Size(s.Height, s.Width));
decrement = SwapRectValues(decrement);
increment = SwapRectValues(increment);
track = SwapRectValues(track);
bar = SwapRectValues(bar);
if (RightToLeft == RightToLeft.Yes)
{
int offset = bar.X - track.X;
int guiMax = track.Width - bar.Width*2/3;
bar.X = guiMax - offset;
}
}
// Sets up the layout rectangles for a VScrollBar's elements
// Windows XP decrement and increment buttons width is just 2/3 of the initially used
// thus we fix this with a 2/3 coefficient and other experimentally found coefficients
// -- the only reason of this hack is that it makes our bar look good
private void LayoutElementsV(Size s)
{
int trackHeight, thumbHeight, thumbPos, zeroMax, zeroVal;
double percentage;
// Track
trackHeight = s.Height - (s.Width * 4/3);
if (trackHeight < 0)
trackHeight = 0;
// Decrement and increment buttons
// Is there enough room to fit both buttons at their
// preferred size?
if(s.Height >= (s.Width * 5/3) + 2) // 5/3 is just an experimental coefficient, no logical reason
{
track = new Rectangle(0, s.Width * 2/3, s.Width, s.Height - (s.Width * 4/3));
decrement = new Rectangle(0, 0, s.Width, s.Width * 2/3);
increment = new Rectangle(0, s.Width * 2/3 + trackHeight, s.Width, (s.Width) * 2/3);
}
else
{
// No. Split what's left.
track = new Rectangle(0, s.Height / 3 + 1, s.Width, s.Height / 3 - 1);
decrement = new Rectangle(0, 0, s.Width, s.Height / 3 );
increment = new Rectangle(0, s.Height * 2/3, s.Width, s.Height / 3);
}
// Thumb.
zeroMax = maximum - minimum - largeChange + 1;
if (zeroMax == 0)
{
bar = Rectangle.Empty;
return;
}
zeroVal = value - minimum;
percentage = (double) (largeChange) / (maximum - minimum + 1);
thumbHeight = (int) (percentage * trackHeight);
if (thumbHeight > trackHeight)
thumbHeight = trackHeight;
if (thumbHeight < minThumbSize)
thumbHeight = minThumbSize - 2;
percentage = (double) zeroVal / zeroMax;
thumbPos = (int)(percentage * (trackHeight - thumbHeight - 3));
if (thumbPos > (trackHeight - thumbHeight - 2))
{ thumbPos = (trackHeight - thumbHeight - 2);
}
// Out of range
if (thumbPos<=0)
thumbPos = -1;
// Out of range. 3/4 is just an experimental coefficient that makes our bar look good
if(s.Height >= s.Width * 5/3 + 2) // 5/3 is just an experimental coefficient, no logical reason
bar = new Rectangle(0, s.Width * 3/4 + thumbPos, s.Width, thumbHeight + 1);
else bar = new Rectangle(0, 0, 0, 0);
}
protected override void OnEnabledChanged(EventArgs e)
{
Invalidate();
base.OnEnabledChanged(e);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (keyDown) { return; }
switch (e.KeyCode)
{
case Keys.PageUp:
{
DecrementBig(null,null);
ScrollKeyPressed(true,-2);
}
break;
case Keys.PageDown:
{
IncrementBig(null,null);
ScrollKeyPressed(true,2);
}
break;
case Keys.Home:
{
Value = 0;
}
break;
case Keys.End:
{
Value = maximum - largeChange + 1;
}
break;
case Keys.Up:
case Keys.Left:
{
Decrement(null,null);
ScrollKeyPressed(true,-1);
}
break;
case Keys.Down:
case Keys.Right:
{
Increment(null,null);
ScrollKeyPressed(true,1);
}
break;
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (!keyDown) { return; }
barDown = -1;
switch (e.KeyCode)
{
case Keys.PageUp:
case Keys.Home:
{
ScrollKeyPressed(false,2);
}
break;
case Keys.PageDown:
case Keys.End:
{
ScrollKeyPressed(false,-2);
}
break;
case Keys.Up:
case Keys.Left:
{
ScrollKeyPressed(false,1);
}
break;
case Keys.Down:
case Keys.Right:
{
ScrollKeyPressed(false,-1);
}
break;
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
Capture = true;
int x = e.X;
int y = e.Y;
mouseX = x;
mouseY = y;
if (increment.Contains(x,y))
{
Increment(null,null);
IncrementDown = true;
}
else if (decrement.Contains(x,y))
{
Decrement(null,null);
DecrementDown = true;
}
else if (bar.Contains(x,y))
{
// Set the position of the mouse as it starts dragging the bar
// Calculate the min and max allowable positions
// This is MS behavior
if (vertical)
{
barDown = y;
minBarDown = y - bar.Y + track.Y;
maxBarDown = track.Bottom - (bar.Bottom - y);
}
else
{
barDown = x;
minBarDown = x - bar.X + track.X;
maxBarDown = track.Right - (bar.Right - x);
}
ScrollEventArgs se = new ScrollEventArgs(ScrollEventType.ThumbTrack, value);
OnScroll(se);
if (value != se.NewValue)
Value = se.NewValue;
}
else if (track.Contains(x,y))
{
if (vertical)
{
if (y >= bar.Bottom)
{
IncrementBig(null,null);
TrackPressed(true,true);
}
else // y <= bar.Top
{
DecrementBig(null,null);
TrackPressed(true,false);
}
}
else
{
bool plus = (x >= bar.Right);
plus ^= (RightToLeft == RightToLeft.Yes);
if (plus)
{
IncrementBig(null,null);
TrackPressed(true,true);
}
else
{
DecrementBig(null,null);
TrackPressed(true,false);
}
}
}
base.OnMouseDown(e);
}
protected override void OnMouseLeave(EventArgs e)
{
if (incDown)
{
IncrementDown = false;
Invalidate(increment);
}
else if (decDown)
{
DecrementDown = false;
Invalidate(decrement);
}
else if (trackDown)
{
TrackPressed(false,false);
}
base.OnMouseLeave(e);
}
protected override void OnMouseEnter(EventArgs e)
{
base.OnMouseEnter (e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
idleMouse = e;
// Do the actual event when the events have caught up.
idleTimer.Start();
}
private void OnMouseMoveActual(MouseEventArgs e)
{
base.OnMouseMove(e);
mouseX = e.X;
mouseY = e.Y;
if (incDown)
{
IncrementDown = increment.Contains(e.X, e.Y);
}
else if (decDown)
{
DecrementDown = decrement.Contains(e.X, e.Y);
}
else if (barDown != -1)
{
Rectangle oldBounds = bar;
if (vertical)
{
int guiMax = track.Y + track.Height - bar.Height;
int newPos = bar.Y + e.Y - barDown;
if (newPos < track.Y)
{
newPos = track.Y;
barDown = minBarDown;
}
else if (newPos > guiMax)
{
newPos = guiMax;
barDown = maxBarDown;
}
else
barDown = e.Y;
if (bar.Y == newPos)
return;
bar.Y = newPos;
}
else
{
int guiMax = track.X + track.Width - bar.Width;
int newPos = bar.X + e.X - barDown;
if (newPos < track.X)
{
newPos = track.X;
barDown = minBarDown;
}
else if (newPos > guiMax)
{
newPos = guiMax;
barDown = maxBarDown;
}
else
barDown = e.X;
if (bar.X == newPos)
return;
bar.X = newPos;
}
// Only generate the events if the bar has moved signficantly enough to change value
int newValue = ValueFromPosition;
if (newValue != value)
{
// Generate the events
ScrollEventArgs se = new ScrollEventArgs(ScrollEventType.ThumbTrack, newValue);
OnScroll(se);
value = se.NewValue;
// Did the event alter the value?
if (newValue != se.NewValue)
LayoutScrollBar();
OnValueChanged(new EventArgs());
}
RedrawTrackBar( oldBounds);
}
}
// When the trackbar moves, to prevent flickering, we only redraw what we have to
private void RedrawTrackBar( Rectangle oldBounds)
{
Region region = new Region(oldBounds);
region.Union(bar);
Invalidate(region);
}
protected override void OnMouseUp(MouseEventArgs e)
{
Capture = false;
mouseX = e.X;
mouseY = e.Y;
ScrollEventArgs se;
if (incDown)
{
IncrementDown = false;
}
else if (decDown)
{
DecrementDown = false;
}
else if (trackDown)
{
TrackPressed(false,false);
}
else if (barDown != -1)
{
barDown = -1;
se = new ScrollEventArgs(ScrollEventType.ThumbPosition, value);
OnScroll(se);
Value = se.NewValue;
}
se = new ScrollEventArgs(ScrollEventType.EndScroll, value);
OnScroll(se);
Value = se.NewValue;
base.OnMouseUp(e);
}
protected override void OnPaint(PaintEventArgs e)
{
Draw(e.Graphics, e.ClipRectangle);
base.OnPaint(e);
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
bool modified = (x != Left || y != Top || width != Width || height != Height);
base.SetBoundsCore (x, y, width, height, specified);
if (modified && IsHandleCreated)
{
LayoutScrollBar();
Invalidate();
}
}
protected override void OnCreateControl()
{
base.OnCreateControl ();
LayoutScrollBar();
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged (e);
if (IsHandleCreated)
LayoutScrollBar();
}
// Generate the events when the scrollbar is incremented or decremented
private void GenerateManualScrollEvents(int newValue, ScrollEventType type)
{
ScrollEventArgs se = new ScrollEventArgs(type, newValue);
OnScroll(se);
// This should be checked. If the value is set back to the previous value, I assume
// this prevents an OnValueChanged event.
if (se.NewValue != value)
{
value = se.NewValue;
LayoutScrollBar();
OnValueChanged(new EventArgs());
}
}
protected virtual void OnScroll(ScrollEventArgs e)
{
ScrollEventHandler handler;
handler = (ScrollEventHandler)(GetHandler(EventId.Scroll));
if (handler != null)
{
handler(this,e);
}
}
protected virtual void OnValueChanged(EventArgs e)
{
EventHandler handler;
handler = (EventHandler)(GetHandler(EventId.ValueChanged));
if (handler != null)
{
handler(this,e);
}
}
private void ScrollKeyPressed(bool pressed, int amount)
{
if (pressed == keyDown) { return; }
keyDown = pressed;
if (pressed)
{
switch (amount)
{
case 2:
{
timer.Tick += new EventHandler(IncrementBig);
}
break;
case -2:
{
timer.Tick += new EventHandler(DecrementBig);
}
break;
case 1:
{
timer.Tick += new EventHandler(Increment);
}
break;
case -1:
{
timer.Tick += new EventHandler(Decrement);
}
break;
}
timer.Interval = startDelay;
timer.Start();
}
else
{
timer.Stop();
timer.Tick -= new EventHandler(IncrementBig);
timer.Tick -= new EventHandler(DecrementBig);
timer.Tick -= new EventHandler(Increment);
timer.Tick -= new EventHandler(Decrement);
}
}
// Set the position based on "value" & layout the elements
private void LayoutScrollBar()
{
if(vertical)
LayoutElementsV(ClientSize);
else
LayoutElementsH(ClientSize);
}
// Calculate "value" from the bar position
private int ValueFromPosition
{
get
{
int v;
if(vertical)
{
int position = bar.Y - track.Y;
double percentage = (double) position / (track.Height - bar.Height);
v = (int)(percentage * (maximum - minimum + 1 - largeChange));
}
else
{
int position = bar.X - track.X;
double percentage = (double) position / (track.Width - bar.Width);
v = (int)(percentage * (maximum - minimum + 1 - largeChange));
if(RightToLeft == RightToLeft.Yes)
{
int guiMax = (maximum - largeChange - minimum);
v = guiMax - v;
}
}
v += minimum;
if (v < minimum)
v = minimum;
if (v > maximum)
v = maximum;
return v;
}
}
private static Rectangle SwapRectValues(Rectangle rect)
{
return new Rectangle(rect.Y,rect.X,rect.Height,rect.Width);
}
public override string ToString()
{
return base.ToString() + ", Minimum: " + minimum + ", Maximum: " +
maximum + ", Value: " + value;
}
private void TrackPressed(bool pressed, bool plus)
{
if (pressed == trackDown) { return; }
trackDown = pressed;
if (pressed)
{
if (plus)
{
timer.Tick += new EventHandler(IncrementBig);
}
else
{
timer.Tick += new EventHandler(DecrementBig);
}
timer.Interval = startDelay;
timer.Start();
}
else
{
timer.Stop();
timer.Tick -= new EventHandler(IncrementBig);
timer.Tick -= new EventHandler(DecrementBig);
}
}
#if !CONFIG_COMPACT_FORMS
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
}
#endif // !CONFIG_COMPACT_FORMS
public event ScrollEventHandler Scroll
{
add { AddHandler(EventId.Scroll,value); }
remove { RemoveHandler(EventId.Scroll,value); }
}
public event EventHandler ValueChanged
{
add { AddHandler(EventId.ValueChanged,value); }
remove { RemoveHandler(EventId.ValueChanged,value); }
}
private void idleTimer_Tick(object sender, EventArgs e)
{
idleTimer.Stop();
OnMouseMoveActual(idleMouse);
}
}; // class ScrollBar
}; // namespace System.Windows.Forms
| |
#region Header
// Vorspire _,-'/-'/ PortalStream.cs
// . __,-; ,'( '/
// \. `-.__`-._`:_,-._ _ , . ``
// `:-._,------' ` _,`--` -: `_ , ` ,' :
// `---..__,,--' (C) 2018 ` -'. -'
// # Vita-Nex [http://core.vita-nex.com] #
// {o)xxx|===============- # -===============|xxx(o}
// # The MIT License (MIT) #
#endregion
#region References
using System;
using System.IO;
using System.Net.Sockets;
#endregion
namespace Multiverse
{
public sealed class PortalStream : Stream
{
private PortalBuffer _Buffer;
public override long Length
{
get
{
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
return _Buffer.Size;
}
}
private long _Position;
public override long Position
{
get { return _Position; }
set
{
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
if (value < 0 || value > _Buffer.Size)
{
throw new ArgumentOutOfRangeException("value", value, "Value must be >= 0 || <= " + _Buffer.Size);
}
_Position = value;
}
}
private bool _Readable = true, _Writable = true, _Seekable = true;
public override bool CanRead { get { return _Readable; } }
public override bool CanWrite { get { return _Writable; } }
public override bool CanSeek { get { return _Seekable; } }
public override bool CanTimeout { get { return false; } }
public PortalStream()
{
_Buffer = new PortalBuffer();
}
public PortalStream(long size)
{
_Buffer = new PortalBuffer(size);
}
public PortalStream(long size, int coalesce)
{
_Buffer = new PortalBuffer(size, coalesce);
}
public PortalStream(PortalBuffer buffer)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (buffer.IsDisposed)
{
throw new ObjectDisposedException("buffer");
}
_Buffer = buffer;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_Readable = false;
_Writable = false;
_Seekable = false;
_Buffer = null;
}
}
finally
{
base.Dispose(disposing);
}
}
public override void Flush()
{ }
public override long Seek(long offset, SeekOrigin origin)
{
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
if (!_Seekable)
{
throw new InvalidOperationException();
}
lock (_Buffer)
{
switch (origin)
{
case SeekOrigin.Begin:
{
if (offset < 0 || offset >= _Buffer.Size)
{
throw new ArgumentOutOfRangeException("offset", origin, "Result must be >= 0 || <= " + _Buffer.Size);
}
_Position = offset;
}
break;
case SeekOrigin.Current:
{
if (_Position + offset < 0 || _Position + offset >= _Buffer.Size)
{
throw new ArgumentOutOfRangeException("offset", origin, "Result must be >= 0 || <= " + _Buffer.Size);
}
_Position += offset;
}
break;
case SeekOrigin.End:
{
if (_Buffer.Size - offset < 0 || _Buffer.Size - offset >= _Buffer.Size)
{
throw new ArgumentOutOfRangeException("offset", origin, "Result must be >= 0 || <= " + _Buffer.Size);
}
_Position = _Buffer.Size - offset;
}
break;
default:
throw new ArgumentOutOfRangeException("origin", origin, null);
}
return _Position;
}
}
public override void SetLength(long size)
{
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
lock (_Buffer)
{
_Buffer.SetSize(size);
}
}
public PortalBuffer GetBuffer()
{
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
return _Buffer;
}
public override int ReadByte()
{
if (!_Readable)
{
throw new InvalidOperationException();
}
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
lock (_Buffer)
{
if (_Position < _Buffer.Size)
{
return _Buffer[_Position++];
}
}
return -1;
}
public override int Read(byte[] buffer, int offset, int count)
{
if (!_Readable)
{
throw new InvalidOperationException();
}
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
lock (_Buffer)
{
for (int i = 0, o = offset; i < count; i++, o++)
{
if (_Position >= _Buffer.Size)
{
throw new EndOfStreamException();
}
buffer[o] = _Buffer[_Position++];
}
}
return count;
}
public override void WriteByte(byte value)
{
if (!_Writable)
{
throw new InvalidOperationException();
}
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
lock (_Buffer)
{
if (_Position + 1 > _Buffer.Size)
{
_Buffer.SetSize(_Position + 1);
}
_Buffer[_Position++] = value;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (!_Writable)
{
throw new InvalidOperationException();
}
if (_Buffer == null || _Buffer.IsDisposed)
{
throw new ObjectDisposedException("_Buffer");
}
lock (_Buffer)
{
if (_Position + count > _Buffer.Size)
{
_Buffer.SetSize(_Position + count);
}
for (int i = 0, o = offset; i < count; i++, o++)
{
_Buffer[_Position++] = buffer[o];
}
}
}
public long ReadToStream(Stream dest, long offset, long length)
{
dest.Seek(offset, offset < 0 ? SeekOrigin.End : SeekOrigin.Begin);
return ReadToStream(dest, length);
}
public long ReadToStream(Stream dest, long length)
{
lock (_Buffer)
{
length = _Buffer.WriteToStream(dest, _Position, length);
_Position += length;
return length;
}
}
public long WriteFromStream(Stream source, long offset, long length)
{
source.Seek(offset, offset < 0 ? SeekOrigin.End : SeekOrigin.Begin);
return WriteFromStream(source, length);
}
public long WriteFromStream(Stream dest, long length)
{
lock (_Buffer)
{
length = _Buffer.ReadFromStream(dest, _Position, length);
_Position += length;
return length;
}
}
public long Send(Socket socket, long offset, long length)
{
return _Buffer.Send(socket, offset, length);
}
public long Receive(Socket socket, long offset, long length)
{
return _Buffer.Receive(socket, offset, length);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Globalization;
namespace Microsoft.PythonTools.Parsing {
/// <summary>
/// Represents a location in source code.
/// </summary>
[Serializable]
public struct SourceLocation {
// TODO: remove index
private readonly int _index;
private readonly int _line;
private readonly int _column;
/// <summary>
/// Creates a new source location.
/// </summary>
/// <param name="index">The index in the source stream the location represents (0-based).</param>
/// <param name="line">The line in the source stream the location represents (1-based).</param>
/// <param name="column">The column in the source stream the location represents (1-based).</param>
public SourceLocation(int index, int line, int column) {
ValidateLocation(index, line, column);
_index = index;
_line = line;
_column = column;
}
private static void ValidateLocation(int index, int line, int column) {
if (index < 0) {
throw ErrorOutOfRange("index", 0);
}
if (line < 1) {
throw ErrorOutOfRange("line", 1);
}
if (column < 1) {
throw ErrorOutOfRange("column", 1);
}
}
private static Exception ErrorOutOfRange(object p0, object p1) {
return new ArgumentOutOfRangeException(string.Format("{0} must be greater than or equal to {1}", p0, p1));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
private SourceLocation(int index, int line, int column, bool noChecks) {
_index = index;
_line = line;
_column = column;
}
/// <summary>
/// The index in the source stream the location represents (0-based).
/// </summary>
public int Index {
get { return _index; }
}
/// <summary>
/// The line in the source stream the location represents (1-based).
/// </summary>
public int Line {
get { return _line; }
}
/// <summary>
/// The column in the source stream the location represents (1-based).
/// </summary>
public int Column {
get { return _column; }
}
/// <summary>
/// Compares two specified location values to see if they are equal.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the locations are the same, False otherwise.</returns>
public static bool operator ==(SourceLocation left, SourceLocation right) {
return left._index == right._index && left._line == right._line && left._column == right._column;
}
/// <summary>
/// Compares two specified location values to see if they are not equal.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the locations are not the same, False otherwise.</returns>
public static bool operator !=(SourceLocation left, SourceLocation right) {
return left._index != right._index || left._line != right._line || left._column != right._column;
}
/// <summary>
/// Compares two specified location values to see if one is before the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is before the other location, False otherwise.</returns>
public static bool operator <(SourceLocation left, SourceLocation right) {
return left._index < right._index;
}
/// <summary>
/// Compares two specified location values to see if one is after the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is after the other location, False otherwise.</returns>
public static bool operator >(SourceLocation left, SourceLocation right) {
return left._index > right._index;
}
/// <summary>
/// Compares two specified location values to see if one is before or the same as the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is before or the same as the other location, False otherwise.</returns>
public static bool operator <=(SourceLocation left, SourceLocation right) {
return left._index <= right._index;
}
/// <summary>
/// Compares two specified location values to see if one is after or the same as the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is after or the same as the other location, False otherwise.</returns>
public static bool operator >=(SourceLocation left, SourceLocation right) {
return left._index >= right._index;
}
/// <summary>
/// Compares two specified location values.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>0 if the locations are equal, -1 if the left one is less than the right one, 1 otherwise.</returns>
public static int Compare(SourceLocation left, SourceLocation right) {
if (left < right) return -1;
if (right > left) return 1;
return 0;
}
/// <summary>
/// A location that is valid but represents no location at all.
/// </summary>
public static readonly SourceLocation None = new SourceLocation(0, 0xfeefee, 0, true);
/// <summary>
/// An invalid location.
/// </summary>
public static readonly SourceLocation Invalid = new SourceLocation(0, 0, 0, true);
/// <summary>
/// A minimal valid location.
/// </summary>
public static readonly SourceLocation MinValue = new SourceLocation(0, 1, 1);
/// <summary>
/// Whether the location is a valid location.
/// </summary>
/// <returns>True if the location is valid, False otherwise.</returns>
public bool IsValid {
get {
return this._line != 0 && this._column != 0;
}
}
public override bool Equals(object obj) {
if (!(obj is SourceLocation)) return false;
SourceLocation other = (SourceLocation)obj;
return other._index == _index && other._line == _line && other._column == _column;
}
public override int GetHashCode() {
return (_line << 16) ^ _column;
}
public override string ToString() {
return "(" + _line + "," + _column + ")";
}
internal string ToDebugString() {
return String.Format(CultureInfo.CurrentCulture, "({0},{1},{2})", _index, _line, _column);
}
}
}
| |
/*
* 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.Drawing;
using System.Drawing.Imaging;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using System.Reflection;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicTextureModule")]
public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int ALL_SIDES = -1;
public const int DISP_EXPIRE = 1;
public const int DISP_TEMP = 2;
/// <summary>
/// If true then where possible dynamic textures are reused.
/// </summary>
public bool ReuseTextures { get; set; }
/// <summary>
/// If false, then textures which have a low data size are not reused when ReuseTextures = true.
/// </summary>
/// <remarks>
/// LL viewers 3.3.4 and before appear to not fully render textures pulled from the viewer cache if those
/// textures have a relatively high pixel surface but a small data size. Typically, this appears to happen
/// if the data size is smaller than the viewer's discard level 2 size estimate. So if this is setting is
/// false, textures smaller than the calculation in IsSizeReuseable are always regenerated rather than reused
/// to work around this problem.</remarks>
public bool ReuseLowDataTextures { get; set; }
private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>();
private Dictionary<string, IDynamicTextureRender> RenderPlugins =
new Dictionary<string, IDynamicTextureRender>();
private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>();
/// <summary>
/// Record dynamic textures that we can reuse for a given data and parameter combination rather than
/// regenerate.
/// </summary>
/// <remarks>
/// Key is string.Format("{0}{1}", data
/// </remarks>
private Cache m_reuseableDynamicTextures;
/// <summary>
/// This constructor is only here because of the Unit Tests...
/// Don't use it.
/// </summary>
public DynamicTextureModule()
{
m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
}
#region IDynamicTextureManager Members
public void RegisterRender(string handleType, IDynamicTextureRender render)
{
if (!RenderPlugins.ContainsKey(handleType))
{
RenderPlugins.Add(handleType, render);
}
}
/// <summary>
/// Called by code which actually renders the dynamic texture to supply texture data.
/// </summary>
/// <param name="updaterId"></param>
/// <param name="texture"></param>
public void ReturnData(UUID updaterId, IDynamicTexture texture)
{
DynamicTextureUpdater updater = null;
lock (Updaters)
{
if (Updaters.ContainsKey(updaterId))
{
updater = Updaters[updaterId];
}
}
if (updater != null)
{
if (RegisteredScenes.ContainsKey(updater.SimUUID))
{
Scene scene = RegisteredScenes[updater.SimUUID];
UUID newTextureID = updater.DataReceived(texture.Data, scene);
if (ReuseTextures
&& !updater.BlendWithOldTexture
&& texture.IsReuseable
&& (ReuseLowDataTextures || IsDataSizeReuseable(texture)))
{
m_reuseableDynamicTextures.Store(
GenerateReusableTextureKey(texture.InputCommands, texture.InputParams), newTextureID);
}
}
}
if (updater.UpdateTimer == 0)
{
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Remove(updater.UpdaterID);
}
}
}
}
/// <summary>
/// Determines whether the texture is reuseable based on its data size.
/// </summary>
/// <remarks>
/// This is a workaround for a viewer bug where very small data size textures relative to their pixel size
/// are not redisplayed properly when pulled from cache. The calculation here is based on the typical discard
/// level of 2, a 'rate' of 0.125 and 4 components (which makes for a factor of 0.5).
/// </remarks>
/// <returns></returns>
private bool IsDataSizeReuseable(IDynamicTexture texture)
{
// Console.WriteLine("{0} {1}", texture.Size.Width, texture.Size.Height);
int discardLevel2DataThreshold = (int)Math.Ceiling((texture.Size.Width >> 2) * (texture.Size.Height >> 2) * 0.5);
// m_log.DebugFormat(
// "[DYNAMIC TEXTURE MODULE]: Discard level 2 threshold {0}, texture data length {1}",
// discardLevel2DataThreshold, texture.Data.Length);
return discardLevel2DataThreshold < texture.Data.Length;
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer)
{
return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureURL(simID, primID, contentType, url,
extraParams, updateTimer, SetBlending,
(int)(DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url,
string extraParams, int updateTimer, bool SetBlending,
int disp, byte AlphaValue, int face)
{
if (RenderPlugins.ContainsKey(contentType))
{
DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID;
updater.PrimID = primID;
updater.ContentType = contentType;
updater.Url = url;
updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue;
updater.Face = face;
updater.Disp = disp;
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams);
return updater.UpdaterID;
}
return UUID.Zero;
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer)
{
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, byte AlphaValue)
{
return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending,
(int) (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES);
}
public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data,
string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face)
{
if (!RenderPlugins.ContainsKey(contentType))
return UUID.Zero;
Scene scene;
RegisteredScenes.TryGetValue(simID, out scene);
if (scene == null)
return UUID.Zero;
SceneObjectPart part = scene.GetSceneObjectPart(primID);
if (part == null)
return UUID.Zero;
// If we want to reuse dynamic textures then we have to ignore any request from the caller to expire
// them.
if (ReuseTextures)
disp = disp & ~DISP_EXPIRE;
DynamicTextureUpdater updater = new DynamicTextureUpdater();
updater.SimUUID = simID;
updater.PrimID = primID;
updater.ContentType = contentType;
updater.BodyData = data;
updater.UpdateTimer = updateTimer;
updater.UpdaterID = UUID.Random();
updater.Params = extraParams;
updater.BlendWithOldTexture = SetBlending;
updater.FrontAlpha = AlphaValue;
updater.Face = face;
updater.Url = "Local image";
updater.Disp = disp;
object objReusableTextureUUID = null;
if (ReuseTextures && !updater.BlendWithOldTexture)
{
string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams);
objReusableTextureUUID = m_reuseableDynamicTextures.Get(reuseableTextureKey);
if (objReusableTextureUUID != null)
{
// If something else has removed this temporary asset from the cache, detect and invalidate
// our cached uuid.
if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null)
{
m_reuseableDynamicTextures.Invalidate(reuseableTextureKey);
objReusableTextureUUID = null;
}
}
}
// We cannot reuse a dynamic texture if the data is going to be blended with something already there.
if (objReusableTextureUUID == null)
{
lock (Updaters)
{
if (!Updaters.ContainsKey(updater.UpdaterID))
{
Updaters.Add(updater.UpdaterID, updater);
}
}
// m_log.DebugFormat(
// "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}",
// part.Name, part.ParentGroup.Scene.Name);
RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams);
}
else
{
// m_log.DebugFormat(
// "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}",
// objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name);
// No need to add to updaters as the texture is always the same. Not that this functionality
// apppears to be implemented anyway.
updater.UpdatePart(part, (UUID)objReusableTextureUUID);
}
return updater.UpdaterID;
}
private string GenerateReusableTextureKey(string data, string extraParams)
{
return string.Format("{0}{1}", data, extraParams);
}
public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize,
out double xSize, out double ySize)
{
xSize = 0;
ySize = 0;
if (RenderPlugins.ContainsKey(contentType))
{
RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize);
}
}
#endregion
#region ISharedRegionModule Members
public void Initialise(IConfigSource config)
{
IConfig texturesConfig = config.Configs["Textures"];
if (texturesConfig != null)
{
ReuseTextures = texturesConfig.GetBoolean("ReuseDynamicTextures", false);
ReuseLowDataTextures = texturesConfig.GetBoolean("ReuseDynamicLowDataTextures", false);
if (ReuseTextures)
{
m_reuseableDynamicTextures = new Cache(CacheMedium.Memory, CacheStrategy.Conservative);
m_reuseableDynamicTextures.DefaultTTL = new TimeSpan(24, 0, 0);
}
}
}
public void PostInitialise()
{
}
public void AddRegion(Scene scene)
{
if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
{
RegisteredScenes.Add(scene.RegionInfo.RegionID, scene);
scene.RegisterModuleInterface<IDynamicTextureManager>(this);
}
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
if (RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID))
RegisteredScenes.Remove(scene.RegionInfo.RegionID);
}
public void Close()
{
}
public string Name
{
get { return "DynamicTextureModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
#region Nested type: DynamicTextureUpdater
public class DynamicTextureUpdater
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool BlendWithOldTexture = false;
public string BodyData;
public string ContentType;
public byte FrontAlpha = 255;
public string Params;
public UUID PrimID;
public bool SetNewFrontAlpha = false;
public UUID SimUUID;
public UUID UpdaterID;
public int UpdateTimer;
public int Face;
public int Disp;
public string Url;
public DynamicTextureUpdater()
{
UpdateTimer = 0;
BodyData = null;
}
/// <summary>
/// Update the given part with the new texture.
/// </summary>
/// <returns>
/// The old texture UUID.
/// </returns>
public UUID UpdatePart(SceneObjectPart part, UUID textureID)
{
UUID oldID;
lock (part)
{
// mostly keep the values from before
Primitive.TextureEntry tmptex = part.Shape.Textures;
// FIXME: Need to return the appropriate ID if only a single face is replaced.
oldID = tmptex.DefaultTexture.TextureID;
if (Face == ALL_SIDES)
{
oldID = tmptex.DefaultTexture.TextureID;
tmptex.DefaultTexture.TextureID = textureID;
}
else
{
try
{
Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face);
texface.TextureID = textureID;
tmptex.FaceTextures[Face] = texface;
}
catch (Exception)
{
tmptex.DefaultTexture.TextureID = textureID;
}
}
// I'm pretty sure we always want to force this to true
// I'm pretty sure noone whats to set fullbright true if it wasn't true before.
// tmptex.DefaultTexture.Fullbright = true;
part.UpdateTextureEntry(tmptex.GetBytes());
}
return oldID;
}
/// <summary>
/// Called once new texture data has been received for this updater.
/// </summary>
/// <param name="data"></param>
/// <param name="scene"></param>
/// <param name="isReuseable">True if the data given is reuseable.</param>
/// <returns>The asset UUID given to the incoming data.</returns>
public UUID DataReceived(byte[] data, Scene scene)
{
SceneObjectPart part = scene.GetSceneObjectPart(PrimID);
if (part == null || data == null || data.Length <= 1)
{
string msg =
String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url);
scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,
0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false);
return UUID.Zero;
}
byte[] assetData = null;
AssetBase oldAsset = null;
if (BlendWithOldTexture)
{
Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture;
if (defaultFace != null)
{
oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString());
if (oldAsset != null)
assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha);
}
}
if (assetData == null)
{
assetData = new byte[data.Length];
Array.Copy(data, assetData, data.Length);
}
// Create a new asset for user
AssetBase asset
= new AssetBase(
UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture,
scene.RegionInfo.RegionID.ToString());
asset.Data = assetData;
asset.Description = String.Format("URL image : {0}", Url);
asset.Local = false;
asset.Temporary = ((Disp & DISP_TEMP) != 0);
scene.AssetService.Store(asset);
IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>();
if (cacheLayerDecode != null)
{
if (!cacheLayerDecode.Decode(asset.FullID, asset.Data))
m_log.WarnFormat(
"[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed",
asset.ID, part.Name, part.ParentGroup.Scene.Name);
}
UUID oldID = UpdatePart(part, asset.FullID);
if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0))
{
if (oldAsset == null)
oldAsset = scene.AssetService.Get(oldID.ToString());
if (oldAsset != null)
{
if (oldAsset.Temporary)
{
scene.AssetService.Delete(oldID.ToString());
}
}
}
return asset.FullID;
}
private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha)
{
ManagedImage managedImage;
Image image;
if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image))
{
Bitmap image1 = new Bitmap(image);
if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image))
{
Bitmap image2 = new Bitmap(image);
if (setNewAlpha)
SetAlpha(ref image1, newAlpha);
Bitmap joint = MergeBitMaps(image1, image2);
byte[] result = new byte[0];
try
{
result = OpenJPEG.EncodeFromImage(joint, true);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}",
e.Message, e.StackTrace);
}
return result;
}
}
return null;
}
public Bitmap MergeBitMaps(Bitmap front, Bitmap back)
{
Bitmap joint;
Graphics jG;
joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb);
jG = Graphics.FromImage(joint);
jG.DrawImage(back, 0, 0, back.Width, back.Height);
jG.DrawImage(front, 0, 0, back.Width, back.Height);
return joint;
}
private void SetAlpha(ref Bitmap b, byte alpha)
{
for (int w = 0; w < b.Width; w++)
{
for (int h = 0; h < b.Height; h++)
{
b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h)));
}
}
}
}
#endregion
}
}
| |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Caliburn.Micro;
using JetBrains.Annotations;
using LogoFX.Client.Mvvm.Commanding;
using LogoFX.Client.Mvvm.ViewModel.Extensions;
using LogoFX.Client.Mvvm.ViewModel.Services;
using LogoFX.Client.Mvvm.ViewModel.Shared;
using LogoFX.Core;
using $saferootprojectname$.Client.Model.Contracts;
namespace $safeprojectname$.ViewModels
{
[UsedImplicitly]
public class MainViewModel : BusyScreen
{
private readonly IViewModelCreatorService _viewModelCreatorService;
private readonly IDataService _dataService;
private readonly IWindowManager _windowManager;
public MainViewModel(
IViewModelCreatorService viewModelCreatorService,
IDataService dataService,
IWindowManager windowManager)
{
_viewModelCreatorService = viewModelCreatorService;
_dataService = dataService;
_windowManager = windowManager;
NewWarehouseItem();
}
private ICommand _newCommand;
public ICommand NewCommand
{
get
{
return _newCommand ?? (_newCommand = ActionCommand.Do(NewWarehouseItem));
}
}
private ICommand _deleteCommand;
public ICommand DeleteCommand
{
get
{
return _deleteCommand ??
(_deleteCommand = ActionCommand
.When(() => ActiveWarehouseItem?.Item.Model.IsNew == false)
.Do(DeleteSelectedItem)
.RequeryOnPropertyChanged(this, () => ActiveWarehouseItem));
}
}
private WarehouseItemContainerViewModel _activeWarehouseItem;
public WarehouseItemContainerViewModel ActiveWarehouseItem
{
get { return _activeWarehouseItem; }
set
{
if (_activeWarehouseItem == value)
{
return;
}
if (_activeWarehouseItem != null)
{
_activeWarehouseItem.Saving -= OnSaving;
_activeWarehouseItem.Saved -= OnSaved;
}
_activeWarehouseItem = value;
if (_activeWarehouseItem != null)
{
_activeWarehouseItem.Saving += OnSaving;
_activeWarehouseItem.Saved += OnSaved;
}
NotifyOfPropertyChange();
}
}
private async void OnSaved(object sender, ResultEventArgs e)
{
IsBusy = true;
try
{
await _dataService.GetWarehouseItemsAsync();
}
finally
{
IsBusy = false;
}
NewWarehouseItem();
}
private void OnSaving(object sender, EventArgs e)
{
IsBusy = true;
}
private WarehouseItemsViewModel _warehouseItems;
public WarehouseItemsViewModel WarehouseItems
{
get { return _warehouseItems ?? (_warehouseItems = CreateWarehouseItems()); }
}
private WarehouseItemsViewModel CreateWarehouseItems()
{
var warehouseItemsViewModel = _viewModelCreatorService.CreateViewModel<WarehouseItemsViewModel>();
EventHandler strongHandler = WarehouseItemsSelectionChanged;
warehouseItemsViewModel.Items.SelectionChanged += WeakDelegate.From(strongHandler);
return warehouseItemsViewModel;
}
private void WarehouseItemsSelectionChanged(object sender, EventArgs e)
{
var selectedItem = WarehouseItems.Items.SelectedItem;
ActiveWarehouseItem = selectedItem == null ? null :
_viewModelCreatorService.CreateViewModel<IWarehouseItem, WarehouseItemContainerViewModel>(
((WarehouseItemViewModel) WarehouseItems.Items.SelectedItem).Model);
}
private EventsViewModel _events;
public EventsViewModel Events
{
get { return _events ?? (_events = _viewModelCreatorService.CreateViewModel<EventsViewModel>()); }
}
private async void NewWarehouseItem()
{
IsBusy = true;
try
{
var warehouseItem = await _dataService.NewWarehouseItemAsync();
var newItem = _viewModelCreatorService.CreateViewModel<IWarehouseItem, WarehouseItemContainerViewModel>(warehouseItem);
ActiveWarehouseItem = newItem;
}
finally
{
IsBusy = false;
}
}
private async void DeleteSelectedItem()
{
IsBusy = true;
try
{
await _dataService.DeleteWarehouseItemAsync(ActiveWarehouseItem?.Item.Model);
}
finally
{
IsBusy = false;
}
NewWarehouseItem();
}
protected override async void OnInitialize()
{
base.OnInitialize();
await _dataService.GetWarehouseItemsAsync();
}
public override async void CanClose(Action<bool> callback)
{
if (_dataService.WarehouseItems.Any(t => t.IsDirty))
{
var exitOptionsViewModel = _viewModelCreatorService.CreateViewModel<ExitOptionsViewModel>();
_windowManager.ShowDialog(exitOptionsViewModel);
var result = exitOptionsViewModel.Result;
if (result == MessageResult.Yes)
{
foreach (var warehouseItem in _dataService.WarehouseItems.Where(t => t.IsDirty && t.CanCommitChanges))
{
await _dataService.SaveWarehouseItemAsync(warehouseItem);
warehouseItem.CommitChanges();
}
await WaitForTestApplication();
callback(true);
}
else if (result == MessageResult.No)
{
foreach (var warehouseItem in _dataService.WarehouseItems.Where(t => t.IsDirty && t.CanCancelChanges))
{
warehouseItem.CancelChanges();
}
await WaitForTestApplication();
callback(true);
}
else if (result == MessageResult.Cancel)
{
callback(false);
}
}
else
{
callback(true);
}
}
private static async Task WaitForTestApplication()
{
//Added for testability purposes only
//The UI test engine has to query controls and perform several actions
await Task.Delay(1000);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
internal partial class CertificateOperations : IServiceOperations<AutomationManagementClient>, ICertificateOperations
{
/// <summary>
/// Initializes a new instance of the CertificateOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal CertificateOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a certificate. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update
/// certificate operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create or update certificate operation.
/// </returns>
public async Task<CertificateCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, CertificateCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.Base64Value == null)
{
throw new ArgumentNullException("parameters.Properties.Base64Value");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject certificateCreateOrUpdateParametersValue = new JObject();
requestDoc = certificateCreateOrUpdateParametersValue;
certificateCreateOrUpdateParametersValue["name"] = parameters.Name;
JObject propertiesValue = new JObject();
certificateCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["base64Value"] = parameters.Properties.Base64Value;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
if (parameters.Properties.Thumbprint != null)
{
propertiesValue["thumbprint"] = parameters.Properties.Thumbprint;
}
propertiesValue["isExportable"] = parameters.Properties.IsExportable;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Certificate certificateInstance = new Certificate();
result.Certificate = certificateInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
certificateInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
CertificateProperties propertiesInstance = new CertificateProperties();
certificateInstance.Properties = propertiesInstance;
JToken thumbprintValue = propertiesValue2["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken expiryTimeValue = propertiesValue2["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isExportableValue = propertiesValue2["isExportable"];
if (isExportableValue != null && isExportableValue.Type != JTokenType.Null)
{
bool isExportableInstance = ((bool)isExportableValue);
propertiesInstance.IsExportable = isExportableInstance;
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete the certificate. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='certificateName'>
/// Required. The name of certificate.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string certificateName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (certificateName == null)
{
throw new ArgumentNullException("certificateName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("certificateName", certificateName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(certificateName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the certificate identified by certificate name. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='certificateName'>
/// Required. The name of certificate.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get certificate operation.
/// </returns>
public async Task<CertificateGetResponse> GetAsync(string resourceGroupName, string automationAccount, string certificateName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (certificateName == null)
{
throw new ArgumentNullException("certificateName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("certificateName", certificateName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(certificateName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Certificate certificateInstance = new Certificate();
result.Certificate = certificateInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
certificateInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CertificateProperties propertiesInstance = new CertificateProperties();
certificateInstance.Properties = propertiesInstance;
JToken thumbprintValue = propertiesValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken expiryTimeValue = propertiesValue["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isExportableValue = propertiesValue["isExportable"];
if (isExportableValue != null && isExportableValue.Type != JTokenType.Null)
{
bool isExportableInstance = ((bool)isExportableValue);
propertiesInstance.IsExportable = isExportableInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list certificate operation.
/// </returns>
public async Task<CertificateListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/certificates";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Certificate certificateInstance = new Certificate();
result.Certificates.Add(certificateInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
certificateInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CertificateProperties propertiesInstance = new CertificateProperties();
certificateInstance.Properties = propertiesInstance;
JToken thumbprintValue = propertiesValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken expiryTimeValue = propertiesValue["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isExportableValue = propertiesValue["isExportable"];
if (isExportableValue != null && isExportableValue.Type != JTokenType.Null)
{
bool isExportableInstance = ((bool)isExportableValue);
propertiesInstance.IsExportable = isExportableInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of certificates. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list certificate operation.
/// </returns>
public async Task<CertificateListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
CertificateListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new CertificateListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Certificate certificateInstance = new Certificate();
result.Certificates.Add(certificateInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
certificateInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
CertificateProperties propertiesInstance = new CertificateProperties();
certificateInstance.Properties = propertiesInstance;
JToken thumbprintValue = propertiesValue["thumbprint"];
if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null)
{
string thumbprintInstance = ((string)thumbprintValue);
propertiesInstance.Thumbprint = thumbprintInstance;
}
JToken expiryTimeValue = propertiesValue["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isExportableValue = propertiesValue["isExportable"];
if (isExportableValue != null && isExportableValue.Type != JTokenType.Null)
{
bool isExportableInstance = ((bool)isExportableValue);
propertiesInstance.IsExportable = isExportableInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update a certificate. (see
/// http://aka.ms/azureautomationsdk/certificateoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the patch certificate
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string automationAccount, CertificatePatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/certificates/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject certificatePatchParametersValue = new JObject();
requestDoc = certificatePatchParametersValue;
certificatePatchParametersValue["name"] = parameters.Name;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
certificatePatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using Shouldly;
using System;
using Xunit;
namespace Valit.Tests.Double
{
public class Double_IsGreaterThan_Tests
{
[Fact]
public void Double_IsGreaterThan_For_Not_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double>)null)
.IsGreaterThan(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsGreaterThan_For_Not_Nullable_Value_And_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double>)null)
.IsGreaterThan((double?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsGreaterThan_For_Nullable_Value_And_Not_Nullable_Value_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double?>)null)
.IsGreaterThan(1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Fact]
public void Double_IsGreaterThan_For_Nullable_Values_Throws_When_Null_Rule_Is_Given()
{
var exception = Record.Exception(() => {
((IValitRule<Model, double?>)null)
.IsGreaterThan((double?)1);
});
exception.ShouldBeOfType(typeof(ValitException));
}
[Theory]
[InlineData(9, false)]
[InlineData(double.NaN, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_NaN_And_Value(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(9, false)]
[InlineData(double.NaN, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_NaN_And_NullableValue(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NaN, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(9, false)]
[InlineData(double.NaN, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_NullableNaN_And_Value(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(9, false)]
[InlineData(double.NaN, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_NullableNaN_And_NullableValue(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.NullableNaN, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(9, true)]
[InlineData(10, false)]
[InlineData(11, false)]
[InlineData(double.NaN, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_Not_Nullable_Values(double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData((double)9, true)]
[InlineData((double)10, false)]
[InlineData((double)11, false)]
[InlineData(double.NaN, false)]
[InlineData(null, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_Not_Nullable_Value_And_Nullable_Value(double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => m.Value, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, 9, true)]
[InlineData(false, 10, false)]
[InlineData(false, 11, false)]
[InlineData(true, 10, false)]
[InlineData(false, double.NaN, false)]
[InlineData(true, double.NaN, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_Nullable_Value_And_Not_Nullable_Value(bool useNullValue, double value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
[Theory]
[InlineData(false, (double)9, true)]
[InlineData(false, (double)10, false)]
[InlineData(false, (double)11, false)]
[InlineData(false, double.NaN, false)]
[InlineData(false, null, false)]
[InlineData(true, (double)10, false)]
[InlineData(true, double.NaN, false)]
[InlineData(true, null, false)]
public void Double_IsGreaterThan_Returns_Proper_Results_For_Nullable_Values(bool useNullValue, double? value, bool expected)
{
IValitResult result = ValitRules<Model>
.Create()
.Ensure(m => useNullValue ? m.NullValue : m.NullableValue, _ => _
.IsGreaterThan(value))
.For(_model)
.Validate();
result.Succeeded.ShouldBe(expected);
}
#region ARRANGE
public Double_IsGreaterThan_Tests()
{
_model = new Model();
}
private readonly Model _model;
class Model
{
public double Value => 10;
public double NaN => double.NaN;
public double? NullableValue => 10;
public double? NullValue => null;
public double? NullableNaN => double.NaN;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
namespace System.ServiceModel.Channels
{
internal abstract class RequestContextBase : RequestContext
{
private TimeSpan _defaultSendTimeout;
private TimeSpan _defaultCloseTimeout;
private CommunicationState _state = CommunicationState.Opened;
private Message _requestMessage;
private Exception _requestMessageException;
private bool _replySent;
private bool _replyInitiated;
private bool _aborted;
private object _thisLock = new object();
protected RequestContextBase(Message requestMessage, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
{
_defaultSendTimeout = defaultSendTimeout;
_defaultCloseTimeout = defaultCloseTimeout;
_requestMessage = requestMessage;
}
public void ReInitialize(Message requestMessage)
{
_state = CommunicationState.Opened;
_requestMessageException = null;
_replySent = false;
_replyInitiated = false;
_aborted = false;
_requestMessage = requestMessage;
}
public override Message RequestMessage
{
get
{
if (_requestMessageException != null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_requestMessageException);
}
return _requestMessage;
}
}
protected void SetRequestMessage(Message requestMessage)
{
Fx.Assert(_requestMessageException == null, "Cannot have both a requestMessage and a requestException.");
_requestMessage = requestMessage;
}
protected void SetRequestMessage(Exception requestMessageException)
{
Fx.Assert(_requestMessage == null, "Cannot have both a requestMessage and a requestException.");
_requestMessageException = requestMessageException;
}
protected bool ReplyInitiated
{
get { return _replyInitiated; }
}
protected object ThisLock
{
get
{
return _thisLock;
}
}
public bool Aborted
{
get
{
return _aborted;
}
}
public TimeSpan DefaultCloseTimeout
{
get { return _defaultCloseTimeout; }
}
public TimeSpan DefaultSendTimeout
{
get { return _defaultSendTimeout; }
}
public override void Abort()
{
lock (ThisLock)
{
if (_state == CommunicationState.Closed)
return;
_state = CommunicationState.Closing;
_aborted = true;
}
try
{
this.OnAbort();
}
finally
{
_state = CommunicationState.Closed;
}
}
public override void Close()
{
this.Close(_defaultCloseTimeout);
}
public override void Close(TimeSpan timeout)
{
if (timeout < TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", timeout, SR.ValueMustBeNonNegative));
}
bool sendAck = false;
lock (ThisLock)
{
if (_state != CommunicationState.Opened)
return;
if (TryInitiateReply())
{
sendAck = true;
}
_state = CommunicationState.Closing;
}
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
bool throwing = true;
try
{
if (sendAck)
{
OnReply(null, timeoutHelper.RemainingTime());
}
OnClose(timeoutHelper.RemainingTime());
_state = CommunicationState.Closed;
throwing = false;
}
finally
{
if (throwing)
this.Abort();
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!disposing)
return;
if (_replySent)
{
this.Close();
}
else
{
this.Abort();
}
}
protected abstract void OnAbort();
protected abstract void OnClose(TimeSpan timeout);
protected abstract void OnReply(Message message, TimeSpan timeout);
protected abstract IAsyncResult OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state);
protected abstract void OnEndReply(IAsyncResult result);
protected void ThrowIfInvalidReply()
{
if (_state == CommunicationState.Closed || _state == CommunicationState.Closing)
{
if (_aborted)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.RequestContextAborted));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
if (_replyInitiated)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.ReplyAlreadySent));
}
/// <summary>
/// Attempts to initiate the reply. If a reply is not initiated already (and the object is opened),
/// then it initiates the reply and returns true. Otherwise, it returns false.
/// </summary>
protected bool TryInitiateReply()
{
lock (_thisLock)
{
if ((_state != CommunicationState.Opened) || _replyInitiated)
{
return false;
}
else
{
_replyInitiated = true;
return true;
}
}
}
public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state)
{
return this.BeginReply(message, _defaultSendTimeout, callback, state);
}
public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
// "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
return OnBeginReply(message, timeout, callback, state);
}
public override void EndReply(IAsyncResult result)
{
OnEndReply(result);
_replySent = true;
}
public override void Reply(Message message)
{
this.Reply(message, _defaultSendTimeout);
}
public override void Reply(Message message, TimeSpan timeout)
{
// "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
this.OnReply(message, timeout);
_replySent = true;
}
// This method is designed for WebSocket only, and will only be used once the WebSocket response was sent.
// For WebSocket, we never call HttpRequestContext.Reply to send the response back.
// Instead we call AcceptWebSocket directly. So we need to set the replyInitiated and
// replySent boolean to be true once the response was sent successfully. Otherwise when we
// are disposing the HttpRequestContext, we will see a bunch of warnings in trace log.
protected void SetReplySent()
{
lock (_thisLock)
{
this.ThrowIfInvalidReply();
_replyInitiated = true;
}
_replySent = true;
}
}
internal class RequestContextMessageProperty : IDisposable
{
private RequestContext _context;
private object _thisLock = new object();
public RequestContextMessageProperty(RequestContext context)
{
_context = context;
}
public static string Name
{
get { return "requestContext"; }
}
void IDisposable.Dispose()
{
bool success = false;
RequestContext thisContext;
lock (_thisLock)
{
if (_context == null)
return;
thisContext = _context;
_context = null;
}
try
{
thisContext.Close();
success = true;
}
catch (CommunicationException)
{
}
catch (TimeoutException e)
{
if (TD.CloseTimeoutIsEnabled())
{
TD.CloseTimeout(e.Message);
}
}
finally
{
if (!success)
{
thisContext.Abort();
}
}
}
}
}
| |
using GeoJSON.Net.Geometry;
using Newtonsoft.Json;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
namespace GeoJSON.Net.Tests.Feature
{
[TestFixture]
public class FeatureTests : TestBase
{
[Test]
public void Can_Deserialize_Point_Feature()
{
var json = GetExpectedJson();
var feature = JsonConvert.DeserializeObject<Net.Feature.Feature>(json);
Assert.IsNotNull(feature);
Assert.IsNotNull(feature.Properties);
Assert.IsTrue(feature.Properties.Any());
Assert.IsTrue(feature.Properties.ContainsKey("name"));
Assert.AreEqual(feature.Properties["name"], "Dinagat Islands");
Assert.AreEqual("test-id", feature.Id);
Assert.AreEqual(GeoJSONObjectType.Point, feature.Geometry.Type);
}
[Test]
public void Can_Serialize_LineString_Feature()
{
var coordinates = new[]
{
new List<IPosition>
{
new Position(52.370725881211314, 4.889259338378906),
new Position(52.3711451105601, 4.895267486572266),
new Position(52.36931095278263, 4.892091751098633),
new Position(52.370725881211314, 4.889259338378906)
},
new List<IPosition>
{
new Position(52.370725881211314, 4.989259338378906),
new Position(52.3711451105601, 4.995267486572266),
new Position(52.36931095278263, 4.992091751098633),
new Position(52.370725881211314, 4.989259338378906)
}
};
var geometry = new LineString(coordinates[0]);
var actualJson = JsonConvert.SerializeObject(new Net.Feature.Feature(geometry));
Console.WriteLine(actualJson);
var expectedJson = GetExpectedJson();
JsonAssert.AreEqual(expectedJson, actualJson);
}
[Test]
public void Can_Serialize_MultiLineString_Feature()
{
var geometry = new MultiLineString(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(52.370725881211314, 4.889259338378906),
new Position(52.3711451105601, 4.895267486572266),
new Position(52.36931095278263, 4.892091751098633),
new Position(52.370725881211314, 4.889259338378906)
}),
new LineString(new List<IPosition>
{
new Position(52.370725881211314, 4.989259338378906),
new Position(52.3711451105601, 4.995267486572266),
new Position(52.36931095278263, 4.992091751098633),
new Position(52.370725881211314, 4.989259338378906)
})
});
var expectedJson = GetExpectedJson();
var actualJson = JsonConvert.SerializeObject(new Net.Feature.Feature(geometry));
JsonAssert.AreEqual(expectedJson, actualJson);
}
[Test]
public void Can_Serialize_Point_Feature()
{
var geometry = new Point(new Position(1, 2));
var expectedJson = GetExpectedJson();
var actualJson = JsonConvert.SerializeObject(new Net.Feature.Feature(geometry));
JsonAssert.AreEqual(expectedJson, actualJson);
}
[Test]
public void Can_Serialize_Polygon_Feature()
{
var coordinates = new List<IPosition>
{
new Position(52.370725881211314, 4.889259338378906),
new Position(52.3711451105601, 4.895267486572266),
new Position(52.36931095278263, 4.892091751098633),
new Position(52.370725881211314, 4.889259338378906)
};
var polygon = new Polygon(new List<LineString> { new LineString(coordinates) });
var properties = new Dictionary<string, object> { { "Name", "Foo" } };
var feature = new Net.Feature.Feature(polygon, properties);
var expectedJson = GetExpectedJson();
var actualJson = JsonConvert.SerializeObject(feature);
JsonAssert.AreEqual(expectedJson, actualJson);
}
[Test]
public void Can_Serialize_MultiPolygon_Feature()
{
var multiPolygon = new MultiPolygon(new List<Polygon>
{
new Polygon(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(0, 0),
new Position(0, 1),
new Position(1, 1),
new Position(1, 0),
new Position(0, 0)
})
}),
new Polygon(new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(70, 70),
new Position(70, 71),
new Position(71, 71),
new Position(71, 70),
new Position(70, 70)
}),
new LineString(new List<IPosition>
{
new Position(80, 80),
new Position(80, 81),
new Position(81, 81),
new Position(81, 80),
new Position(80, 80)
})
})
});
var feature = new Net.Feature.Feature(multiPolygon);
var expectedJson = GetExpectedJson();
var actualJson = JsonConvert.SerializeObject(feature);
JsonAssert.AreEqual(expectedJson, actualJson);
}
[Test]
public void Can_Serialize_Dictionary_Subclass()
{
var properties =
new TestFeaturePropertyDictionary()
{
BooleanProperty = true,
DoubleProperty = 1.2345d,
EnumProperty = TestFeatureEnum.Value1,
IntProperty = -1,
StringProperty = "Hello, GeoJSON !"
};
Net.Feature.Feature feature = new Net.Feature.Feature(new Point(new Position(10, 10)), properties);
var expectedJson = this.GetExpectedJson();
var actualJson = JsonConvert.SerializeObject(feature);
Assert.False(string.IsNullOrEmpty(expectedJson));
JsonAssert.AreEqual(expectedJson, actualJson);
}
[Test]
public void Ctor_Can_Add_Properties_Using_Object()
{
var properties = new TestFeatureProperty
{
BooleanProperty = true,
DateTimeProperty = DateTime.Now,
DoubleProperty = 1.2345d,
EnumProperty = TestFeatureEnum.Value1,
IntProperty = -1,
StringProperty = "Hello, GeoJSON !"
};
Net.Feature.Feature feature = new Net.Feature.Feature(new Point(new Position(10, 10)), properties);
Assert.IsNotNull(feature.Properties);
Assert.IsTrue(feature.Properties.Count > 1);
Assert.AreEqual(feature.Properties.Count, 6);
}
[Test]
public void Ctor_Can_Add_Properties_Using_Object_Inheriting_Dictionary()
{
int expectedProperties = 6;
var properties = new TestFeaturePropertyDictionary()
{
BooleanProperty = true,
DateTimeProperty = DateTime.Now,
DoubleProperty = 1.2345d,
EnumProperty = TestFeatureEnum.Value1,
IntProperty = -1,
StringProperty = "Hello, GeoJSON !"
};
Net.Feature.Feature feature = new Net.Feature.Feature(new Point(new Position(10, 10)), properties);
Assert.IsNotNull(feature.Properties);
Assert.IsTrue(feature.Properties.Count > 1);
Assert.AreEqual(
feature.Properties.Count,
expectedProperties,
$"Expected: {expectedProperties} Actual: {feature.Properties.Count}");
}
[Test]
public void Ctor_Creates_Properties_Collection_When_Passed_Null_Proper_Object()
{
Net.Feature.Feature feature = new Net.Feature.Feature(new Point(new Position(10, 10)), (object)null);
Assert.IsNotNull(feature.Properties);
CollectionAssert.IsEmpty(feature.Properties);
}
[Test]
public void Feature_Equals_GetHashCode_Contract_Properties_Of_Objects()
{
// order of keys should not matter
var leftProp = new TestFeatureProperty
{
StringProperty = "Hello, GeoJSON !",
EnumProperty = TestFeatureEnum.Value1,
IntProperty = -1,
BooleanProperty = true,
DateTimeProperty = DateTime.Now,
DoubleProperty = 1.2345d
};
var left = new Net.Feature.Feature(new Point(new Position(10, 10)), leftProp);
var rightProp = new TestFeatureProperty
{
BooleanProperty = true,
DateTimeProperty = DateTime.Now,
DoubleProperty = 1.2345d,
EnumProperty = TestFeatureEnum.Value1,
IntProperty = -1,
StringProperty = "Hello, GeoJSON !"
};
var right = new Net.Feature.Feature(new Point(new Position(10, 10)), rightProp);
Assert_Are_Equal(left, right);
}
[Test]
public void Feature_Equals_GetHashCode_Contract_Dictionary()
{
var leftDictionary = GetPropertiesInRandomOrder();
var rightDictionary = GetPropertiesInRandomOrder();
var geometry10 = new Position(10, 10);
var geometry20 = new Position(20, 20);
var left = new Net.Feature.Feature(new Point(
geometry10),
leftDictionary,
"abc");
var right = new Net.Feature.Feature(new Point(
geometry20),
rightDictionary,
"abc");
Assert_Are_Not_Equal(left, right); // different geometries
left = new Net.Feature.Feature(new Point(
geometry10),
leftDictionary,
"abc");
right = new Net.Feature.Feature(new Point(
geometry10),
rightDictionary,
"abc"); // identical geometries, different ids and or properties or not compared
Assert_Are_Equal(left, right);
}
[Test]
public void Serialized_And_Deserialized_Feature_Equals_And_Share_HashCode()
{
var geometry = GetGeometry();
var leftFeature = new Net.Feature.Feature(geometry);
var leftJson = JsonConvert.SerializeObject(leftFeature);
var left = JsonConvert.DeserializeObject<Net.Feature.Feature>(leftJson);
var rightFeature = new Net.Feature.Feature(geometry);
var rightJson = JsonConvert.SerializeObject(rightFeature);
var right = JsonConvert.DeserializeObject<Net.Feature.Feature>(rightJson);
Assert_Are_Equal(left, right);
leftFeature = new Net.Feature.Feature(geometry, GetPropertiesInRandomOrder());
leftJson = JsonConvert.SerializeObject(leftFeature);
left = JsonConvert.DeserializeObject<Net.Feature.Feature>(leftJson);
rightFeature = new Net.Feature.Feature(geometry, GetPropertiesInRandomOrder());
rightJson = JsonConvert.SerializeObject(rightFeature);
right = JsonConvert.DeserializeObject<Net.Feature.Feature>(rightJson);
Assert_Are_Equal(left, right); // assert properties doesn't influence comparison and hashcode
leftFeature = new Net.Feature.Feature(geometry, null, "abc_abc");
leftJson = JsonConvert.SerializeObject(leftFeature);
left = JsonConvert.DeserializeObject<Net.Feature.Feature>(leftJson);
rightFeature = new Net.Feature.Feature(geometry, null, "xyz_XYZ");
rightJson = JsonConvert.SerializeObject(rightFeature);
right = JsonConvert.DeserializeObject<Net.Feature.Feature>(rightJson);
Assert_Are_Equal(left, right); // assert id's doesn't influence comparison and hashcode
leftFeature = new Net.Feature.Feature(geometry, GetPropertiesInRandomOrder(), "abc");
leftJson = JsonConvert.SerializeObject(leftFeature);
left = JsonConvert.DeserializeObject<Net.Feature.Feature>(leftJson);
rightFeature = new Net.Feature.Feature(geometry, GetPropertiesInRandomOrder(), "abc");
rightJson = JsonConvert.SerializeObject(rightFeature);
right = JsonConvert.DeserializeObject<Net.Feature.Feature>(rightJson);
Assert_Are_Equal(left, right); // assert id's + properties doesn't influence comparison and hashcode
}
[Test]
public void Feature_Equals_Null_Issue94()
{
bool equal1 = true;
bool equal2 = true;
var feature = new Net.Feature.Feature(new Point(new Position(12, 123)));
Assert.DoesNotThrow(() =>
{
equal1 = feature.Equals(null);
equal2 = feature == null;
});
Assert.IsFalse(equal1);
Assert.IsFalse(equal2);
}
[Test]
public void Feature_Null_Instance_Equals_Null_Issue94()
{
var equal1 = true;
Net.Feature.Feature feature = null;
Assert.DoesNotThrow(() =>
{
equal1 = feature != null;
});
Assert.IsFalse(equal1);
}
[Test]
public void Feature_Equals_Itself_Issue94()
{
bool equal1 = false;
bool equal2 = false;
var feature = new Net.Feature.Feature(new Point(new Position(12, 123)));
Assert.DoesNotThrow(() =>
{
equal1 = feature == feature;
equal2 = feature.Equals(feature);
});
Assert.IsTrue(equal1);
Assert.IsTrue(equal2);
}
[Test]
public void Feature_Equals_Geometry_Null_Issue115()
{
bool equal1 = false;
bool equal2 = false;
var feature1 = new Net.Feature.Feature(null);
var feature2 = new Net.Feature.Feature(new Point(new Position(12, 123)));
Assert.DoesNotThrow(() =>
{
equal1 = feature1 == feature2;
equal2 = feature1.Equals(feature2);
});
Assert.IsFalse(equal1);
Assert.IsFalse(equal2);
}
[Test]
public void Feature_Equals_Other_Geometry_Null_Issue115()
{
bool equal1 = false;
bool equal2 = false;
var feature1 = new Net.Feature.Feature(new Point(new Position(12, 123)));
var feature2 = new Net.Feature.Feature(null);
Assert.DoesNotThrow(() =>
{
equal1 = feature1 == feature2;
equal2 = feature1.Equals(feature2);
});
Assert.IsFalse(equal1);
Assert.IsFalse(equal2);
}
[Test]
public void Feature_Equals_All_Geometry_Null_Issue115()
{
bool equal1 = false;
bool equal2 = false;
var feature1 = new Net.Feature.Feature(null);
var feature2 = new Net.Feature.Feature(null);
Assert.DoesNotThrow(() =>
{
equal1 = feature1 == feature2;
equal2 = feature1.Equals(feature2);
});
Assert.IsTrue(equal1);
Assert.IsTrue(equal2);
}
private IGeometryObject GetGeometry()
{
var coordinates = new List<LineString>
{
new LineString(new List<IPosition>
{
new Position(52.370725881211314, 4.889259338378906),
new Position(52.3711451105601, 4.895267486572266),
new Position(52.36931095278263, 4.892091751098633),
new Position(52.370725881211314, 4.889259338378906)
}),
new LineString(new List<IPosition>
{
new Position(52.370725881211314, 4.989259338378906),
new Position(52.3711451105601, 4.995267486572266),
new Position(52.36931095278263, 4.992091751098633),
new Position(52.370725881211314, 4.989259338378906)
})
};
var multiLine = new MultiLineString(coordinates);
return multiLine;
}
public static IDictionary<string, object> GetPropertiesInRandomOrder()
{
var properties = new Dictionary<string, object>()
{
{ "DateTimeProperty", DateTime.Now },
{ "IntProperty", -1 },
{ "EnumProperty", TestFeatureEnum.Value1 },
{ "BooleanProperty", true },
{ "DoubleProperty", 1.2345d },
{ "StringProperty", "Hello, GeoJSON !" }
};
var randomlyOrdered = new Dictionary<string, object>();
var randomlyOrderedKeys = properties.Keys.Select(k => Guid.NewGuid() + k).OrderBy(k => k).ToList();
foreach (var key in randomlyOrderedKeys)
{
var theKey = key.Substring(36);
randomlyOrdered.Add(theKey, properties[theKey]);
}
return randomlyOrdered;
}
private void Assert_Are_Equal(Net.Feature.Feature left, Net.Feature.Feature right)
{
Assert.AreEqual(left, right);
Assert.IsTrue(left.Equals(right));
Assert.IsTrue(right.Equals(left));
Assert.IsTrue(left.Equals(left));
Assert.IsTrue(right.Equals(right));
Assert.IsTrue(left == right);
Assert.IsTrue(right == left);
Assert.IsFalse(left != right);
Assert.IsFalse(right != left);
Assert.AreEqual(left.GetHashCode(), right.GetHashCode());
}
private void Assert_Are_Not_Equal(Net.Feature.Feature left, Net.Feature.Feature right)
{
Assert.AreNotEqual(left, right);
Assert.IsFalse(left.Equals(right));
Assert.IsFalse(right.Equals(left));
Assert.IsFalse(left == right);
Assert.IsFalse(right == left);
Assert.IsTrue(left != right);
Assert.IsTrue(right != left);
Assert.AreNotEqual(left.GetHashCode(), right.GetHashCode());
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Management.Network
{
/// <summary>
/// The Windows Azure Network management API provides a RESTful set of web
/// services that interact with Windows Azure Networks service to manage
/// your network resrources. The API has entities that capture the
/// relationship between an end user and the Windows Azure Networks
/// service.
/// </summary>
public static partial class LocalNetworkGatewayOperationsExtensions
{
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Create or update Local
/// Network Gateway operation through Network resource provider.
/// </param>
/// <returns>
/// Response for PutLocalNetworkGateway Api servive call
/// </returns>
public static LocalNetworkGatewayPutResponse BeginCreateOrUpdating(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ILocalNetworkGatewayOperations)s).BeginCreateOrUpdatingAsync(resourceGroupName, localNetworkGatewayName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Create or update Local
/// Network Gateway operation through Network resource provider.
/// </param>
/// <returns>
/// Response for PutLocalNetworkGateway Api servive call
/// </returns>
public static Task<LocalNetworkGatewayPutResponse> BeginCreateOrUpdatingAsync(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters)
{
return operations.BeginCreateOrUpdatingAsync(resourceGroupName, localNetworkGatewayName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public static UpdateOperationResponse BeginDeleting(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ILocalNetworkGatewayOperations)s).BeginDeletingAsync(resourceGroupName, localNetworkGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <returns>
/// If the resource provide needs to return an error to any operation,
/// it should return the appropriate HTTP error code and a message
/// body as can be seen below.The message should be localized per the
/// Accept-Language header specified in the original request such
/// thatit could be directly be exposed to users
/// </returns>
public static Task<UpdateOperationResponse> BeginDeletingAsync(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return operations.BeginDeletingAsync(resourceGroupName, localNetworkGatewayName, CancellationToken.None);
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Create or update Local
/// Network Gateway operation through Network resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static AzureAsyncOperationResponse CreateOrUpdate(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ILocalNetworkGatewayOperations)s).CreateOrUpdateAsync(resourceGroupName, localNetworkGatewayName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Put LocalNetworkGateway operation creates/updates a local
/// network gateway in the specified resource group through Network
/// resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the Begin Create or update Local
/// Network Gateway operation through Network resource provider.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public static Task<AzureAsyncOperationResponse> CreateOrUpdateAsync(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName, LocalNetworkGateway parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, localNetworkGatewayName, parameters, CancellationToken.None);
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ILocalNetworkGatewayOperations)s).DeleteAsync(resourceGroupName, localNetworkGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Delete LocalNetworkGateway operation deletes the specifed local
/// network Gateway through Network resource provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return operations.DeleteAsync(resourceGroupName, localNetworkGatewayName, CancellationToken.None);
}
/// <summary>
/// The Get LocalNetworkGateway operation retrieves information about
/// the specified local network gateway through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <returns>
/// Response for GetLocalNetworkgateway Api servive call.
/// </returns>
public static LocalNetworkGatewayGetResponse Get(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ILocalNetworkGatewayOperations)s).GetAsync(resourceGroupName, localNetworkGatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get LocalNetworkGateway operation retrieves information about
/// the specified local network gateway through Network resource
/// provider.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='localNetworkGatewayName'>
/// Required. The name of the local network gateway.
/// </param>
/// <returns>
/// Response for GetLocalNetworkgateway Api servive call.
/// </returns>
public static Task<LocalNetworkGatewayGetResponse> GetAsync(this ILocalNetworkGatewayOperations operations, string resourceGroupName, string localNetworkGatewayName)
{
return operations.GetAsync(resourceGroupName, localNetworkGatewayName, CancellationToken.None);
}
/// <summary>
/// The List LocalNetworkGateways opertion retrieves all the local
/// network gateways stored.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <returns>
/// Response for ListLocalNetworkGateways Api service call
/// </returns>
public static LocalNetworkGatewayListResponse List(this ILocalNetworkGatewayOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ILocalNetworkGatewayOperations)s).ListAsync(resourceGroupName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The List LocalNetworkGateways opertion retrieves all the local
/// network gateways stored.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Network.ILocalNetworkGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <returns>
/// Response for ListLocalNetworkGateways Api service call
/// </returns>
public static Task<LocalNetworkGatewayListResponse> ListAsync(this ILocalNetworkGatewayOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName, CancellationToken.None);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Reflection;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Completion;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.CSharp.SplitStringLiteral;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.VisualStudio.LanguageServices.Implementation.Options;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
[ExportLanguageSpecificOptionSerializer(
LanguageNames.CSharp,
GenerationOptions.FeatureName,
SplitStringLiteralOptions.FeatureName,
AddImportOptions.FeatureName,
CompletionOptions.FeatureName,
CSharpCompletionOptions.FeatureName,
CSharpCodeStyleOptions.FeatureName,
CodeStyleOptions.PerLanguageCodeStyleOption,
SimplificationOptions.PerLanguageFeatureName,
ExtractMethodOptions.FeatureName,
CSharpFormattingOptions.IndentFeatureName,
CSharpFormattingOptions.NewLineFormattingFeatureName,
CSharpFormattingOptions.SpacingFeatureName,
CSharpFormattingOptions.WrappingFeatureName,
FormattingOptions.InternalTabFeatureName,
FeatureOnOffOptions.OptionName,
ServiceFeatureOnOffOptions.OptionName), Shared]
internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer
{
[ImportingConstructor]
public CSharpSettingsManagerOptionSerializer(VisualStudioWorkspaceImpl workspace)
: base(workspace)
{
}
private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators);
private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator);
private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels);
private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft);
private const string Style_QualifyFieldAccess = nameof(AutomationObject.Style_QualifyFieldAccess);
private const string Style_QualifyPropertyAccess = nameof(AutomationObject.Style_QualifyPropertyAccess);
private const string Style_QualifyMethodAccess = nameof(AutomationObject.Style_QualifyMethodAccess);
private const string Style_QualifyEventAccess = nameof(AutomationObject.Style_QualifyEventAccess);
private const string Style_UseImplicitTypeForIntrinsicTypes = nameof(AutomationObject.Style_UseImplicitTypeForIntrinsicTypes);
private const string Style_UseImplicitTypeWhereApparent = nameof(AutomationObject.Style_UseImplicitTypeWhereApparent);
private const string Style_UseImplicitTypeWherePossible = nameof(AutomationObject.Style_UseImplicitTypeWherePossible);
private const string Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration = nameof(AutomationObject.Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration);
private const string Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess = nameof(AutomationObject.Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess);
private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo)
{
var value = (IOption)fieldInfo.GetValue(obj: null);
return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value);
}
private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo)
{
return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null));
}
protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap()
{
var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder();
result.AddRange(new[]
{
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnDeletion), CompletionOptions.TriggerOnDeletion),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.ShowCompletionItemFilters), CompletionOptions.ShowCompletionItemFilters),
new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.HighlightMatchingPortionsOfCompletionListItems), CompletionOptions.HighlightMatchingPortionsOfCompletionListItems),
});
Type[] types = new[]
{
typeof(GenerationOptions),
typeof(AddImportOptions),
typeof(SplitStringLiteralOptions),
typeof(CSharpCompletionOptions),
typeof(SimplificationOptions),
typeof(CSharpCodeStyleOptions),
typeof(ExtractMethodOptions),
typeof(ServiceFeatureOnOffOptions),
typeof(CSharpFormattingOptions),
typeof(CodeStyleOptions)
};
var bindingFlags = BindingFlags.Public | BindingFlags.Static;
result.AddRange(GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo));
types = new[] { typeof(FeatureOnOffOptions) };
result.AddRange(GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption));
return result.ToImmutable();
}
protected override string LanguageName { get { return LanguageNames.CSharp; } }
protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } }
protected override string GetStorageKeyForOption(IOption option)
{
var name = option.Name;
if (option == ServiceFeatureOnOffOptions.ClosedFileDiagnostic)
{
// ClosedFileDiagnostics has been deprecated in favor of CSharpClosedFileDiagnostics.
// ClosedFileDiagnostics had a default value of 'true', while CSharpClosedFileDiagnostics has a default value of 'false'.
// We want to ensure that we don't fetch the setting store value for the old flag, as that can cause the default value for this option to change.
name = nameof(AutomationObject.CSharpClosedFileDiagnostics);
}
return SettingStorageRoot + name;
}
protected override bool SupportsOption(IOption option, string languageName)
{
if (option == GenerationOptions.PlaceSystemNamespaceFirst ||
option == AddImportOptions.SuggestForTypesInReferenceAssemblies ||
option == AddImportOptions.SuggestForTypesInNuGetPackages ||
option.Feature == CodeStyleOptions.PerLanguageCodeStyleOption ||
option.Feature == CSharpCodeStyleOptions.FeatureName ||
option.Feature == CSharpFormattingOptions.WrappingFeatureName ||
option.Feature == CSharpFormattingOptions.IndentFeatureName ||
option.Feature == CSharpFormattingOptions.SpacingFeatureName ||
option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName)
{
return true;
}
else if (languageName == LanguageNames.CSharp)
{
if (option == CompletionOptions.TriggerOnTypingLetters ||
option == CompletionOptions.TriggerOnDeletion ||
option == CompletionOptions.ShowCompletionItemFilters ||
option == CompletionOptions.HighlightMatchingPortionsOfCompletionListItems ||
option == CompletionOptions.EnterKeyBehavior ||
option == CompletionOptions.SnippetsBehavior ||
option.Feature == SimplificationOptions.PerLanguageFeatureName ||
option.Feature == ExtractMethodOptions.FeatureName ||
option.Feature == ServiceFeatureOnOffOptions.OptionName ||
option.Feature == FormattingOptions.InternalTabFeatureName)
{
return true;
}
else if (option.Feature == FeatureOnOffOptions.OptionName)
{
return SupportsOnOffOption(option);
}
}
return false;
}
private bool SupportsOnOffOption(IOption option)
{
return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace ||
option == FeatureOnOffOptions.AutoFormattingOnSemicolon ||
option == FeatureOnOffOptions.LineSeparator ||
option == FeatureOnOffOptions.Outlining ||
option == FeatureOnOffOptions.ReferenceHighlighting ||
option == FeatureOnOffOptions.KeywordHighlighting ||
option == FeatureOnOffOptions.FormatOnPaste ||
option == FeatureOnOffOptions.AutoXmlDocCommentGeneration ||
option == FeatureOnOffOptions.AutoInsertBlockCommentStartString ||
option == FeatureOnOffOptions.RefactoringVerification ||
option == FeatureOnOffOptions.RenameTracking ||
option == FeatureOnOffOptions.RenameTrackingPreview;
}
public override bool TryFetch(OptionKey optionKey, out object value)
{
value = null;
if (this.Manager == null)
{
Debug.Fail("Manager field is unexpectedly null.");
return false;
}
if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator)
{
// Remove space -> Space_AroundBinaryOperator = 0
// Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing
// Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1
object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0);
if (ignoreSpacesAroundBinaryObjectValue.Equals(1))
{
value = BinaryOperatorSpacingOptions.Ignore;
return true;
}
object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1);
if (spaceAroundBinaryOperatorObjectValue.Equals(0))
{
value = BinaryOperatorSpacingOptions.Remove;
return true;
}
value = BinaryOperatorSpacingOptions.Single;
return true;
}
if (optionKey.Option == CSharpFormattingOptions.LabelPositioning)
{
object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0);
if (flushLabelLeftObjectValue.Equals(1))
{
value = LabelPositionOptions.LeftMost;
return true;
}
object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1);
if (unindentLabelsObjectValue.Equals(0))
{
value = LabelPositionOptions.NoIndent;
return true;
}
value = LabelPositionOptions.OneLess;
return true;
}
// code style: use this.
if (optionKey.Option == CodeStyleOptions.QualifyFieldAccess)
{
return FetchStyleBool(Style_QualifyFieldAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyPropertyAccess)
{
return FetchStyleBool(Style_QualifyPropertyAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyMethodAccess)
{
return FetchStyleBool(Style_QualifyMethodAccess, out value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyEventAccess)
{
return FetchStyleBool(Style_QualifyEventAccess, out value);
}
// code style: use var options.
if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes)
{
return FetchStyleBool(Style_UseImplicitTypeForIntrinsicTypes, out value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWhereApparent)
{
return FetchStyleBool(Style_UseImplicitTypeWhereApparent, out value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWherePossible)
{
return FetchStyleBool(Style_UseImplicitTypeWherePossible, out value);
}
// code style: intrinsic/framework type.
if (optionKey.Option == CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
{
return FetchStyleBool(Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration, out value);
}
else if (optionKey.Option == CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)
{
return FetchStyleBool(Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess, out value);
}
if (optionKey.Option == CompletionOptions.EnterKeyBehavior)
{
return FetchEnterKeyBehavior(optionKey, out value);
}
if (optionKey.Option == CompletionOptions.SnippetsBehavior)
{
return FetchSnippetsBehavior(optionKey, out value);
}
if (optionKey.Option == CompletionOptions.TriggerOnDeletion)
{
return FetchTriggerOnDeletion(optionKey, out value);
}
return base.TryFetch(optionKey, out value);
}
private bool FetchTriggerOnDeletion(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (value == null)
{
// The default behavior for c# is to not trigger completion on deletion.
value = (bool?)false;
}
return true;
}
private bool FetchStyleBool(string settingName, out object value)
{
var typeStyleValue = Manager.GetValueOrDefault<string>(settingName);
return FetchStyleOption<bool>(typeStyleValue, out value);
}
/// <summary>
/// The EnterKeyBehavior option (formerly AddNewLineOnEnterAfterFullyTypedWord) used to only exist in C# and as a boolean.
/// We need to maintain the meaning of the serialized legacy setting.
/// </summary>
private bool FetchSnippetsBehavior(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (!value.Equals(SnippetsRule.Default))
{
return true;
}
// if the SnippetsBehavior setting cannot be loaded, then attempt to load and upgrade the legacy setting
#pragma warning disable CS0618 // IncludeSnippets is obsolete
if (base.TryFetch(CSharpCompletionOptions.IncludeSnippets, out value))
#pragma warning restore CS0618
{
if ((bool)value)
{
value = SnippetsRule.AlwaysInclude;
}
else
{
value = SnippetsRule.NeverInclude;
}
return true;
}
value = SnippetsRule.AlwaysInclude;
return true;
}
/// <summary>
/// The EnterKeyBehavior option (formerly AddNewLineOnEnterAfterFullyTypedWord) used to only exist in C# and as a boolean.
/// We need to maintain the meaning of the serialized legacy setting.
/// </summary>
private bool FetchEnterKeyBehavior(OptionKey optionKey, out object value)
{
if (!base.TryFetch(optionKey, out value))
{
return false;
}
if (!value.Equals(EnterKeyRule.Default))
{
return true;
}
// if the EnterKeyBehavior setting cannot be loaded, then attempt to load and upgrade the legacy AddNewLineOnEnterAfterFullyTypedWord setting
#pragma warning disable CS0618 // AddNewLineOnEnterAfterFullyTypedWord is obsolete
if (base.TryFetch(CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord, out value))
#pragma warning restore CS0618
{
int intValue = (int)value;
switch (intValue)
{
case 1:
value = EnterKeyRule.AfterFullyTypedWord;
break;
case 0:
default:
value = EnterKeyRule.Never;
break;
}
return true;
}
value = EnterKeyRule.Never;
return true;
}
public override bool TryPersist(OptionKey optionKey, object value)
{
if (this.Manager == null)
{
Debug.Fail("Manager field is unexpectedly null.");
return false;
}
if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator)
{
// Remove space -> Space_AroundBinaryOperator = 0
// Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing
// Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1
switch ((BinaryOperatorSpacingOptions)value)
{
case BinaryOperatorSpacingOptions.Remove:
{
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false);
return true;
}
case BinaryOperatorSpacingOptions.Ignore:
{
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false);
return true;
}
case BinaryOperatorSpacingOptions.Single:
{
this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false);
return true;
}
}
}
else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning)
{
switch ((LabelPositionOptions)value)
{
case LabelPositionOptions.LeftMost:
{
this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false);
this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false);
return true;
}
case LabelPositionOptions.NoIndent:
{
this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false);
return true;
}
case LabelPositionOptions.OneLess:
{
this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false);
this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false);
return true;
}
}
}
// code style: use this.
if (optionKey.Option == CodeStyleOptions.QualifyFieldAccess)
{
return PersistStyleOption<bool>(Style_QualifyFieldAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyPropertyAccess)
{
return PersistStyleOption<bool>(Style_QualifyPropertyAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyMethodAccess)
{
return PersistStyleOption<bool>(Style_QualifyMethodAccess, value);
}
else if (optionKey.Option == CodeStyleOptions.QualifyEventAccess)
{
return PersistStyleOption<bool>(Style_QualifyEventAccess, value);
}
// code style: use var options.
if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeForIntrinsicTypes, value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWhereApparent)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeWhereApparent, value);
}
else if (optionKey.Option == CSharpCodeStyleOptions.UseImplicitTypeWherePossible)
{
return PersistStyleOption<bool>(Style_UseImplicitTypeWherePossible, value);
}
// code style: intrinsic/framework type.
if (optionKey.Option == CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
{
return PersistStyleOption<bool>(Style_PreferIntrinsicPredefinedTypeKeywordInDeclaration, value);
}
else if (optionKey.Option == CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess)
{
return PersistStyleOption<bool>(Style_PreferIntrinsicPredefinedTypeKeywordInMemberAccess, value);
}
return base.TryPersist(optionKey, value);
}
private bool PersistStyleOption<T>(string option, object value)
{
var serializedValue = ((CodeStyleOption<T>)value).ToXElement().ToString();
this.Manager.SetValueAsync(option, value: serializedValue, isMachineLocal: false);
return true;
}
private static bool FetchStyleOption<T>(string typeStyleOptionValue, out object value)
{
if (string.IsNullOrEmpty(typeStyleOptionValue))
{
value = CodeStyleOption<T>.Default;
}
else
{
value = CodeStyleOption<T>.FromXElement(XElement.Parse(typeStyleOptionValue));
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Events;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServer4Admin.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace IdentityServer4.Quickstart.UI
{
[SecurityHeaders]
[AllowAnonymous]
public class ExternalController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IEventService _events;
private readonly ILogger<ExternalController> _logger;
public ExternalController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IEventService events,
ILogger<ExternalController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_interaction = interaction;
_clientStore = clientStore;
_events = events;
_logger = logger;
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
[HttpGet]
public async Task<IActionResult> Challenge(string provider, string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/";
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
if (AccountOptions.WindowsAuthenticationSchemeName == provider)
{
// windows authentication needs special handling
return await ProcessWindowsLoginAsync(returnUrl);
}
else
{
// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", provider },
}
};
return Challenge(props, provider);
}
}
/// <summary>
/// Post processing of external authentication
/// </summary>
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
if (_logger.IsEnabled(LogLevel.Debug))
{
var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}");
_logger.LogDebug("External claims: {@claims}", externalClaims);
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUserAsync(provider, providerUserId, claims);
}
// this allows us to collect any additonal claims or properties
// for the specific prtotocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
// we must issue the cookie maually, and can't use the SignInManager because
// it doesn't expose an API to issue additional claims from the login workflow
var principal = await _signInManager.CreateUserPrincipalAsync(user);
additionalLocalClaims.AddRange(principal.Claims);
var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id;
await HttpContext.SignInAsync(user.Id, name, provider, localSignInProps, additionalLocalClaims.ToArray());
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// retrieve return URL
var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";
// check if external login is in the context of an OIDC request
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, name, true, context?.ClientId));
if (context != null)
{
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl });
}
}
return Redirect(returnUrl);
}
private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
// see if windows auth has already been requested and succeeded
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
// we will issue the external cookie and then redirect the
// user back to the external callback, in essence, treating windows
// auth the same as any other external authentication mechanism
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("Callback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName },
}
};
var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.FindFirst(ClaimTypes.PrimarySid).Value));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
// add the groups as claims -- be careful if the number of groups is too large
if (AccountOptions.IncludeWindowsGroups)
{
var wi = wp.Identity as WindowsIdentity;
var groups = wi.Groups.Translate(typeof(NTAccount));
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
id.AddClaims(roles);
}
await HttpContext.SignInAsync(
IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
// trigger windows auth
// since windows auth don't support the redirect uri,
// this URL is re-triggered when we call challenge
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
private async Task<(ApplicationUser user, string provider, string providerUserId, IEnumerable<Claim> claims)>
FindUserFromExternalProviderAsync(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
var user = await _userManager.FindByLoginAsync(provider, providerUserId);
return (user, provider, providerUserId, claims);
}
private async Task<ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable<Claim> claims)
{
// create a list of claims that we want to transfer into our store
var filtered = new List<Claim>();
// user's display name
var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
if (name != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, name));
}
else
{
var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
if (first != null && last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
}
else if (first != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first));
}
else if (last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, last));
}
}
// email
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null)
{
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
var user = new ApplicationUser
{
UserName = Guid.NewGuid().ToString(),
};
var identityResult = await _userManager.CreateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
if (filtered.Any())
{
identityResult = await _userManager.AddClaimsAsync(user, filtered);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
return user;
}
private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var id_token = externalResult.Properties.GetTokenValue("id_token");
if (id_token != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
}
private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
}
}
| |
// $begin{copyright}
//
// This file is part of WebSharper
//
// Copyright (c) 2008-2018 IntelliFactory
//
// 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.
//
// $end{copyright}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FSharp.Core;
using WebSharper.Testing;
using System.Threading.Tasks;
using System.Threading;
using WebSharper.Web;
using static WebSharper.JavaScript.Pervasives;
namespace WebSharper.CSharp.Tests
{
[JavaScript]
public struct TestStruct
{
public int X;
public int Y;
public TestStruct (int x, int y)
{
this.X = x;
this.Y = y;
}
}
[JavaScript]
public class TestClass
{
public int X = 0;
public int Y { get; set; }
}
[JavaScript]
public class TestClassSub : TestClass
{
}
public static class Server
{
[Remote]
public static Task<int> GetOneAsync()
{
return Task.FromResult(1);
}
[Remote]
public static Task<int> FailOnServer()
{
return Task.FromException<int>(new Exception("Deliberately failing for testing."));
}
[Remote]
public static Task<int> AddOneAsync(int x)
{
return Task.FromResult(x + 1);
}
[Remote]
public static Task<(int, int)> AddOnesAsync((int, int) t)
{
var (x, y) = t;
return Task.FromResult((x + 1, y + 1));
}
private static Dictionary<int, int> values = new Dictionary<int, int>();
[Remote]
public static void Void() { }
[Remote]
public static void Set(int key, int value)
{
values[key] = value;
}
[Remote]
public static Task SetAsync(int key, int value)
{
Set(key, value);
return Task.FromResult<object>(null); // .NET 4.6 has Task.CompletedTask;
}
[Remote]
public static Task<int> Extract(int key)
{
Thread.Sleep(1000); // to wait out a call to void Set();
int value = -1;
values.TryGetValue(key, out value);
values.Remove(key);
return Task.FromResult(value);
}
[Remote]
public static async Task Login(string user)
{
var ctx = WebSharper.Web.Remoting.GetContext();
await ctx.UserSession.LoginUserAsync(user);
}
[Remote]
public static async Task<string> GetUser()
{
var ctx = WebSharper.Web.Remoting.GetContext();
return await ctx.UserSession.GetLoggedInUserAsync();
}
[Remote]
public static async Task Logout()
{
var ctx = WebSharper.Web.Remoting.GetContext();
await ctx.UserSession.LogoutAsync();
}
[Remote]
public static Task<TestClass> IncrementXY(TestClass o)
{
o.X++;
o.Y++;
return Task.FromResult(o);
}
[Remote]
public static Task<TestClassSub> IncrementXYSub(TestClassSub o)
{
o.X++;
o.Y++;
return Task.FromResult(o);
}
[Remote]
public static Task<TestStruct> IncrementXYStruct(TestStruct o)
{
return Task.FromResult(new TestStruct(o.X + 1, o.Y + 1));
}
public static int Zero()
{
return 0;
}
static Server()
{
WebSharper.Core.Remoting.AddHandler(typeof(Handler), new HandlerImpl());
}
}
public abstract class Handler
{
[Remote]
public abstract Task<int> Increment(int x);
[Remote]
public abstract Task Reset();
}
public class HandlerImpl : Handler
{
private static int counter = 0;
public override Task<int> Increment(int x)
{
counter += x;
return Task.FromResult(counter);
}
public override Task Reset()
{
counter = 0;
return Task.FromResult(0);
}
}
[JavaScript, Test("Task based remoting")]
public class Remoting : TestCategory
{
public static bool ShouldRun { get; set; } = true;
public int GetSync() => 3;
[Test]
public async Task SimpleAsync()
{
if (!ShouldRun) { Expect(0); return; }
var r = await Server.GetOneAsync();
Equal(r, 1);
}
[Test]
public async Task SimpleAsyncWith1Arg()
{
if (!ShouldRun) { Expect(0); return; }
var r = await Server.AddOneAsync(1783);
Equal(r, 1784);
}
[Test]
public async Task WithValueTuple()
{
if (!ShouldRun) { Expect(0); return; }
var r = await Server.AddOnesAsync((1783, 456));
Equal(r, (1784, 457));
}
[Test]
public void SimpleVoid()
{
if (!ShouldRun) { Expect(0); return; }
Server.Void();
IsTrue(true);
}
[Test]
public async Task VoidAndCheckReturn()
{
if (!ShouldRun) { Expect(0); return; }
var k = (int)(JavaScript.Math.Round(JavaScript.Math.Random() * 100));
var v = (int)(JavaScript.Math.Round(JavaScript.Math.Random() * 100));
Server.Set(k, v);
var v2 = await Server.Extract(k);
Equal(v, v2);
}
[Test]
public async Task VoidTaskAndCheckReturn()
{
if (!ShouldRun) { Expect(0); return; }
var k = (int)(JavaScript.Math.Round(JavaScript.Math.Random() * 100));
var v = (int)(JavaScript.Math.Round(JavaScript.Math.Random() * 100));
await Server.SetAsync(k, v);
var v2 = await Server.Extract(k);
Equal(v, v2);
}
[Test]
public async Task UserSession()
{
if (!ShouldRun) { Expect(0); return; }
Equal(await Server.GetUser(), null, "No logged in user");
await Server.Login("testuser");
Equal(await Server.GetUser(), "testuser", "Get logged in user");
await Server.Logout();
Equal(await Server.GetUser(), null, "Logout");
}
[Test]
public async Task CustomHandler()
{
if (!ShouldRun) { Expect(0); return; }
await Remote<Handler>().Reset();
Equal(await Remote<Handler>().Increment(5), 5);
Equal(await Remote<Handler>().Increment(5), 10);
}
[Test]
public async Task CustomClass()
{
if (!ShouldRun) { Expect(0); return; }
var o = new TestClass();
o.X = 1;
o.Y = 1;
o = await Server.IncrementXY(o);
Equal(o.X, 2);
Equal(o.Y, 2);
}
[Test]
public async Task CustomSubClass()
{
if (!ShouldRun) { Expect(0); return; }
var o = new TestClassSub();
o.X = 1;
o.Y = 1;
o = await Server.IncrementXYSub(o);
Equal(o.X, 2);
Equal(o.Y, 2);
}
[Test]
public async Task CustomStruct()
{
if (!ShouldRun) { Expect(0); return; }
var o = new TestStruct(1, 1);
o = await Server.IncrementXYStruct(o);
Equal(o.X, 2);
Equal(o.Y, 2);
}
[Test]
public void IsClientTest()
{
if (WebSharper.Pervasives.IsClient)
{
if (!WebSharper.Pervasives.IsClient)
{
Server.Zero();
}
else
{
Equal(1, 1, "IsClient in if statement");
}
}
else
{
Server.Zero();
}
var ok =
WebSharper.Pervasives.IsClient ?
(!WebSharper.Pervasives.IsClient ? Server.Zero() : 1)
: Server.Zero();
Equal(ok, 1, "IsClient in conditional expression");
}
static public async Task<int> AddOneAsyncSafe(int x)
{
try
{
return await Server.AddOneAsync(x);
}
catch (Exception)
{
Console.WriteLine("Unexpected server error");
throw;
}
}
static public async Task<int> TestServerFailure()
{
try
{
return await Server.FailOnServer();
}
catch (Exception)
{
Console.WriteLine("Successfully caught exception in C# async");
throw;
}
}
[Test]
public async Task AsyncTryCatch()
{
if (!ShouldRun) { Expect(0); return; }
var r = await AddOneAsyncSafe(1783);
Equal(r, 1784);
r = 0;
try
{
await TestServerFailure();
}
catch (Exception)
{
r = 1;
}
Equal(r, 1);
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* 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.Xml;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using Reporting.Rdl.Utility;
namespace Reporting.Rdl
{
///<summary>
///CustomReportItem describes a report item that is not natively defined in RDL. The
/// RdlEngineConfig.xml file (loaded by RdlEngineConfig.cs) contains a list of the
/// extensions. RdlCri.dll is a code module that contains the built-in CustomReportItems.
/// However, the runtime dynamically loads this so RdlCrl.dll is not required for the
/// report engine to function properly.
///</summary>
[Serializable]
internal class CustomReportItem : Rectangle
{
static readonly ImageFormat IMAGEFORMAT = ImageFormat.Jpeg;
string _Type; // The type of the custom report item. Interpreted by a
// report design tool or server.
System.Collections.Generic.List<CustomProperty> _Properties;
internal CustomReportItem(ReportDefn r, ReportLink p, XmlNode xNode):base(r, p, xNode, false)
{
_Type=null;
ReportItems ris=null;
bool bVersion2 = true;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Type":
_Type = xNodeLoop.InnerText;
break;
case "ReportItems": // Version 1 of the specification
ris = new ReportItems(r, this, xNodeLoop);
bVersion2 = false;
break;
case "AltReportItem": // Verstion 2 of the specification
ris = new ReportItems(r, this, xNodeLoop);
break;
case "CustomProperties":
_Properties = CustomProperties(xNodeLoop);
break;
default:
if (ReportItemElement(xNodeLoop)) // try at ReportItem level
break;
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown CustomReportItem element " + xNodeLoop.Name + " ignored.");
break;
}
}
ReportItems = ris;
if (bVersion2 && ris != null)
{
if (ris.Items.Count != 1)
OwnerReport.rl.LogError(8, "Only one element is allowed within an AltReportItem.");
}
if (_Type == null)
OwnerReport.rl.LogError(8, "CustomReportItem requires the Type element.");
}
override internal void FinalPass()
{
base.FinalPass(); // this handles the finalpass of the AltReportItems
// Handle the final pass for the Custom Properties
if (_Properties != null)
{
foreach (CustomProperty cp in _Properties)
{
cp.Name.FinalPass();
cp.Value.FinalPass();
}
}
// Find out whether the type is known
ICustomReportItem cri = null;
try
{
cri = RdlEngineConfig.CreateCustomReportItem(_Type);
}
catch (Exception ex)
{ // Not an error since we'll simply use the ReportItems
OwnerReport.rl.LogError(4, string.Format("CustomReportItem load of {0} failed: {1}",
_Type, ex.Message));
}
finally
{
if (cri != null)
cri.Dispose();
}
return;
}
override internal void Run(IPresent ip, Row row)
{
Report rpt = ip.Report();
ICustomReportItem cri = null;
try
{
cri = RdlEngineConfig.CreateCustomReportItem(_Type);
}
catch (Exception ex)
{
rpt.rl.LogError(8, string.Format("Exception in CustomReportItem handling.\n{0}\n{1}", ex.Message, ex.StackTrace));
}
finally
{
if (cri != null)
cri.Dispose();
}
return;
}
override internal void RunPage(Pages pgs, Row row)
{
Report rpt = pgs.Report;
if (IsHidden(pgs.Report, row))
return;
SetPagePositionBegin(pgs);
// Build the Chart bitmap, along with data regions
Page p = pgs.CurrentPage;
ICustomReportItem cri = null;
Bitmap bm = null;
try
{
cri = RdlEngineConfig.CreateCustomReportItem(_Type);
SetProperties(pgs.Report, row, cri);
int width = WidthCalc(rpt, pgs.G) -
(Style == null? 0 :
(Style.EvalPaddingLeftPx(rpt, row) + Style.EvalPaddingRightPx(rpt, row)));
int height = Measurement.PixelsFromPoints(this.HeightOrOwnerHeight, Measurement.STANDARD_DPI_Y) -
(Style == null? 0 :
(Style.EvalPaddingTopPx(rpt, row) + Style.EvalPaddingBottomPx(rpt, row)));
bm = new Bitmap(width, height);
cri.DrawImage(bm);
MemoryStream ostrm = new MemoryStream();
// 06122007AJM Changed to use high quality JPEG encoding
//bm.Save(ostrm, IMAGEFORMAT); // generate a jpeg TODO: get png to work with pdf
System.Drawing.Imaging.ImageCodecInfo[] info;
info = ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
// 20022008 AJM GJL - Using centralised image quality
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, ImageQualityManager.CustomImageQuality);
System.Drawing.Imaging.ImageCodecInfo codec = null;
for (int i = 0; i < info.Length; i++)
{
if (info[i].FormatDescription == "JPEG")
{
codec = info[i];
break;
}
}
bm.Save(ostrm, codec, encoderParameters);
byte[] ba = ostrm.ToArray();
ostrm.Close();
PageImage pi = new PageImage(IMAGEFORMAT, ba, width, height); // Create an image
pi.Sizing = ImageSizingEnum.Clip;
// RunPageRegionBegin(pgs);
SetPagePositionAndStyle(rpt, pi, row);
if (pgs.CurrentPage.YOffset + pi.Y + pi.H >= pgs.BottomOfPage && !pgs.CurrentPage.IsEmpty())
{ // force page break if it doesn't fit on the page
pgs.NextOrNew();
pgs.CurrentPage.YOffset = OwnerReport.TopOfPage;
if (this.YParents != null)
pi.Y = 0;
}
p = pgs.CurrentPage;
p.AddObject(pi); // Put image onto the current page
// RunPageRegionEnd(pgs);
if (!this.PageBreakAtEnd && !IsTableOrMatrixCell(rpt))
{
float newY = pi.Y + pi.H;
p.YOffset += newY; // bump the y location
}
SetPagePositionEnd(pgs, pi.Y + pi.H);
}
catch (Exception ex)
{
rpt.rl.LogError(8, string.Format("Exception in CustomReportItem handling: {0}", ex.Message));
}
finally
{
if (cri != null)
cri.Dispose();
}
return;
}
void SetProperties(Report rpt, Row row, ICustomReportItem cri)
{
if (_Properties == null || _Properties.Count == 0) // Any properties specified?
return;
System.Collections.Generic.Dictionary<string, object> dict =
new Dictionary<string, object>(_Properties.Count);
foreach (CustomProperty cp in _Properties)
{
string name = cp.Name.EvaluateString(rpt, row);
object val = cp.Value.Evaluate(rpt, row);
try { dict.Add(name, val); }
catch
{
rpt.rl.LogError(4, string.Format("Property {0} has already been set. New value {1} ignored.", name, val));
}
}
cri.SetProperties(dict);
}
internal string Type
{
get { return _Type; }
set { _Type = value; }
}
List<CustomProperty> CustomProperties(XmlNode xNode)
{
if (!xNode.HasChildNodes)
return null;
List<CustomProperty> cps = new List<CustomProperty>(xNode.ChildNodes.Count);
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
switch (xNodeLoop.Name)
{
case "CustomProperty":
CustomProperty cp = CustomProperty(xNodeLoop);
if (cp != null)
cps.Add(cp);
break;
default:
OwnerReport.rl.LogError(4, "Unknown CustomProperties element " + xNodeLoop.Name + " ignored.");
break;
}
}
return cps;
}
CustomProperty CustomProperty(XmlNode xNode)
{
Expression name=null;
Expression val=null;
CustomProperty cp = null;
foreach (XmlNode xNodeLoop in xNode.ChildNodes)
{
switch (xNodeLoop.Name)
{
case "Name":
name = new Expression(OwnerReport, this, xNodeLoop, ExpressionType.String);
break;
case "Value":
val = new Expression(OwnerReport, this, xNodeLoop, ExpressionType.Variant);
break;
default:
OwnerReport.rl.LogError(4, "Unknown CustomProperty element " + xNodeLoop.Name + " ignored.");
break;
}
}
if (name == null || val == null)
OwnerReport.rl.LogError(8, "CustomProperty requires the Name and Value element.");
else
{
cp = new CustomProperty(name, val);
}
return cp;
}
}
class CustomProperty
{
Expression _Name; // name of the property
Expression _Value; // value of the property
internal CustomProperty(Expression name, Expression val)
{
_Name = name;
_Value = val;
}
internal Expression Name
{
get { return _Name; }
}
internal Expression Value
{
get { return _Value; }
}
}
}
| |
// ==========================================================================
// This software is subject to the provisions of the Zope Public License,
// Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
// WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
// FOR A PARTICULAR PURPOSE.
// ==========================================================================
using System;
using System.Reflection;
namespace Python.Runtime {
/// <summary>
/// Managed class that provides the implementation for reflected types.
/// Managed classes and value types are represented in Python by actual
/// Python type objects. Each of those type objects is associated with
/// an instance of ClassObject, which provides its implementation.
/// </summary>
internal class ClassObject : ClassBase {
internal ConstructorBinder binder;
internal ConstructorInfo[] ctors;
internal ClassObject(Type tp) : base(tp) {
ctors = type.GetConstructors();
binder = new ConstructorBinder();
for (int i = 0; i < ctors.Length; i++) {
binder.AddMethod(ctors[i]);
}
}
//====================================================================
// Helper to get docstring from reflected constructor info.
//====================================================================
internal IntPtr GetDocString() {
MethodBase[] methods = binder.GetMethods();
string str = "";
for (int i = 0; i < methods.Length; i++) {
if (str.Length > 0)
str += Environment.NewLine;
str += methods[i].ToString();
}
return Runtime.PyString_FromString(str);
}
//====================================================================
// Implements __new__ for reflected classes and value types.
//====================================================================
public static IntPtr tp_new(IntPtr tp, IntPtr args, IntPtr kw) {
ClassObject self = GetManagedObject(tp) as ClassObject;
// Sanity check: this ensures a graceful error if someone does
// something intentially wrong like use the managed metatype for
// a class that is not really derived from a managed class.
if (self == null) {
return Exceptions.RaiseTypeError("invalid object");
}
Type type = self.type;
// Primitive types do not have constructors, but they look like
// they do from Python. If the ClassObject represents one of the
// convertible primitive types, just convert the arg directly.
if (type.IsPrimitive || type == typeof(String)) {
if (Runtime.PyTuple_Size(args) != 1) {
Exceptions.SetError(Exceptions.TypeError,
"no constructors match given arguments"
);
return IntPtr.Zero;
}
IntPtr op = Runtime.PyTuple_GetItem(args, 0);
Object result;
if (!Converter.ToManaged(op, type, out result, true)) {
return IntPtr.Zero;
}
return CLRObject.GetInstHandle(result, tp);
}
if (type.IsAbstract) {
Exceptions.SetError(Exceptions.TypeError,
"cannot instantiate abstract class"
);
return IntPtr.Zero;
}
if (type.IsEnum) {
Exceptions.SetError(Exceptions.TypeError,
"cannot instantiate enumeration"
);
return IntPtr.Zero;
}
Object obj = self.binder.InvokeRaw(IntPtr.Zero, args, kw);
if (obj == null) {
return IntPtr.Zero;
}
return CLRObject.GetInstHandle(obj, tp);
}
//====================================================================
// Implementation of [] semantics for reflected types. This exists
// both to implement the Array[int] syntax for creating arrays and
// to support generic name overload resolution using [].
//====================================================================
public override IntPtr type_subscript(IntPtr idx) {
// If this type is the Array type, the [<type>] means we need to
// construct and return an array type of the given element type.
if ((this.type) == typeof(Array)) {
if (Runtime.PyTuple_Check(idx)) {
return Exceptions.RaiseTypeError("type expected");
}
ClassBase c = GetManagedObject(idx) as ClassBase;
Type t = (c != null) ? c.type : Converter.GetTypeByAlias(idx);
if (t == null) {
return Exceptions.RaiseTypeError("type expected");
}
Type a = t.MakeArrayType();
ClassBase o = ClassManager.GetClass(a);
Runtime.Incref(o.pyHandle);
return o.pyHandle;
}
// If there are generics in our namespace with the same base name
// as the current type, then [<type>] means the caller wants to
// bind the generic type matching the given type parameters.
Type[] types = Runtime.PythonArgsToTypeArray(idx);
if (types == null) {
return Exceptions.RaiseTypeError("type(s) expected");
}
string gname = this.type.FullName + "`" + types.Length.ToString();
Type gtype = AssemblyManager.LookupType(gname);
if (gtype != null) {
GenericType g = ClassManager.GetClass(gtype) as GenericType;
return g.type_subscript(idx);
/*Runtime.Incref(g.pyHandle);
return g.pyHandle;*/
}
return Exceptions.RaiseTypeError("unsubscriptable object");
}
//====================================================================
// Implements __getitem__ for reflected classes and value types.
//====================================================================
public static IntPtr mp_subscript(IntPtr ob, IntPtr idx) {
//ManagedType self = GetManagedObject(ob);
IntPtr tp = Runtime.PyObject_TYPE(ob);
ClassBase cls = (ClassBase)GetManagedObject(tp);
if (cls.indexer == null || !cls.indexer.CanGet) {
Exceptions.SetError(Exceptions.TypeError,
"unindexable object"
);
return IntPtr.Zero;
}
// Arg may be a tuple in the case of an indexer with multiple
// parameters. If so, use it directly, else make a new tuple
// with the index arg (method binders expect arg tuples).
IntPtr args = idx;
bool free = false;
if (!Runtime.PyTuple_Check(idx)) {
args = Runtime.PyTuple_New(1);
Runtime.Incref(idx);
Runtime.PyTuple_SetItem(args, 0, idx);
free = true;
}
IntPtr value = IntPtr.Zero;
try {
value = cls.indexer.GetItem(ob, args);
}
finally {
if (free) {
Runtime.Decref(args);
}
}
return value;
}
//====================================================================
// Implements __setitem__ for reflected classes and value types.
//====================================================================
public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v) {
//ManagedType self = GetManagedObject(ob);
IntPtr tp = Runtime.PyObject_TYPE(ob);
ClassBase cls = (ClassBase)GetManagedObject(tp);
if (cls.indexer == null || !cls.indexer.CanSet) {
Exceptions.SetError(Exceptions.TypeError,
"object doesn't support item assignment"
);
return -1;
}
// Arg may be a tuple in the case of an indexer with multiple
// parameters. If so, use it directly, else make a new tuple
// with the index arg (method binders expect arg tuples).
IntPtr args = idx;
bool free = false;
if (!Runtime.PyTuple_Check(idx)) {
args = Runtime.PyTuple_New(1);
Runtime.Incref(idx);
Runtime.PyTuple_SetItem(args, 0, idx);
free = true;
}
int i = Runtime.PyTuple_Size(args);
IntPtr real = Runtime.PyTuple_New(i + 1);
for (int n = 0; n < i; n++) {
IntPtr item = Runtime.PyTuple_GetItem(args, n);
Runtime.Incref(item);
Runtime.PyTuple_SetItem(real, n, item);
}
Runtime.Incref(v);
Runtime.PyTuple_SetItem(real, i, v);
try {
cls.indexer.SetItem(ob, real);
}
finally {
Runtime.Decref(real);
if (free) {
Runtime.Decref(args);
}
}
if (Exceptions.ErrorOccurred()) {
return -1;
}
return 0;
}
//====================================================================
// This is a hack. Generally, no managed class is considered callable
// from Python - with the exception of System.Delegate. It is useful
// to be able to call a System.Delegate instance directly, especially
// when working with multicast delegates.
//====================================================================
public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) {
//ManagedType self = GetManagedObject(ob);
IntPtr tp = Runtime.PyObject_TYPE(ob);
ClassBase cb = (ClassBase)GetManagedObject(tp);
if (cb.type != typeof(System.Delegate)) {
Exceptions.SetError(Exceptions.TypeError,
"object is not callable");
return IntPtr.Zero;
}
CLRObject co = (CLRObject)ManagedType.GetManagedObject(ob);
Delegate d = co.inst as Delegate;
BindingFlags flags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static;
MethodInfo method = d.GetType().GetMethod("Invoke", flags);
MethodBinder binder = new MethodBinder(method);
return binder.Invoke(ob, args, kw);
}
}
}
| |
// Outline Object Copy|Highlighters|40030
namespace VRTK.Highlighters
{
using UnityEngine;
using System;
using System.Collections.Generic;
/// <summary>
/// The Outline Object Copy Highlighter works by making a copy of a mesh and adding an outline shader to it and toggling the appearance of the highlighted object.
/// </summary>
/// <example>
/// `VRTK/Examples/005_Controller_BasicObjectGrabbing` demonstrates the outline highlighting on the green sphere when the controller touches it.
///
/// `VRTK/Examples/035_Controller_OpacityAndHighlighting` demonstrates the outline highlighting if the left controller collides with the green box.
/// </example>
[AddComponentMenu("VRTK/Scripts/Interactions/Highlighters/VRTK_OutlineObjectCopyHighlighter")]
public class VRTK_OutlineObjectCopyHighlighter : VRTK_BaseHighlighter
{
[Tooltip("The thickness of the outline effect")]
public float thickness = 1f;
[Tooltip("The GameObjects to use as the model to outline. If one isn't provided then the first GameObject with a valid Renderer in the current GameObject hierarchy will be used.")]
public GameObject[] customOutlineModels;
[Tooltip("A path to a GameObject to find at runtime, if the GameObject doesn't exist at edit time.")]
public string[] customOutlineModelPaths;
[Tooltip("If the mesh has multiple sub-meshes to highlight then this should be checked, otherwise only the first mesh will be highlighted.")]
public bool enableSubmeshHighlight = false;
protected Material stencilOutline;
protected GameObject[] highlightModels;
protected string[] copyComponents = new string[] { "UnityEngine.MeshFilter", "UnityEngine.MeshRenderer" };
/// <summary>
/// The Initialise method sets up the highlighter for use.
/// </summary>
/// <param name="color">Not used.</param>
/// <param name="options">A dictionary array containing the highlighter options:\r * `<'thickness', float>` - Same as `thickness` inspector parameter.\r * `<'customOutlineModels', GameObject[]>` - Same as `customOutlineModels` inspector parameter.\r * `<'customOutlineModelPaths', string[]>` - Same as `customOutlineModelPaths` inspector parameter.</param>
public override void Initialise(Color? color = null, Dictionary<string, object> options = null)
{
usesClonedObject = true;
if (stencilOutline == null)
{
stencilOutline = Instantiate((Material)Resources.Load("OutlineBasic"));
}
SetOptions(options);
ResetHighlighter();
}
/// <summary>
/// The ResetHighlighter method creates the additional model to use as the outline highlighted object.
/// </summary>
public override void ResetHighlighter()
{
DeleteExistingHighlightModels();
//First try and use the paths if they have been set
ResetHighlighterWithCustomModelPaths();
//If the custom models have been set then use these to override any set paths.
ResetHighlighterWithCustomModels();
//if no highlights set then try falling back
ResetHighlightersWithCurrentGameObject();
}
/// <summary>
/// The Highlight method initiates the outline object to be enabled and display the outline colour.
/// </summary>
/// <param name="color">The colour to outline with.</param>
/// <param name="duration">Not used.</param>
public override void Highlight(Color? color, float duration = 0f)
{
if (highlightModels != null && highlightModels.Length > 0)
{
stencilOutline.SetFloat("_Thickness", thickness);
stencilOutline.SetColor("_OutlineColor", (Color)color);
for (int i = 0; i < highlightModels.Length; i++)
{
if (highlightModels[i])
{
highlightModels[i].SetActive(true);
}
}
}
}
/// <summary>
/// The Unhighlight method hides the outline object and removes the outline colour.
/// </summary>
/// <param name="color">Not used.</param>
/// <param name="duration">Not used.</param>
public override void Unhighlight(Color? color = null, float duration = 0f)
{
if (highlightModels != null)
{
for (int i = 0; i < highlightModels.Length; i++)
{
if (highlightModels[i])
{
highlightModels[i].SetActive(false);
}
}
}
}
protected virtual void OnEnable()
{
if (customOutlineModels == null)
{
customOutlineModels = new GameObject[0];
}
if (customOutlineModelPaths == null)
{
customOutlineModelPaths = new string[0];
}
}
protected virtual void OnDestroy()
{
if (highlightModels != null)
{
for (int i = 0; i < highlightModels.Length; i++)
{
if (highlightModels[i])
{
Destroy(highlightModels[i]);
}
}
}
Destroy(stencilOutline);
}
protected virtual void ResetHighlighterWithCustomModels()
{
if (customOutlineModels != null && customOutlineModels.Length > 0)
{
highlightModels = new GameObject[customOutlineModels.Length];
for (int i = 0; i < customOutlineModels.Length; i++)
{
highlightModels[i] = CreateHighlightModel(customOutlineModels[i], "");
}
}
}
protected virtual void ResetHighlighterWithCustomModelPaths()
{
if (customOutlineModelPaths != null && customOutlineModelPaths.Length > 0)
{
highlightModels = new GameObject[customOutlineModels.Length];
for (int i = 0; i < customOutlineModelPaths.Length; i++)
{
highlightModels[i] = CreateHighlightModel(null, customOutlineModelPaths[i]);
}
}
}
protected virtual void ResetHighlightersWithCurrentGameObject()
{
if (highlightModels == null || highlightModels.Length == 0)
{
highlightModels = new GameObject[1];
highlightModels[0] = CreateHighlightModel(null, "");
}
}
protected virtual void SetOptions(Dictionary<string, object> options = null)
{
var tmpThickness = GetOption<float>(options, "thickness");
if (tmpThickness > 0f)
{
thickness = tmpThickness;
}
var tmpCustomModels = GetOption<GameObject[]>(options, "customOutlineModels");
if (tmpCustomModels != null)
{
customOutlineModels = tmpCustomModels;
}
var tmpCustomModelPaths = GetOption<string[]>(options, "customOutlineModelPaths");
if (tmpCustomModelPaths != null)
{
customOutlineModelPaths = tmpCustomModelPaths;
}
}
protected virtual void DeleteExistingHighlightModels()
{
var existingHighlighterObjects = GetComponentsInChildren<VRTK_PlayerObject>(true);
for (int i = 0; i < existingHighlighterObjects.Length; i++)
{
if (existingHighlighterObjects[i].objectType == VRTK_PlayerObject.ObjectTypes.Highlighter)
{
Destroy(existingHighlighterObjects[i].gameObject);
}
}
}
protected virtual GameObject CreateHighlightModel(GameObject givenOutlineModel, string givenOutlineModelPath)
{
if (givenOutlineModel != null)
{
givenOutlineModel = (givenOutlineModel.GetComponent<Renderer>() ? givenOutlineModel : givenOutlineModel.GetComponentInChildren<Renderer>().gameObject);
}
else if (givenOutlineModelPath != "")
{
var getChildModel = transform.FindChild(givenOutlineModelPath);
givenOutlineModel = (getChildModel ? getChildModel.gameObject : null);
}
GameObject copyModel = givenOutlineModel;
if (copyModel == null)
{
copyModel = (GetComponent<Renderer>() ? gameObject : GetComponentInChildren<Renderer>().gameObject);
}
if (copyModel == null)
{
VRTK_Logger.Error(VRTK_Logger.GetCommonMessage(VRTK_Logger.CommonMessageKeys.REQUIRED_COMPONENT_MISSING_FROM_GAMEOBJECT, "VRTK_OutlineObjectCopyHighlighter", "Renderer", "the same or child", " to add the highlighter to"));
return null;
}
GameObject highlightModel = new GameObject(name + "_HighlightModel");
highlightModel.transform.SetParent(copyModel.transform.parent, false);
highlightModel.transform.localPosition = copyModel.transform.localPosition;
highlightModel.transform.localRotation = copyModel.transform.localRotation;
highlightModel.transform.localScale = copyModel.transform.localScale;
highlightModel.transform.SetParent(transform);
foreach (var component in copyModel.GetComponents<Component>())
{
if (Array.IndexOf(copyComponents, component.GetType().ToString()) >= 0)
{
VRTK_SharedMethods.CloneComponent(component, highlightModel);
}
}
var copyMesh = copyModel.GetComponent<MeshFilter>();
var highlightMesh = highlightModel.GetComponent<MeshFilter>();
if (highlightMesh)
{
if (enableSubmeshHighlight)
{
List<CombineInstance> combine = new List<CombineInstance>();
for (int i = 0; i < copyMesh.mesh.subMeshCount; i++)
{
CombineInstance ci = new CombineInstance();
ci.mesh = copyMesh.mesh;
ci.subMeshIndex = i;
ci.transform = copyMesh.transform.localToWorldMatrix;
combine.Add(ci);
}
highlightMesh.mesh = new Mesh();
highlightMesh.mesh.CombineMeshes(combine.ToArray(), true, false);
}
else
{
highlightMesh.mesh = copyMesh.mesh;
}
highlightModel.GetComponent<Renderer>().material = stencilOutline;
}
highlightModel.SetActive(false);
VRTK_PlayerObject.SetPlayerObject(highlightModel, VRTK_PlayerObject.ObjectTypes.Highlighter);
return highlightModel;
}
}
}
| |
using System;
using System.Linq;
namespace Tibia.Objects
{
/// <summary>
/// Creature object.
/// </summary>
public class Creature
{
protected Client client;
protected uint address;
/// <summary>
/// Create a new creature object with the given client and address.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="address">The address.</param>
public Creature(Client client, uint address)
{
this.client = client;
this.address = address;
}
/// <summary>
/// Check if a player (creature) is in your party.
/// </summary>
/// <returns>True if the player is a member or leader of your party. False otherwise.</returns>
public bool InParty()
{
Constants.PartyShield party = PartyShield;
return (party != Constants.PartyShield.None
&& party != Constants.PartyShield.Invitee
&& party != Constants.PartyShield.Inviter);
}
private static Location AdjustLocation(Location loc, int xDiff, int yDiff)
{
int xNew = loc.X - xDiff;
int yNew = loc.Y - yDiff;
if (xNew > 17)
xNew -= 18;
else if (xNew < 0)
xNew += 18;
if (yNew > 13)
yNew -= 14;
else if (yNew < 0)
yNew += 14;
return new Location(xNew, yNew, loc.Z);
}
/// <summary>
/// Check if have a path to the creature.
/// </summary>
/// <returns></returns>
public bool IsReachable()
{
var tileList = client.Map.GetTilesOnSameFloor();
var playerTile = tileList.GetTileWithPlayer(Client);
var creatureTile = tileList.GetTileWithCreature(Id);
if (playerTile == null || creatureTile == null)
return false;
int xDiff, yDiff;
uint playerZ = client.Player.Z;
var creatures = client.BattleList.GetCreatures().Where(c => c.Z == playerZ);
uint playerId = client.Player.Id;
xDiff = (int)playerTile.MemoryLocation.X - 8;
yDiff = (int)playerTile.MemoryLocation.Y - 6;
playerTile.MemoryLocation = AdjustLocation(playerTile.MemoryLocation, xDiff, yDiff);
creatureTile.MemoryLocation = AdjustLocation(creatureTile.MemoryLocation, xDiff, yDiff);
foreach (Tile tile in tileList)
{
tile.MemoryLocation = AdjustLocation(tile.MemoryLocation, xDiff, yDiff);
if (tile.Ground.GetFlag(Addresses.DatItem.Flag.Blocking) || tile.Ground.GetFlag(Addresses.DatItem.Flag.BlocksPath) ||
tile.Items.Any(i => i.GetFlag(Addresses.DatItem.Flag.Blocking) || i.GetFlag(Addresses.DatItem.Flag.BlocksPath) || client.PathFinder.ModifiedItems.ContainsKey(i.Id)) ||
creatures.Any(c => tile.Objects.Any(o => o.Data == c.Id && o.Data != playerId && o.Data != this.Id)))
{
client.PathFinder.Grid[tile.MemoryLocation.X, tile.MemoryLocation.Y] = 0;
}
else
{
client.PathFinder.Grid[tile.MemoryLocation.X, tile.MemoryLocation.Y] = 1;
}
}
return client.PathFinder.FindPath(playerTile.MemoryLocation, creatureTile.MemoryLocation);
}
/// <summary>
/// Check if the current creature is actually yourself.
/// </summary>
/// <returns>True if it's yourself, false otherwise</returns>
public bool IsSelf()
{
return (Id == client.Player.Id);
}
public void Approach()
{
Player p = client.GetPlayer();
p.GoTo = Location;
}
/// <summary>
/// Check if the creature is attacking the player.
/// </summary>
/// <returns></returns>
public bool IsAttacking()
{
return BlackSquare != 0;
}
/// <summary>
/// Attack the creature.
/// Sends a packet to the server and sets the red square around the creature.
/// </summary>
/// <returns></returns>
public bool Attack()
{
if (client.VersionNumber >= 860)
{
if (client.Player.TargetId != Id)
{
if (client.VersionNumber >= 872)
{
client.Player.AttackCount += 2;
}
else
{
client.Player.AttackCount += 1;
}
}
}
client.Player.TargetId = Id;
return Packets.Outgoing.AttackPacket.Send(client, (uint)Id);
}
/// <summary>
/// Look at the creature / player.
/// Sends a packet to the server with the same effect as
/// shift-clicking or left-right clicking a creature.
/// </summary>
/// <returns></returns>
public bool Look()
{
return Packets.Outgoing.LookAtPacket.Send(client, Location, 0x63, 1);
}
/// <summary>
/// Follow the creature / player.
/// </summary>
/// <returns></returns>
public bool Follow()
{
if (client.VersionNumber >= 860)
{
if (client.Player.TargetId != Id)
{
if (client.VersionNumber >= 872)
{
client.Player.FollowCount += 2;
}
else
{
client.Player.FollowCount += 1;
}
}
}
client.Player.GreenSquare = Id;
return Packets.Outgoing.FollowPacket.Send(client, (uint)Id);
}
/// <summary>
/// Gets the distance between player and creature / player.
/// </summary>
/// <returns></returns>
public double DistanceTo(Location l)
{
return Location.DistanceTo(l);
}
public uint Address
{
get { return address; }
set { address = value; }
}
#region Get/Set Methods
public Client Client
{
get { return client; }
}
public uint Id
{
get { return client.Memory.ReadUInt32(address + Addresses.Creature.DistanceId); }
set { client.Memory.WriteUInt32(address + Addresses.Creature.DistanceId, value); }
}
public CreatureData Data
{
get
{
if (Constants.CreatureLists.AllCreatures.ContainsKey(Name))
{
return Constants.CreatureLists.AllCreatures[Name];
}
else
{
return null;
}
}
}
public string Name
{
get { return client.Memory.ReadString(address + Addresses.Creature.DistanceName); }
set { client.Memory.WriteString(address + Addresses.Creature.DistanceName, value); }
}
public int X
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceX); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceX, value); }
}
public int Y
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceY); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceY, value); }
}
public int Z
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceZ); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceZ, value); }
}
public Location Location
{
get { return new Location(X, Y, Z); }
}
public int ScreenOffsetHoriz
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceScreenOffsetHoriz); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceScreenOffsetHoriz, value); }
}
public int ScreenOffsetVert
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceScreenOffsetVert); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceScreenOffsetVert, value); }
}
public bool IsWalking
{
get { return Convert.ToBoolean(client.Memory.ReadByte(address + Addresses.Creature.DistanceIsWalking)); }
set { client.Memory.WriteByte(address + Addresses.Creature.DistanceIsWalking, Convert.ToByte(value)); }
}
public int WalkSpeed
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceWalkSpeed); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceWalkSpeed, value); }
}
public Constants.Direction Direction
{
get { return (Constants.Direction)client.Memory.ReadInt32(address + Addresses.Creature.DistanceDirection); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceDirection, (int)value); }
}
public bool IsVisible
{
get { return Convert.ToBoolean(client.Memory.ReadInt32(address + Addresses.Creature.DistanceIsVisible)); }
set { client.Memory.WriteByte(address + Addresses.Creature.DistanceIsVisible, Convert.ToByte(value)); }
}
public int Light
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceLight); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceLight, value); }
}
public int LightColor
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceLightColor); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceLightColor, value); }
}
public int HPBar
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceHPBar); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceHPBar, value); }
}
public int BlackSquare
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceBlackSquare); }
}
public Constants.Skull Skull
{
get { return (Constants.Skull)client.Memory.ReadInt32(address + Addresses.Creature.DistanceSkull); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceSkull, (int)value); }
}
public Constants.PartyShield PartyShield
{
get { return (Constants.PartyShield)client.Memory.ReadInt32(address + Addresses.Creature.DistanceParty); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceParty, (int)value); }
}
public Constants.WarIcon WarIcon
{
get { return (Constants.WarIcon)client.Memory.ReadInt32(address + Addresses.Creature.DistanceWarIcon); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceWarIcon, (int)value); }
}
public bool IsBlocking
{
get { return Convert.ToBoolean(client.Memory.ReadInt32(address + Addresses.Creature.DistanceIsBlocking)); }
set { client.Memory.WriteByte(address + Addresses.Creature.DistanceIsBlocking, Convert.ToByte(value)); }
}
public Constants.OutfitType OutfitType
{
get { return (Constants.OutfitType)client.Memory.ReadInt32(address + Addresses.Creature.DistanceOutfit); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceOutfit, (int)value); }
}
public int HeadColor
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceColorHead); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceColorHead, value); }
}
public int BodyColor
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceColorBody); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceColorBody, value); }
}
public int LegsColor
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceColorLegs); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceColorLegs, value); }
}
public int FeetColor
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceColorFeet); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceColorFeet, value); }
}
public Constants.OutfitAddon Addon
{
get { return (Constants.OutfitAddon)client.Memory.ReadInt32(address + Addresses.Creature.DistanceAddon); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceAddon, (int)value); }
}
public int MountId
{
get { return client.Memory.ReadInt32(address + Addresses.Creature.DistanceMountId); }
set { client.Memory.WriteInt32(address + Addresses.Creature.DistanceMountId, (int)value); }
}
public Outfit Outfit
{
get
{
return new Outfit(this, (ushort)OutfitType, (byte)HeadColor, (byte)BodyColor,
(byte)LegsColor, (byte)FeetColor, (byte)Addon, (byte)MountId);
}
set
{
OutfitType = (Constants.OutfitType)value.LookType;
HeadColor = (int)value.Head;
BodyColor = (int)value.Body;
LegsColor = (int)value.Legs;
FeetColor = (int)value.Feet;
Addon = (Constants.OutfitAddon)value.Addons;
MountId = value.MountId;
}
}
#endregion
public override string ToString()
{
return string.Format("{0}: {1}%", Name, HPBar.ToString());
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Management.WebSites.Models;
namespace Microsoft.WindowsAzure.Management.WebSites.Models
{
/// <summary>
/// Parameters supplied to the Update Web Site operation.
/// </summary>
public partial class WebSiteUpdateParameters
{
private Microsoft.WindowsAzure.Management.WebSites.Models.WebSpaceAvailabilityState? _availabilityState;
/// <summary>
/// The state of the availability of management information for the
/// site. Possible values are Normal or Limited. Normal means that the
/// site is running correctly and that management information for the
/// site is available. Limited means that only partial management
/// information for the site is available and that detailed site
/// information is unavailable.
/// </summary>
public Microsoft.WindowsAzure.Management.WebSites.Models.WebSpaceAvailabilityState? AvailabilityState
{
get { return this._availabilityState; }
set { this._availabilityState = value; }
}
private Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteComputeMode? _computeMode;
/// <summary>
/// The Compute Mode for the web site. Possible values are Shared or
/// Dedicated.
/// </summary>
public Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteComputeMode? ComputeMode
{
get { return this._computeMode; }
set { this._computeMode = value; }
}
private bool? _enabled;
/// <summary>
/// true if the site is enabled; otherwise, false. Setting this value
/// to false disables the site (takes the site off line).
/// </summary>
public bool? Enabled
{
get { return this._enabled; }
set { this._enabled = value; }
}
private IList<string> _hostNames;
/// <summary>
/// An array of strings that contains the public hostnames for the
/// site, including custom domains. Important: When you add a custom
/// domain in a PUT operation, be sure to include every hostname that
/// you want for the web site. To delete a custom domain name in a PUT
/// operation, include all of the hostnames for the site that you want
/// to keep, but leave out the one that you wangt to delete.
/// </summary>
public IList<string> HostNames
{
get { return this._hostNames; }
set { this._hostNames = value; }
}
private IList<WebSiteUpdateParameters.WebSiteHostNameSslState> _hostNameSslStates;
/// <summary>
/// SSL states bound to the website.
/// </summary>
public IList<WebSiteUpdateParameters.WebSiteHostNameSslState> HostNameSslStates
{
get { return this._hostNameSslStates; }
set { this._hostNameSslStates = value; }
}
private Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteRuntimeAvailabilityState? _runtimeAvailabilityState;
/// <summary>
/// Possible values are Normal, Degraded, or NotAvailable. Normal: the
/// web site is running correctly. Degraded: the web site is running
/// temporarily in a degraded mode (typically with less memory and a
/// shared instance.) Not Available: due to an unexpected issue, the
/// site has been excluded from provisioning. This typically occurs
/// only for free sites.
/// </summary>
public Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteRuntimeAvailabilityState? RuntimeAvailabilityState
{
get { return this._runtimeAvailabilityState; }
set { this._runtimeAvailabilityState = value; }
}
private string _serverFarm;
/// <summary>
/// String. If a server farm exists, this value is DefaultServerFarm.
/// </summary>
public string ServerFarm
{
get { return this._serverFarm; }
set { this._serverFarm = value; }
}
private Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteMode? _siteMode;
/// <summary>
/// String that represents the web site mode. If the web site mode is
/// Free, this value is Limited. If the web site mode is Shared, this
/// value is Basic. Note: The SiteMode value is not used for Reserved
/// mode. Reserved mode uses the ComputeMode setting.
/// </summary>
public Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteMode? SiteMode
{
get { return this._siteMode; }
set { this._siteMode = value; }
}
private IList<WebSiteUpdateParameters.WebSiteSslCertificate> _sslCertificates;
/// <summary>
/// SSL certificates bound to the web site.
/// </summary>
public IList<WebSiteUpdateParameters.WebSiteSslCertificate> SslCertificates
{
get { return this._sslCertificates; }
set { this._sslCertificates = value; }
}
private Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteState? _state;
/// <summary>
/// A string that describes the state of the web site. Possible values
/// are Stopped or Running.
/// </summary>
public Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteState? State
{
get { return this._state; }
set { this._state = value; }
}
/// <summary>
/// Initializes a new instance of the WebSiteUpdateParameters class.
/// </summary>
public WebSiteUpdateParameters()
{
this._hostNames = new List<string>();
this._hostNameSslStates = new List<WebSiteUpdateParameters.WebSiteHostNameSslState>();
this._sslCertificates = new List<WebSiteUpdateParameters.WebSiteSslCertificate>();
}
/// <summary>
/// SSL states bound to a website.
/// </summary>
public partial class WebSiteHostNameSslState
{
private Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteSslState? _sslState;
/// <summary>
/// The SSL state. Possible values are Disabled, SniEnabled, or
/// IpBasedEnabled.
/// </summary>
public Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteSslState? SslState
{
get { return this._sslState; }
set { this._sslState = value; }
}
private string _thumbprint;
/// <summary>
/// A string that contains the thumbprint of the SSL certificate.
/// </summary>
public string Thumbprint
{
get { return this._thumbprint; }
set { this._thumbprint = value; }
}
private bool? _toUpdate;
public bool? ToUpdate
{
get { return this._toUpdate; }
set { this._toUpdate = value; }
}
/// <summary>
/// Initializes a new instance of the WebSiteHostNameSslState class.
/// </summary>
public WebSiteHostNameSslState()
{
}
}
/// <summary>
/// Contains SSL certificate properties.
/// </summary>
public partial class WebSiteSslCertificate
{
private bool? _isToBeDeleted;
/// <summary>
/// Boolean. true if the certificate is to be deleted.
/// </summary>
public bool? IsToBeDeleted
{
get { return this._isToBeDeleted; }
set { this._isToBeDeleted = value; }
}
private string _password;
/// <summary>
/// A string that contains the password for the certificate.
/// </summary>
public string Password
{
get { return this._password; }
set { this._password = value; }
}
private byte[] _pfxBlob;
/// <summary>
/// A base64Binary value that contains the PfxBlob of the
/// certificate.
/// </summary>
public byte[] PfxBlob
{
get { return this._pfxBlob; }
set { this._pfxBlob = value; }
}
private string _thumbprint;
/// <summary>
/// A string that contains the certificate thumbprint.
/// </summary>
public string Thumbprint
{
get { return this._thumbprint; }
set { this._thumbprint = value; }
}
/// <summary>
/// Initializes a new instance of the WebSiteSslCertificate class.
/// </summary>
public WebSiteSslCertificate()
{
}
}
}
}
| |
// 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.
// File System.Windows.Media.Animation.ThicknessKeyFrameCollection.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Animation
{
public partial class ThicknessKeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable
{
#region Methods and constructors
public int Add(ThicknessKeyFrame keyFrame)
{
Contract.Requires(!this.IsFrozen);
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public void Clear()
{
}
public System.Windows.Media.Animation.ThicknessKeyFrameCollection Clone()
{
Contract.Ensures(Contract.Result<System.Windows.Media.Animation.ThicknessKeyFrameCollection>() != null);
Contract.Ensures(Contract.Result<System.Windows.Media.Animation.ThicknessKeyFrameCollection>() == ((System.Windows.Media.Animation.ThicknessKeyFrameCollection)(this.Clone())));
return default(System.Windows.Media.Animation.ThicknessKeyFrameCollection);
}
protected override void CloneCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable)
{
}
public bool Contains(ThicknessKeyFrame keyFrame)
{
return default(bool);
}
public void CopyTo(ThicknessKeyFrame[] array, int index)
{
Contract.Requires(array != null);
Contract.Requires(index >= 0);
Contract.Requires(index < array.Length);
}
protected override System.Windows.Freezable CreateInstanceCore()
{
return default(System.Windows.Freezable);
}
protected override bool FreezeCore(bool isChecking)
{
return default(bool);
}
protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable)
{
}
public System.Collections.IEnumerator GetEnumerator()
{
return default(System.Collections.IEnumerator);
}
public int IndexOf(ThicknessKeyFrame keyFrame)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public void Insert(int index, ThicknessKeyFrame keyFrame)
{
Contract.Requires(!this.IsFrozen);
Contract.Requires(index >= 0);
}
public void Remove(ThicknessKeyFrame keyFrame)
{
Contract.Requires(!this.IsFrozen);
}
public void RemoveAt(int index)
{
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
int System.Collections.IList.Add(Object keyFrame)
{
return default(int);
}
bool System.Collections.IList.Contains(Object keyFrame)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object keyFrame)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object keyFrame)
{
}
void System.Collections.IList.Remove(Object keyFrame)
{
}
public ThicknessKeyFrameCollection()
{
}
#endregion
#region Properties and indexers
public int Count
{
get
{
return default(int);
}
}
public static System.Windows.Media.Animation.ThicknessKeyFrameCollection Empty
{
get
{
Contract.Ensures(Contract.Result<System.Windows.Media.Animation.ThicknessKeyFrameCollection>() != null);
return default(System.Windows.Media.Animation.ThicknessKeyFrameCollection);
}
}
public bool IsFixedSize
{
get
{
return default(bool);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public bool IsSynchronized
{
get
{
return default(bool);
}
}
public ThicknessKeyFrame this [int index]
{
get
{
Contract.Requires(index >= 0);
return default(ThicknessKeyFrame);
}
set
{
Contract.Requires(!this.IsFrozen);
Contract.Requires(index >= 0);
}
}
public Object SyncRoot
{
get
{
return default(Object);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.IO.Compression
{
// All blocks.TryReadBlock do a check to see if signature is correct. Generic extra field is slightly different
// all of the TryReadBlocks will throw if there are not enough bytes in the stream
internal struct ZipGenericExtraField
{
private const int SizeOfHeader = 4;
private ushort _tag;
private ushort _size;
private byte[] _data;
public ushort Tag => _tag;
// returns size of data, not of the entire block
public ushort Size => _size;
public byte[] Data => _data;
public void WriteBlock(Stream stream)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(Tag);
writer.Write(Size);
writer.Write(Data);
}
// shouldn't ever read the byte at position endExtraField
// assumes we are positioned at the beginning of an extra field subfield
public static bool TryReadBlock(BinaryReader reader, long endExtraField, out ZipGenericExtraField field)
{
field = new ZipGenericExtraField();
// not enough bytes to read tag + size
if (endExtraField - reader.BaseStream.Position < 4)
return false;
field._tag = reader.ReadUInt16();
field._size = reader.ReadUInt16();
// not enough bytes to read the data
if (endExtraField - reader.BaseStream.Position < field._size)
return false;
field._data = reader.ReadBytes(field._size);
return true;
}
// shouldn't ever read the byte at position endExtraField
public static List<ZipGenericExtraField> ParseExtraField(Stream extraFieldData)
{
List<ZipGenericExtraField> extraFields = new List<ZipGenericExtraField>();
using (BinaryReader reader = new BinaryReader(extraFieldData))
{
ZipGenericExtraField field;
while (TryReadBlock(reader, extraFieldData.Length, out field))
{
extraFields.Add(field);
}
}
return extraFields;
}
public static int TotalSize(List<ZipGenericExtraField> fields)
{
int size = 0;
foreach (ZipGenericExtraField field in fields)
size += field.Size + SizeOfHeader; //size is only size of data
return size;
}
public static void WriteAllBlocks(List<ZipGenericExtraField> fields, Stream stream)
{
foreach (ZipGenericExtraField field in fields)
field.WriteBlock(stream);
}
}
internal struct Zip64ExtraField
{
// Size is size of the record not including the tag or size fields
// If the extra field is going in the local header, it cannot include only
// one of uncompressed/compressed size
public const int OffsetToFirstField = 4;
private const ushort TagConstant = 1;
private ushort _size;
private long? _uncompressedSize;
private long? _compressedSize;
private long? _localHeaderOffset;
private int? _startDiskNumber;
public ushort TotalSize => (ushort)(_size + 4);
public long? UncompressedSize
{
get { return _uncompressedSize; }
set { _uncompressedSize = value; UpdateSize(); }
}
public long? CompressedSize
{
get { return _compressedSize; }
set { _compressedSize = value; UpdateSize(); }
}
public long? LocalHeaderOffset
{
get { return _localHeaderOffset; }
set { _localHeaderOffset = value; UpdateSize(); }
}
public int? StartDiskNumber => _startDiskNumber;
private void UpdateSize()
{
_size = 0;
if (_uncompressedSize != null) _size += 8;
if (_compressedSize != null) _size += 8;
if (_localHeaderOffset != null) _size += 8;
if (_startDiskNumber != null) _size += 4;
}
// There is a small chance that something very weird could happen here. The code calling into this function
// will ask for a value from the extra field if the field was masked with FF's. It's theoretically possible
// that a field was FF's legitimately, and the writer didn't decide to write the corresponding extra field.
// Also, at the same time, other fields were masked with FF's to indicate looking in the zip64 record.
// Then, the search for the zip64 record will fail because the expected size is wrong,
// and a nulled out Zip64ExtraField will be returned. Thus, even though there was Zip64 data,
// it will not be used. It is questionable whether this situation is possible to detect
// unlike the other functions that have try-pattern semantics, these functions always return a
// Zip64ExtraField. If a Zip64 extra field actually doesn't exist, all of the fields in the
// returned struct will be null
//
// If there are more than one Zip64 extra fields, we take the first one that has the expected size
//
public static Zip64ExtraField GetJustZip64Block(Stream extraFieldStream,
bool readUncompressedSize, bool readCompressedSize,
bool readLocalHeaderOffset, bool readStartDiskNumber)
{
Zip64ExtraField zip64Field;
using (BinaryReader reader = new BinaryReader(extraFieldStream))
{
ZipGenericExtraField currentExtraField;
while (ZipGenericExtraField.TryReadBlock(reader, extraFieldStream.Length, out currentExtraField))
{
if (TryGetZip64BlockFromGenericExtraField(currentExtraField, readUncompressedSize,
readCompressedSize, readLocalHeaderOffset, readStartDiskNumber, out zip64Field))
{
return zip64Field;
}
}
}
zip64Field = new Zip64ExtraField();
zip64Field._compressedSize = null;
zip64Field._uncompressedSize = null;
zip64Field._localHeaderOffset = null;
zip64Field._startDiskNumber = null;
return zip64Field;
}
private static bool TryGetZip64BlockFromGenericExtraField(ZipGenericExtraField extraField,
bool readUncompressedSize, bool readCompressedSize,
bool readLocalHeaderOffset, bool readStartDiskNumber,
out Zip64ExtraField zip64Block)
{
zip64Block = new Zip64ExtraField();
zip64Block._compressedSize = null;
zip64Block._uncompressedSize = null;
zip64Block._localHeaderOffset = null;
zip64Block._startDiskNumber = null;
if (extraField.Tag != TagConstant)
return false;
// this pattern needed because nested using blocks trigger CA2202
MemoryStream ms = null;
try
{
ms = new MemoryStream(extraField.Data);
using (BinaryReader reader = new BinaryReader(ms))
{
ms = null;
zip64Block._size = extraField.Size;
ushort expectedSize = 0;
if (readUncompressedSize) expectedSize += 8;
if (readCompressedSize) expectedSize += 8;
if (readLocalHeaderOffset) expectedSize += 8;
if (readStartDiskNumber) expectedSize += 4;
// if it is not the expected size, perhaps there is another extra field that matches
if (expectedSize != zip64Block._size)
return false;
if (readUncompressedSize) zip64Block._uncompressedSize = reader.ReadInt64();
if (readCompressedSize) zip64Block._compressedSize = reader.ReadInt64();
if (readLocalHeaderOffset) zip64Block._localHeaderOffset = reader.ReadInt64();
if (readStartDiskNumber) zip64Block._startDiskNumber = reader.ReadInt32();
// original values are unsigned, so implies value is too big to fit in signed integer
if (zip64Block._uncompressedSize < 0) throw new InvalidDataException(SR.FieldTooBigUncompressedSize);
if (zip64Block._compressedSize < 0) throw new InvalidDataException(SR.FieldTooBigCompressedSize);
if (zip64Block._localHeaderOffset < 0) throw new InvalidDataException(SR.FieldTooBigLocalHeaderOffset);
if (zip64Block._startDiskNumber < 0) throw new InvalidDataException(SR.FieldTooBigStartDiskNumber);
return true;
}
}
finally
{
if (ms != null)
ms.Dispose();
}
}
public static Zip64ExtraField GetAndRemoveZip64Block(List<ZipGenericExtraField> extraFields,
bool readUncompressedSize, bool readCompressedSize,
bool readLocalHeaderOffset, bool readStartDiskNumber)
{
Zip64ExtraField zip64Field = new Zip64ExtraField();
zip64Field._compressedSize = null;
zip64Field._uncompressedSize = null;
zip64Field._localHeaderOffset = null;
zip64Field._startDiskNumber = null;
List<ZipGenericExtraField> markedForDelete = new List<ZipGenericExtraField>();
bool zip64FieldFound = false;
foreach (ZipGenericExtraField ef in extraFields)
{
if (ef.Tag == TagConstant)
{
markedForDelete.Add(ef);
if (!zip64FieldFound)
{
if (TryGetZip64BlockFromGenericExtraField(ef, readUncompressedSize, readCompressedSize,
readLocalHeaderOffset, readStartDiskNumber, out zip64Field))
{
zip64FieldFound = true;
}
}
}
}
foreach (ZipGenericExtraField ef in markedForDelete)
extraFields.Remove(ef);
return zip64Field;
}
public static void RemoveZip64Blocks(List<ZipGenericExtraField> extraFields)
{
List<ZipGenericExtraField> markedForDelete = new List<ZipGenericExtraField>();
foreach (ZipGenericExtraField field in extraFields)
if (field.Tag == TagConstant)
markedForDelete.Add(field);
foreach (ZipGenericExtraField field in markedForDelete)
extraFields.Remove(field);
}
public void WriteBlock(Stream stream)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(TagConstant);
writer.Write(_size);
if (_uncompressedSize != null) writer.Write(_uncompressedSize.Value);
if (_compressedSize != null) writer.Write(_compressedSize.Value);
if (_localHeaderOffset != null) writer.Write(_localHeaderOffset.Value);
if (_startDiskNumber != null) writer.Write(_startDiskNumber.Value);
}
}
internal struct Zip64EndOfCentralDirectoryLocator
{
public const uint SignatureConstant = 0x07064B50;
public const int SizeOfBlockWithoutSignature = 16;
public uint NumberOfDiskWithZip64EOCD;
public ulong OffsetOfZip64EOCD;
public uint TotalNumberOfDisks;
public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryLocator zip64EOCDLocator)
{
zip64EOCDLocator = new Zip64EndOfCentralDirectoryLocator();
if (reader.ReadUInt32() != SignatureConstant)
return false;
zip64EOCDLocator.NumberOfDiskWithZip64EOCD = reader.ReadUInt32();
zip64EOCDLocator.OffsetOfZip64EOCD = reader.ReadUInt64();
zip64EOCDLocator.TotalNumberOfDisks = reader.ReadUInt32();
return true;
}
public static void WriteBlock(Stream stream, long zip64EOCDRecordStart)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(SignatureConstant);
writer.Write((uint)0); // number of disk with start of zip64 eocd
writer.Write(zip64EOCDRecordStart);
writer.Write((uint)1); // total number of disks
}
}
internal struct Zip64EndOfCentralDirectoryRecord
{
private const uint SignatureConstant = 0x06064B50;
private const ulong NormalSize = 0x2C; // the size of the data excluding the size/signature fields if no extra data included
public ulong SizeOfThisRecord;
public ushort VersionMadeBy;
public ushort VersionNeededToExtract;
public uint NumberOfThisDisk;
public uint NumberOfDiskWithStartOfCD;
public ulong NumberOfEntriesOnThisDisk;
public ulong NumberOfEntriesTotal;
public ulong SizeOfCentralDirectory;
public ulong OffsetOfCentralDirectory;
public static bool TryReadBlock(BinaryReader reader, out Zip64EndOfCentralDirectoryRecord zip64EOCDRecord)
{
zip64EOCDRecord = new Zip64EndOfCentralDirectoryRecord();
if (reader.ReadUInt32() != SignatureConstant)
return false;
zip64EOCDRecord.SizeOfThisRecord = reader.ReadUInt64();
zip64EOCDRecord.VersionMadeBy = reader.ReadUInt16();
zip64EOCDRecord.VersionNeededToExtract = reader.ReadUInt16();
zip64EOCDRecord.NumberOfThisDisk = reader.ReadUInt32();
zip64EOCDRecord.NumberOfDiskWithStartOfCD = reader.ReadUInt32();
zip64EOCDRecord.NumberOfEntriesOnThisDisk = reader.ReadUInt64();
zip64EOCDRecord.NumberOfEntriesTotal = reader.ReadUInt64();
zip64EOCDRecord.SizeOfCentralDirectory = reader.ReadUInt64();
zip64EOCDRecord.OffsetOfCentralDirectory = reader.ReadUInt64();
return true;
}
public static void WriteBlock(Stream stream, long numberOfEntries, long startOfCentralDirectory, long sizeOfCentralDirectory)
{
BinaryWriter writer = new BinaryWriter(stream);
// write Zip 64 EOCD record
writer.Write(SignatureConstant);
writer.Write(NormalSize);
writer.Write((ushort)ZipVersionNeededValues.Zip64); // version needed is 45 for zip 64 support
writer.Write((ushort)ZipVersionNeededValues.Zip64); // version made by: high byte is 0 for MS DOS, low byte is version needed
writer.Write((uint)0); // number of this disk is 0
writer.Write((uint)0); // number of disk with start of central directory is 0
writer.Write(numberOfEntries); // number of entries on this disk
writer.Write(numberOfEntries); // number of entries total
writer.Write(sizeOfCentralDirectory);
writer.Write(startOfCentralDirectory);
}
}
internal struct ZipLocalFileHeader
{
public const uint DataDescriptorSignature = 0x08074B50;
public const uint SignatureConstant = 0x04034B50;
public const int OffsetToCrcFromHeaderStart = 14;
public const int OffsetToBitFlagFromHeaderStart = 6;
public const int SizeOfLocalHeader = 30;
public static List<ZipGenericExtraField> GetExtraFields(BinaryReader reader)
{
// assumes that TrySkipBlock has already been called, so we don't have to validate twice
List<ZipGenericExtraField> result;
const int OffsetToFilenameLength = 26; // from the point before the signature
reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current);
ushort filenameLength = reader.ReadUInt16();
ushort extraFieldLength = reader.ReadUInt16();
reader.BaseStream.Seek(filenameLength, SeekOrigin.Current);
using (Stream str = new SubReadStream(reader.BaseStream, reader.BaseStream.Position, extraFieldLength))
{
result = ZipGenericExtraField.ParseExtraField(str);
}
Zip64ExtraField.RemoveZip64Blocks(result);
return result;
}
// will not throw end of stream exception
public static bool TrySkipBlock(BinaryReader reader)
{
const int OffsetToFilenameLength = 22; // from the point after the signature
if (reader.ReadUInt32() != SignatureConstant)
return false;
if (reader.BaseStream.Length < reader.BaseStream.Position + OffsetToFilenameLength)
return false;
reader.BaseStream.Seek(OffsetToFilenameLength, SeekOrigin.Current);
ushort filenameLength = reader.ReadUInt16();
ushort extraFieldLength = reader.ReadUInt16();
if (reader.BaseStream.Length < reader.BaseStream.Position + filenameLength + extraFieldLength)
return false;
reader.BaseStream.Seek(filenameLength + extraFieldLength, SeekOrigin.Current);
return true;
}
}
internal struct ZipCentralDirectoryFileHeader
{
public const uint SignatureConstant = 0x02014B50;
public byte VersionMadeByCompatibility;
public byte VersionMadeBySpecification;
public ushort VersionNeededToExtract;
public ushort GeneralPurposeBitFlag;
public ushort CompressionMethod;
public uint LastModified; // convert this on the fly
public uint Crc32;
public long CompressedSize;
public long UncompressedSize;
public ushort FilenameLength;
public ushort ExtraFieldLength;
public ushort FileCommentLength;
public int DiskNumberStart;
public ushort InternalFileAttributes;
public uint ExternalFileAttributes;
public long RelativeOffsetOfLocalHeader;
public byte[] Filename;
public byte[] FileComment;
public List<ZipGenericExtraField> ExtraFields;
// if saveExtraFieldsAndComments is false, FileComment and ExtraFields will be null
// in either case, the zip64 extra field info will be incorporated into other fields
public static bool TryReadBlock(BinaryReader reader, bool saveExtraFieldsAndComments, out ZipCentralDirectoryFileHeader header)
{
header = new ZipCentralDirectoryFileHeader();
if (reader.ReadUInt32() != SignatureConstant)
return false;
header.VersionMadeBySpecification = reader.ReadByte();
header.VersionMadeByCompatibility = reader.ReadByte();
header.VersionNeededToExtract = reader.ReadUInt16();
header.GeneralPurposeBitFlag = reader.ReadUInt16();
header.CompressionMethod = reader.ReadUInt16();
header.LastModified = reader.ReadUInt32();
header.Crc32 = reader.ReadUInt32();
uint compressedSizeSmall = reader.ReadUInt32();
uint uncompressedSizeSmall = reader.ReadUInt32();
header.FilenameLength = reader.ReadUInt16();
header.ExtraFieldLength = reader.ReadUInt16();
header.FileCommentLength = reader.ReadUInt16();
ushort diskNumberStartSmall = reader.ReadUInt16();
header.InternalFileAttributes = reader.ReadUInt16();
header.ExternalFileAttributes = reader.ReadUInt32();
uint relativeOffsetOfLocalHeaderSmall = reader.ReadUInt32();
header.Filename = reader.ReadBytes(header.FilenameLength);
bool uncompressedSizeInZip64 = uncompressedSizeSmall == ZipHelper.Mask32Bit;
bool compressedSizeInZip64 = compressedSizeSmall == ZipHelper.Mask32Bit;
bool relativeOffsetInZip64 = relativeOffsetOfLocalHeaderSmall == ZipHelper.Mask32Bit;
bool diskNumberStartInZip64 = diskNumberStartSmall == ZipHelper.Mask16Bit;
Zip64ExtraField zip64;
long endExtraFields = reader.BaseStream.Position + header.ExtraFieldLength;
using (Stream str = new SubReadStream(reader.BaseStream, reader.BaseStream.Position, header.ExtraFieldLength))
{
if (saveExtraFieldsAndComments)
{
header.ExtraFields = ZipGenericExtraField.ParseExtraField(str);
zip64 = Zip64ExtraField.GetAndRemoveZip64Block(header.ExtraFields,
uncompressedSizeInZip64, compressedSizeInZip64,
relativeOffsetInZip64, diskNumberStartInZip64);
}
else
{
header.ExtraFields = null;
zip64 = Zip64ExtraField.GetJustZip64Block(str,
uncompressedSizeInZip64, compressedSizeInZip64,
relativeOffsetInZip64, diskNumberStartInZip64);
}
}
// There are zip files that have malformed ExtraField blocks in which GetJustZip64Block() silently bails out without reading all the way to the end
// of the ExtraField block. Thus we must force the stream's position to the proper place.
reader.BaseStream.AdvanceToPosition(endExtraFields);
if (saveExtraFieldsAndComments)
header.FileComment = reader.ReadBytes(header.FileCommentLength);
else
{
reader.BaseStream.Position += header.FileCommentLength;
header.FileComment = null;
}
header.UncompressedSize = zip64.UncompressedSize == null
? uncompressedSizeSmall
: zip64.UncompressedSize.Value;
header.CompressedSize = zip64.CompressedSize == null
? compressedSizeSmall
: zip64.CompressedSize.Value;
header.RelativeOffsetOfLocalHeader = zip64.LocalHeaderOffset == null
? relativeOffsetOfLocalHeaderSmall
: zip64.LocalHeaderOffset.Value;
header.DiskNumberStart = zip64.StartDiskNumber == null
? diskNumberStartSmall
: zip64.StartDiskNumber.Value;
return true;
}
}
internal struct ZipEndOfCentralDirectoryBlock
{
public const uint SignatureConstant = 0x06054B50;
public const int SizeOfBlockWithoutSignature = 18;
public uint Signature;
public ushort NumberOfThisDisk;
public ushort NumberOfTheDiskWithTheStartOfTheCentralDirectory;
public ushort NumberOfEntriesInTheCentralDirectoryOnThisDisk;
public ushort NumberOfEntriesInTheCentralDirectory;
public uint SizeOfCentralDirectory;
public uint OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber;
public byte[] ArchiveComment;
public static void WriteBlock(Stream stream, long numberOfEntries, long startOfCentralDirectory, long sizeOfCentralDirectory, byte[] archiveComment)
{
BinaryWriter writer = new BinaryWriter(stream);
ushort numberOfEntriesTruncated = numberOfEntries > ushort.MaxValue ?
ZipHelper.Mask16Bit : (ushort)numberOfEntries;
uint startOfCentralDirectoryTruncated = startOfCentralDirectory > uint.MaxValue ?
ZipHelper.Mask32Bit : (uint)startOfCentralDirectory;
uint sizeOfCentralDirectoryTruncated = sizeOfCentralDirectory > uint.MaxValue ?
ZipHelper.Mask32Bit : (uint)sizeOfCentralDirectory;
writer.Write(SignatureConstant);
writer.Write((ushort)0); // number of this disk
writer.Write((ushort)0); // number of disk with start of CD
writer.Write(numberOfEntriesTruncated); // number of entries on this disk's cd
writer.Write(numberOfEntriesTruncated); // number of entries in entire CD
writer.Write(sizeOfCentralDirectoryTruncated);
writer.Write(startOfCentralDirectoryTruncated);
// Should be valid because of how we read archiveComment in TryReadBlock:
Debug.Assert((archiveComment == null) || (archiveComment.Length < ushort.MaxValue));
writer.Write(archiveComment != null ? (ushort)archiveComment.Length : (ushort)0); // zip file comment length
if (archiveComment != null)
writer.Write(archiveComment);
}
public static bool TryReadBlock(BinaryReader reader, out ZipEndOfCentralDirectoryBlock eocdBlock)
{
eocdBlock = new ZipEndOfCentralDirectoryBlock();
if (reader.ReadUInt32() != SignatureConstant)
return false;
eocdBlock.Signature = SignatureConstant;
eocdBlock.NumberOfThisDisk = reader.ReadUInt16();
eocdBlock.NumberOfTheDiskWithTheStartOfTheCentralDirectory = reader.ReadUInt16();
eocdBlock.NumberOfEntriesInTheCentralDirectoryOnThisDisk = reader.ReadUInt16();
eocdBlock.NumberOfEntriesInTheCentralDirectory = reader.ReadUInt16();
eocdBlock.SizeOfCentralDirectory = reader.ReadUInt32();
eocdBlock.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber = reader.ReadUInt32();
ushort commentLength = reader.ReadUInt16();
eocdBlock.ArchiveComment = reader.ReadBytes(commentLength);
return true;
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// ParticleSystem.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace VectorRumble
{
/// <summary>
/// A system for maintaining and rendering particles in this game.
/// </summary>
class ParticleSystem
{
#region Constants
/// <summary>
/// The amount that the alpha on each particle diminishes per second.
/// </summary>
const float alphaReductionPerSecond = 45f;
/// <summary>
/// The percent that the velocity on each particle diminishes per second.
/// </summary>
const float velocityPercentReductionPerSecond = 0.98f;
#endregion
#region Fields
static Random random = new Random();
/// <summary>
/// The amount of time left before this particle system disappears.
/// </summary>
float lifeRemaining;
/// <summary>
/// The number of particles in this particle system.
/// </summary>
int count;
/// <summary>
/// The total lifetime of the particle system.
/// </summary>
float life;
/// <summary>
/// The list of particles in this system.
/// </summary>
Particle[] particles = null;
/// <summary>
/// The position of the particle system.
/// </summary>
Vector2 position;
/// <summary>
/// The direction that this particle system is moving in.
/// </summary>
Vector2 direction;
/// <summary>
/// The minimum velocity of particles when the system starts.
/// </summary>
float minVelocity;
/// <summary>
/// The maximum velocity of particles when the system starts.
/// </summary>
float maxVelocity;
/// <summary>
/// The length of the lines drawn for each particle.
/// </summary>
float tailLength;
/// <summary>
/// The colors used for the particles.
/// </summary>
Color[] colors;
#endregion
#region Properties
/// <summary>
/// If true, the particle system is still updating and rendering.
/// </summary>
public bool IsActive
{
get
{
return (lifeRemaining > 0f);
}
}
#endregion
#region Initialization
/// <summary>
/// Constructs a new particle system object using the given parameters.
/// </summary>
/// <param name="position">The position of the system.</param>
/// <param name="direction">The direction that the system is moving in.</param>
/// <param name="count">The number of particles in the system.</param>
/// <param name="minVelocity">The minimum velocity of particles.</param>
/// <param name="maxVelocity">The maximum velocity of particles.</param>
/// <param name="life">The lifetime of the system.</param>
/// <param name="tailLength">The length of the tails of the particles.</param>
/// <param name="colors">The colors of the particles.</param>
public ParticleSystem(Vector2 position, Vector2 direction, int count,
float minVelocity, float maxVelocity, float life, float tailLength,
params Color[] colors)
{
Reset(position, direction, count, minVelocity, maxVelocity, life,
tailLength, colors);
}
/// <summary>
/// Resets the particle system object using the new values.
/// </summary>
/// <param name="position">The position of the system.</param>
/// <param name="direction">The direction that the system is moving in.</param>
/// <param name="count">The number of particles in the system.</param>
/// <param name="minVelocity">The minimum velocity of particles.</param>
/// <param name="maxVelocity">The maximum velocity of particles.</param>
/// <param name="life">The lifetime of the system.</param>
/// <param name="tailLength">The length of the tails of the particles.</param>
/// <param name="colors">The colors of the particles.</param>
public void Reset(Vector2 position, Vector2 direction, int count,
float minVelocity, float maxVelocity, float life, float tailLength,
params Color[] colors)
{
// assign the parameters
this.count = Math.Max(0, count);
this.life = life;
this.position = position;
this.direction = direction;
this.minVelocity = minVelocity;
this.maxVelocity = maxVelocity;
this.tailLength = tailLength;
this.colors = colors;
if ((this.colors == null) || (this.colors.Length < 1))
{
colors = new Color[1];
colors[0] = Color.White;
}
// recreate the particle array if necessary
if ((particles == null) || (particles.Length != this.count))
{
particles = new Particle[this.count];
}
Reset();
}
/// <summary>
/// Reset the particle system to it's initial state, using the last set of
/// parameters.
/// </summary>
public void Reset()
{
// set each particle to it's default starting state
for (int i = 0; i < particles.Length; i++)
{
particles[i].Position = this.position;
particles[i].Velocity = new Vector2(
1.0f - 2.0f * (float)random.NextDouble(),
1.0f - 2.0f * (float)random.NextDouble());
particles[i].Velocity.Normalize();
particles[i].Velocity *= this.minVelocity +
this.maxVelocity * (float)random.NextDouble();
particles[i].Velocity += this.direction;
particles[i].Color = this.colors[random.Next(this.colors.Length)];
}
// reset the remaining lifetime on the particle system
lifeRemaining = life;
}
#endregion
#region Update and Draw
/// <summary>
/// Update the particle system.
/// </summary>
/// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
public virtual void Update(float elapsedTime)
{
if (lifeRemaining > 0f)
{
// update each particle
for (int i = 0; i < particles.Length; i++)
{
particles[i].Position += particles[i].Velocity * elapsedTime;
particles[i].Color = new Color(
particles[i].Color.R,
particles[i].Color.G,
particles[i].Color.B,
(byte)((float)particles[i].Color.A -
alphaReductionPerSecond * elapsedTime)
);
particles[i].Velocity -= particles[i].Velocity *
(velocityPercentReductionPerSecond * elapsedTime);
}
this.lifeRemaining -= elapsedTime;
}
}
/// <summary>
/// Render the particle system.
/// </summary>
/// <param name="lineBatch">The line batch which draws all the particles</param>
public virtual void Draw(LineBatch lineBatch)
{
if (lifeRemaining > 0f)
{
if (lineBatch == null)
{
throw new ArgumentNullException("lineBatch");
}
for (int i = 0; i < particles.Length; i++)
{
lineBatch.DrawLine(particles[i].Position,
particles[i].Position - particles[i].Velocity * tailLength,
particles[i].Color);
}
}
}
#endregion
}
}
| |
/*
* 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.Process
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Defines forked Ignite node.
/// </summary>
public class IgniteProcess
{
/** Executable file name. */
private static readonly string ExeName = "Apache.Ignite.exe";
/** Executable process name. */
private static readonly string ExeProcName = ExeName.Substring(0, ExeName.LastIndexOf('.'));
/** Executable configuration file name. */
private static readonly string ExeCfgName = ExeName + ".config";
/** Executable backup configuration file name. */
private static readonly string ExeCfgBakName = ExeCfgName + ".bak";
/** Directory where binaries are stored. */
private static readonly string ExeDir;
/** Full path to executable. */
private static readonly string ExePath;
/** Full path to executable configuration file. */
private static readonly string ExeCfgPath;
/** Full path to executable configuration file backup. */
private static readonly string ExeCfgBakPath;
/** Default process output reader. */
private static readonly IIgniteProcessOutputReader DfltOutReader = new IgniteProcessConsoleOutputReader();
/** Process. */
private readonly Process _proc;
/// <summary>
/// Static initializer.
/// </summary>
static IgniteProcess()
{
// 1. Locate executable file and related stuff.
DirectoryInfo dir = new FileInfo(new Uri(typeof(IgniteProcess).Assembly.CodeBase).LocalPath).Directory;
// ReSharper disable once PossibleNullReferenceException
ExeDir = dir.FullName;
var exe = dir.GetFiles(ExeName);
if (exe.Length == 0)
throw new Exception(ExeName + " is not found in test output directory: " + dir.FullName);
ExePath = exe[0].FullName;
var exeCfg = dir.GetFiles(ExeCfgName);
if (exeCfg.Length == 0)
throw new Exception(ExeCfgName + " is not found in test output directory: " + dir.FullName);
ExeCfgPath = exeCfg[0].FullName;
ExeCfgBakPath = Path.Combine(ExeDir, ExeCfgBakName);
File.Delete(ExeCfgBakPath);
}
/// <summary>
/// Save current configuration to backup.
/// </summary>
public static void SaveConfigurationBackup()
{
File.Copy(ExeCfgPath, ExeCfgBakPath, true);
}
/// <summary>
/// Restore configuration from backup.
/// </summary>
public static void RestoreConfigurationBackup()
{
File.Copy(ExeCfgBakPath, ExeCfgPath, true);
}
/// <summary>
/// Replace application configuration with another one.
/// </summary>
/// <param name="relPath">Path to config relative to executable directory.</param>
public static void ReplaceConfiguration(string relPath)
{
File.Copy(Path.Combine(ExeDir, relPath), ExeCfgPath, true);
}
/// <summary>
/// Kill all Ignite processes.
/// </summary>
public static void KillAll()
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(ExeProcName))
{
proc.Kill();
proc.WaitForExit();
}
}
}
/// <summary>
/// Construector.
/// </summary>
/// <param name="args">Arguments</param>
public IgniteProcess(params string[] args) : this(DfltOutReader, args) { }
/// <summary>
/// Construector.
/// </summary>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
public IgniteProcess(IIgniteProcessOutputReader outReader, params string[] args)
{
// Add test dll path
args = args.Concat(new[] {"-assembly=" + GetType().Assembly.Location}).ToArray();
_proc = Start(ExePath, IgniteHome.Resolve(null), outReader, args);
}
/// <summary>
/// Starts a grid process.
/// </summary>
/// <param name="exePath">Exe path.</param>
/// <param name="ggHome">Ignite home.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
/// <returns>Started process.</returns>
public static Process Start(string exePath, string ggHome, IIgniteProcessOutputReader outReader = null,
params string[] args)
{
Debug.Assert(!string.IsNullOrEmpty(exePath));
// 1. Define process start configuration.
var sb = new StringBuilder();
foreach (string arg in args)
sb.Append('\"').Append(arg).Append("\" ");
var procStart = new ProcessStartInfo
{
FileName = exePath,
Arguments = sb.ToString(),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
if (ggHome != null)
procStart.EnvironmentVariables[IgniteHome.EnvIgniteHome] = ggHome;
procStart.EnvironmentVariables[Classpath.EnvIgniteNativeTestClasspath] = "true";
var workDir = Path.GetDirectoryName(exePath);
if (workDir != null)
procStart.WorkingDirectory = workDir;
Console.WriteLine("About to run Apache.Ignite.exe process [exePath=" + exePath + ", arguments=" + sb + ']');
// 2. Start.
var proc = Process.Start(procStart);
Debug.Assert(proc != null);
// 3. Attach output readers to avoid hangs.
outReader = outReader ?? DfltOutReader;
Attach(proc, proc.StandardOutput, outReader, false);
Attach(proc, proc.StandardError, outReader, true);
return proc;
}
/// <summary>
/// Whether the process is still alive.
/// </summary>
public bool Alive
{
get { return !_proc.HasExited; }
}
/// <summary>
/// Gets the process.
/// </summary>
public string GetInfo()
{
return Alive
? string.Format("Id={0}, Alive={1}", _proc.Id, Alive)
: string.Format("Id={0}, Alive={1}, ExitCode={2}, ExitTime={3}",
_proc.Id, Alive, _proc.ExitCode, _proc.ExitTime);
}
/// <summary>
/// Kill process.
/// </summary>
public void Kill()
{
_proc.Kill();
}
/// <summary>
/// Suspends the process.
/// </summary>
public void Suspend()
{
_proc.Suspend();
}
/// <summary>
/// Resumes the process.
/// </summary>
public void Resume()
{
_proc.Resume();
}
/// <summary>
/// Join process.
/// </summary>
/// <returns>Exit code.</returns>
public int Join()
{
_proc.WaitForExit();
return _proc.ExitCode;
}
/// <summary>
/// Join process with timeout.
/// </summary>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <param name="exitCode">Exit code.</param>
/// <returns><c>True</c> if process exit occurred before timeout.</returns>
public bool Join(int timeout, out int exitCode)
{
if (_proc.WaitForExit(timeout))
{
exitCode = _proc.ExitCode;
return true;
}
exitCode = 0;
return false;
}
/// <summary>
/// Attach output reader to the process.
/// </summary>
/// <param name="proc">Process.</param>
/// <param name="reader">Process stream reader.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="err">Whether this is error stream.</param>
private static void Attach(Process proc, StreamReader reader, IIgniteProcessOutputReader outReader, bool err)
{
new Thread(() =>
{
while (!proc.HasExited)
outReader.OnOutput(proc, reader.ReadLine(), err);
}) {IsBackground = true}.Start();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using Common.Logging;
using Rhino.Queues.Exceptions;
using Rhino.Queues.Model;
using Rhino.Queues.Protocol;
using Rhino.Queues.Storage;
using Wintellect.Threading.AsyncProgModel;
namespace Rhino.Queues.Tests.Protocol
{
public class FakeSender : IDisposable
{
private readonly ILog logger = LogManager.GetLogger(typeof(FakeSender));
public bool FailToAcknowledgeReceipt;
public event Action SendCompleted;
public Func<MessageBookmark[]> Success { get; set; }
public Action<Exception> Failure { get; set; }
public Action<MessageBookmark[]> Revert { get; set; }
public Action Commit { get; set; }
public Endpoint Destination { get; set; }
public Message[] Messages { get; set; }
public FakeSender()
{
Failure = e => { };
Success = () => null;
Revert = bookmarks => { };
Commit = () => { };
}
public void Send()
{
var enumerator = new AsyncEnumerator(
string.Format("Sending {0} messages to {1}", Messages.Length,
Destination)
);
logger.DebugFormat("Starting to send {0} messages to {1}", Messages.Length, Destination);
enumerator.BeginExecute(SendInternal(enumerator), result =>
{
try
{
enumerator.EndExecute(result);
}
catch (Exception exception)
{
logger.Warn("Failed to send message", exception);
Failure(exception);
}
});
}
private IEnumerator<int> SendInternal(AsyncEnumerator ae)
{
try
{
using (var client = new TcpClient())
{
try
{
client.BeginConnect(Destination.Host, Destination.Port,
ae.End(),
null);
}
catch (Exception exception)
{
logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception);
Failure(exception);
yield break;
}
yield return 1;
try
{
client.EndConnect(ae.DequeueAsyncResult());
}
catch (Exception exception)
{
logger.WarnFormat("Failed to connect to {0} because {1}", Destination, exception);
Failure(exception);
yield break;
}
logger.DebugFormat("Successfully connected to {0}", Destination);
using (var stream = client.GetStream())
{
var buffer = Messages.Serialize();
var bufferLenInBytes = BitConverter.GetBytes(buffer.Length);
logger.DebugFormat("Writing length of {0} bytes to {1}", buffer.Length, Destination);
try
{
stream.BeginWrite(bufferLenInBytes, 0, bufferLenInBytes.Length, ae.End(), null);
}
catch (Exception exception)
{
logger.WarnFormat("Could not write to {0} because {1}", Destination,
exception);
Failure(exception);
yield break;
}
yield return 1;
try
{
stream.EndWrite(ae.DequeueAsyncResult());
}
catch (Exception exception)
{
logger.WarnFormat("Could not write to {0} because {1}", Destination,
exception);
Failure(exception);
yield break;
}
logger.DebugFormat("Writing {0} bytes to {1}", buffer.Length, Destination);
try
{
stream.BeginWrite(buffer, 0, buffer.Length, ae.End(), null);
}
catch (Exception exception)
{
logger.WarnFormat("Could not write to {0} because {1}", Destination,
exception);
Failure(exception);
yield break;
}
yield return 1;
try
{
stream.EndWrite(ae.DequeueAsyncResult());
}
catch (Exception exception)
{
logger.WarnFormat("Could not write to {0} because {1}", Destination,
exception);
Failure(exception);
yield break;
}
logger.DebugFormat("Successfully wrote to {0}", Destination);
var recieveBuffer = new byte[ProtocolConstants.RecievedBuffer.Length];
var readConfirmationEnumerator = new AsyncEnumerator();
try
{
readConfirmationEnumerator.BeginExecute(
StreamUtil.ReadBytes(recieveBuffer, stream, readConfirmationEnumerator, "recieve confirmation", false), ae.End());
}
catch (Exception exception)
{
logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination,
exception);
Failure(exception);
yield break;
}
yield return 1;
try
{
readConfirmationEnumerator.EndExecute(ae.DequeueAsyncResult());
}
catch (Exception exception)
{
logger.WarnFormat("Could not read confirmation from {0} because {1}", Destination,
exception);
Failure(exception);
yield break;
}
var recieveRespone = Encoding.Unicode.GetString(recieveBuffer);
if (recieveRespone == ProtocolConstants.QueueDoesNotExists)
{
logger.WarnFormat(
"Response from reciever {0} is that queue does not exists",
Destination);
Failure(new QueueDoesNotExistsException());
yield break;
}
else if(recieveRespone!=ProtocolConstants.Recieved)
{
logger.WarnFormat(
"Response from reciever {0} is not the expected one, unexpected response was: {1}",
Destination, recieveRespone);
Failure(null);
yield break;
}
try
{
if (FailToAcknowledgeReceipt)
yield break;
stream.BeginWrite(ProtocolConstants.AcknowledgedBuffer, 0,
ProtocolConstants.AcknowledgedBuffer.Length, ae.End(), null);
}
catch (Exception exception)
{
logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}",
Destination, exception);
Failure(exception);
yield break;
}
yield return 1;
try
{
stream.EndWrite(ae.DequeueAsyncResult());
}
catch (Exception exception)
{
logger.WarnFormat("Failed to write acknowledgement to reciever {0} because {1}",
Destination, exception);
Failure(exception);
yield break;
}
var bookmarks = Success();
buffer = new byte[ProtocolConstants.RevertBuffer.Length];
var readRevertMessage = new AsyncEnumerator(ae.ToString());
bool startingToReadFailed = false;
try
{
readRevertMessage.BeginExecute(
StreamUtil.ReadBytes(buffer, stream, readRevertMessage, "revert", true), ae.End());
}
catch (Exception)
{
//more or less expected
startingToReadFailed = true;
}
if (startingToReadFailed)
{
Commit();
yield break;
}
yield return 1;
try
{
readRevertMessage.EndExecute(ae.DequeueAsyncResult());
var revert = Encoding.Unicode.GetString(buffer);
if (revert == ProtocolConstants.Revert)
{
logger.Warn("Got back revert message from receiver, reverting send");
Revert(bookmarks);
}
else
Commit();
}
catch (Exception)
{
// expected, there is nothing to do here, the
// reciever didn't report anything for us
Commit();
}
}
}
}
finally
{
var completed = SendCompleted;
if (completed != null)
completed();
}
}
public void Dispose()
{
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayer
{
public class UniverseSyncCache
{
private static UniverseSyncCache singleton = new UniverseSyncCache();
public string cacheDirectory
{
get
{
return Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Cache");
}
}
private AutoResetEvent incomingEvent = new AutoResetEvent(false);
private Queue<byte[]> incomingQueue = new Queue<byte[]>();
private Dictionary<string, long> fileLengths = new Dictionary<string, long>();
private Dictionary<string, DateTime> fileCreationTimes = new Dictionary<string, DateTime>();
public long currentCacheSize
{
get;
private set;
}
public UniverseSyncCache()
{
Thread processingThread = new Thread(new ThreadStart(ProcessingThreadMain));
processingThread.IsBackground = true;
processingThread.Start();
}
public static UniverseSyncCache fetch
{
get
{
return singleton;
}
}
private void ProcessingThreadMain()
{
while (true)
{
if (incomingQueue.Count == 0)
{
incomingEvent.WaitOne(500);
}
else
{
byte[] incomingBytes;
lock (incomingQueue)
{
incomingBytes = incomingQueue.Dequeue();
}
SaveToCache(incomingBytes);
}
}
}
private string[] GetCachedFiles()
{
return Directory.GetFiles(cacheDirectory);
}
public string[] GetCachedObjects()
{
string[] cacheFiles = GetCachedFiles();
string[] cacheObjects = new string[cacheFiles.Length];
for (int i = 0; i < cacheFiles.Length; i++)
{
cacheObjects[i] = Path.GetFileNameWithoutExtension(cacheFiles[i]);
}
return cacheObjects;
}
public void ExpireCache()
{
DarkLog.Debug("Expiring cache!");
//No folder, no delete.
if (!Directory.Exists(Path.Combine(cacheDirectory, "Incoming")))
{
DarkLog.Debug("No sync cache folder, skipping expire.");
return;
}
//Delete partial incoming files
string[] incomingFiles = Directory.GetFiles(Path.Combine(cacheDirectory, "Incoming"));
foreach (string incomingFile in incomingFiles)
{
DarkLog.Debug("Deleting partially cached object " + incomingFile);
File.Delete(incomingFile);
}
//Delete old files
string[] cacheObjects = GetCachedObjects();
currentCacheSize = 0;
foreach (string cacheObject in cacheObjects)
{
string cacheFile = Path.Combine(cacheDirectory, cacheObject + ".txt");
//If the file is older than a week, delete it.
if (File.GetCreationTime(cacheFile).AddDays(7d) < DateTime.Now)
{
DarkLog.Debug("Deleting cached object " + cacheObject + ", reason: Expired!");
File.Delete(cacheFile);
}
else
{
FileInfo fi = new FileInfo(cacheFile);
fileCreationTimes[cacheObject] = fi.CreationTime;
fileLengths[cacheObject] = fi.Length;
currentCacheSize += fi.Length;
}
}
//While the directory is over (cacheSize) MB
while (currentCacheSize > (Settings.fetch.cacheSize * 1024 * 1024))
{
string deleteObject = null;
//Find oldest file
foreach (KeyValuePair<string, DateTime> testFile in fileCreationTimes)
{
if (deleteObject == null)
{
deleteObject = testFile.Key;
}
if (testFile.Value < fileCreationTimes[deleteObject])
{
deleteObject = testFile.Key;
}
}
DarkLog.Debug("Deleting cached object " + deleteObject + ", reason: Cache full!");
string deleteFile = Path.Combine(cacheDirectory, deleteObject + ".txt");
File.Delete(deleteFile);
currentCacheSize -= fileLengths[deleteObject];
if (fileCreationTimes.ContainsKey(deleteObject))
{
fileCreationTimes.Remove(deleteObject);
}
if (fileLengths.ContainsKey(deleteObject))
{
fileLengths.Remove(deleteObject);
}
}
}
/// <summary>
/// Queues to cache. This method is non-blocking, using SaveToCache for a blocking method.
/// </summary>
/// <param name="fileData">File data.</param>
public void QueueToCache(byte[] fileData)
{
lock (incomingQueue)
{
incomingQueue.Enqueue(fileData);
}
incomingEvent.Set();
}
/// <summary>
/// Saves to cache. This method is blocking, use QueueToCache for a non-blocking method.
/// </summary>
/// <param name="fileData">File data.</param>
public void SaveToCache(byte[] fileData)
{
if (fileData == null || fileData.Length == 0)
{
//Don't save 0 byte data.
return;
}
string objectName = Common.CalculateSHA256Hash(fileData);
string objectFile = Path.Combine(cacheDirectory, objectName + ".txt");
string incomingFile = Path.Combine(Path.Combine(cacheDirectory, "Incoming"), objectName + ".txt");
if (!File.Exists(objectFile))
{
File.WriteAllBytes(incomingFile, fileData);
File.Move(incomingFile, objectFile);
currentCacheSize += fileData.Length;
fileLengths[objectName] = fileData.Length;
fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime;
}
else
{
File.SetCreationTime(objectFile, DateTime.Now);
fileCreationTimes[objectName] = new FileInfo(objectFile).CreationTime;
}
}
public byte[] GetFromCache(string objectName)
{
string objectFile = Path.Combine(cacheDirectory, objectName + ".txt");
if (File.Exists(objectFile))
{
return File.ReadAllBytes(objectFile);
}
else
{
throw new IOException("Cached object " + objectName + " does not exist");
}
}
public void DeleteCache()
{
DarkLog.Debug("Deleting cache!");
foreach (string cacheFile in GetCachedFiles())
{
File.Delete(cacheFile);
}
fileLengths = new Dictionary<string, long>();
fileCreationTimes = new Dictionary<string, DateTime>();
currentCacheSize = 0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.X509Certificates.Asn1;
namespace Internal.Cryptography.Pal
{
internal sealed class CertificatePolicy
{
public bool ImplicitAnyCertificatePolicy { get; set; }
public bool SpecifiedAnyCertificatePolicy { get; set; }
public ISet<string> DeclaredCertificatePolicies { get; set; }
public bool ImplicitAnyApplicationPolicy { get; set; }
public bool SpecifiedAnyApplicationPolicy { get; set; }
public ISet<string> DeclaredApplicationPolicies { get; set; }
public int? InhibitAnyDepth { get; set; }
public List<CertificatePolicyMappingAsn> PolicyMapping { get; set; }
public int? InhibitMappingDepth { get; set; }
public int? RequireExplicitPolicyDepth { get; set; }
public bool AllowsAnyCertificatePolicy
{
get { return ImplicitAnyCertificatePolicy || SpecifiedAnyCertificatePolicy; }
}
public bool AllowsAnyApplicationPolicy
{
get { return ImplicitAnyApplicationPolicy || SpecifiedAnyApplicationPolicy; }
}
}
internal sealed class CertificatePolicyChain
{
private readonly CertificatePolicy[] _policies;
private bool _failAllCertificatePolicies;
public CertificatePolicyChain(List<X509Certificate2> chain)
{
_policies = new CertificatePolicy[chain.Count];
ReadPolicies(chain);
}
internal bool MatchesCertificatePolicies(OidCollection policyOids)
{
foreach (Oid oid in policyOids)
{
if (!MatchesCertificatePolicies(oid))
{
return false;
}
}
return true;
}
internal bool MatchesCertificatePolicies(Oid policyOid)
{
if (_failAllCertificatePolicies)
{
return false;
}
string nextOid = policyOid.Value;
for (int i = 1; i <= _policies.Length; i++)
{
// The loop variable (i) matches the definition in RFC 3280,
// section 6.1.3. In that description i=1 is the root CA, and n
// is the EE/leaf certificate. In our chain object 0 is the EE cert
// and _policies.Length-1 is the root cert. So we will index things as
// _policies.Length - i (because i is 1 indexed).
int dataIdx = _policies.Length - i;
CertificatePolicy policy = _policies[dataIdx];
string oidToCheck = nextOid;
if (policy.PolicyMapping != null)
{
for (int iMapping = 0; iMapping < policy.PolicyMapping.Count; iMapping++)
{
CertificatePolicyMappingAsn mapping = policy.PolicyMapping[iMapping];
if (StringComparer.Ordinal.Equals(mapping.IssuerDomainPolicy, oidToCheck))
{
nextOid = mapping.SubjectDomainPolicy;
}
}
}
if (policy.AllowsAnyCertificatePolicy)
{
continue;
}
if (policy.DeclaredCertificatePolicies == null)
{
return false;
}
if (!policy.DeclaredCertificatePolicies.Contains(oidToCheck))
{
return false;
}
}
return true;
}
internal bool MatchesApplicationPolicies(OidCollection policyOids)
{
foreach (Oid oid in policyOids)
{
if (!MatchesApplicationPolicies(oid))
{
return false;
}
}
return true;
}
internal bool MatchesApplicationPolicies(Oid policyOid)
{
string oidToCheck = policyOid.Value;
for (int i = 1; i <= _policies.Length; i++)
{
// The loop variable (i) matches the definition in RFC 3280,
// section 6.1.3. In that description i=1 is the root CA, and n
// is the EE/leaf certificate. In our chain object 0 is the EE cert
// and _policies.Length-1 is the root cert. So we will index things as
// _policies.Length - i (because i is 1 indexed).
int dataIdx = _policies.Length - i;
CertificatePolicy policy = _policies[dataIdx];
if (policy.AllowsAnyApplicationPolicy)
{
continue;
}
if (policy.DeclaredApplicationPolicies == null)
{
return false;
}
if (!policy.DeclaredApplicationPolicies.Contains(oidToCheck))
{
return false;
}
}
return true;
}
private void ReadPolicies(List<X509Certificate2> chain)
{
for (int i = 0; i < chain.Count; i++)
{
_policies[i] = ReadPolicy(chain[i]);
}
int explicitPolicyDepth = chain.Count;
int inhibitAnyPolicyDepth = explicitPolicyDepth;
int inhibitPolicyMappingDepth = explicitPolicyDepth;
for (int i = 1; i <= chain.Count; i++)
{
// The loop variable (i) matches the definition in RFC 3280,
// section 6.1.3. In that description i=1 is the root CA, and n
// is the EE/leaf certificate. In our chain object 0 is the EE cert
// and chain.Count-1 is the root cert. So we will index things as
// chain.Count - i (because i is 1 indexed).
int dataIdx = chain.Count - i;
CertificatePolicy policy = _policies[dataIdx];
if (policy.DeclaredCertificatePolicies == null && explicitPolicyDepth <= 0)
{
_failAllCertificatePolicies = true;
}
if (inhibitAnyPolicyDepth <= 0)
{
policy.ImplicitAnyCertificatePolicy = false;
policy.SpecifiedAnyCertificatePolicy = false;
}
else
{
inhibitAnyPolicyDepth--;
}
if (inhibitPolicyMappingDepth <= 0)
{
policy.PolicyMapping = null;
}
else
{
inhibitAnyPolicyDepth--;
}
if (explicitPolicyDepth <= 0)
{
policy.ImplicitAnyCertificatePolicy = false;
policy.ImplicitAnyApplicationPolicy = false;
}
else
{
explicitPolicyDepth--;
}
ApplyRestriction(ref inhibitAnyPolicyDepth, policy.InhibitAnyDepth);
ApplyRestriction(ref inhibitPolicyMappingDepth, policy.InhibitMappingDepth);
ApplyRestriction(ref explicitPolicyDepth, policy.RequireExplicitPolicyDepth);
}
}
private static void ApplyRestriction(ref int restriction, int? policyRestriction)
{
if (policyRestriction.HasValue)
{
restriction = Math.Min(restriction, policyRestriction.Value);
}
}
private static CertificatePolicy ReadPolicy(X509Certificate2 cert)
{
// If no ApplicationCertPolicies extension is provided then it uses the EKU
// OIDS.
ISet<string> applicationCertPolicies = null;
ISet<string> ekus = null;
CertificatePolicy policy = new CertificatePolicy();
foreach (X509Extension extension in cert.Extensions)
{
switch (extension.Oid.Value)
{
case Oids.ApplicationCertPolicies:
applicationCertPolicies = ReadCertPolicyExtension(extension);
break;
case Oids.CertPolicies:
policy.DeclaredCertificatePolicies = ReadCertPolicyExtension(extension);
break;
case Oids.CertPolicyMappings:
policy.PolicyMapping = ReadCertPolicyMappingsExtension(extension);
break;
case Oids.CertPolicyConstraints:
ReadCertPolicyConstraintsExtension(extension, policy);
break;
case Oids.EnhancedKeyUsage:
if (applicationCertPolicies == null)
{
// No reason to do this if the applicationCertPolicies was already read
ekus = ReadExtendedKeyUsageExtension(extension);
}
break;
case Oids.InhibitAnyPolicyExtension:
policy.InhibitAnyDepth = ReadInhibitAnyPolicyExtension(extension);
break;
}
}
policy.DeclaredApplicationPolicies = applicationCertPolicies ?? ekus;
policy.ImplicitAnyApplicationPolicy = policy.DeclaredApplicationPolicies == null;
policy.ImplicitAnyCertificatePolicy = policy.DeclaredCertificatePolicies == null;
policy.SpecifiedAnyApplicationPolicy = CheckExplicitAnyPolicy(policy.DeclaredApplicationPolicies);
policy.SpecifiedAnyCertificatePolicy = CheckExplicitAnyPolicy(policy.DeclaredCertificatePolicies);
return policy;
}
private static bool CheckExplicitAnyPolicy(ISet<string> declaredPolicies)
{
if (declaredPolicies == null)
{
return false;
}
return declaredPolicies.Remove(Oids.AnyCertPolicy);
}
private static int ReadInhibitAnyPolicyExtension(X509Extension extension)
{
AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER);
int inhibitAnyPolicy;
reader.TryReadInt32(out inhibitAnyPolicy);
reader.ThrowIfNotEmpty();
return inhibitAnyPolicy;
}
private static void ReadCertPolicyConstraintsExtension(X509Extension extension, CertificatePolicy policy)
{
PolicyConstraintsAsn constraints = PolicyConstraintsAsn.Decode(
extension.RawData,
AsnEncodingRules.DER);
policy.RequireExplicitPolicyDepth = constraints.RequireExplicitPolicyDepth;
policy.InhibitMappingDepth = constraints.InhibitMappingDepth;
}
private static ISet<string> ReadExtendedKeyUsageExtension(X509Extension extension)
{
X509EnhancedKeyUsageExtension ekusExtension = (X509EnhancedKeyUsageExtension)extension;
HashSet<string> oids = new HashSet<string>();
foreach (Oid oid in ekusExtension.EnhancedKeyUsages)
{
oids.Add(oid.Value);
}
return oids;
}
internal static ISet<string> ReadCertPolicyExtension(X509Extension extension)
{
AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER);
AsnReader sequenceReader = reader.ReadSequence();
reader.ThrowIfNotEmpty();
HashSet<string> policies = new HashSet<string>();
while (sequenceReader.HasData)
{
PolicyInformationAsn.Decode(sequenceReader, out PolicyInformationAsn policyInformation);
policies.Add(policyInformation.PolicyIdentifier);
// There is an optional policy qualifier here, but it is for information
// purposes, there is no logic that would be changed.
// Since reader (the outer one) has already skipped past the rest of the
// sequence we don't particularly need to drain out here.
}
return policies;
}
private static List<CertificatePolicyMappingAsn> ReadCertPolicyMappingsExtension(X509Extension extension)
{
AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER);
AsnReader sequenceReader = reader.ReadSequence();
reader.ThrowIfNotEmpty();
List<CertificatePolicyMappingAsn> mappings = new List<CertificatePolicyMappingAsn>();
while (sequenceReader.HasData)
{
CertificatePolicyMappingAsn.Decode(sequenceReader, out CertificatePolicyMappingAsn mapping);
mappings.Add(mapping);
}
return mappings;
}
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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 System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows.Input;
using SpatialAnalysis.Visualization;
using SpatialAnalysis.CellularEnvironment;
using SpatialAnalysis.Geometry;
namespace SpatialAnalysis.IsovistUtility.IsovistVisualization
{
/// <summary>
/// Visualize polygonal isovists
/// </summary>
public class PolygonalIsovistVisualHost : FrameworkElement
{
private OSMDocument _host { get; set; }
private double boarderThickness { get; set; }
private Brush boarderBrush { get; set; }
private Brush fillBrush { get; set; }
private Brush centerBrush { get; set; }
private double centerSize { get; set; }
private MenuItem visualization_Menu { get; set; }
private MenuItem hide_Show_Menu { get; set; }
private MenuItem boarderThickness_Menu { get; set; }
private MenuItem boarderBrush_Menu { get; set; }
private MenuItem fillBrush_Menu { get; set; }
private MenuItem centerBrush_Menu { get; set; }
private MenuItem centerSize_Menu { get; set; }
private MenuItem clear_Menu { get; set; }
private MenuItem getIsovist_Menu { get; set; }
private List<IsovistPolygon> _isovistPolygons;
// Create a collection of child visual objects.
private VisualCollection _children;
/// <summary>
/// Initializes a new instance of the <see cref="PolygonalIsovistVisualHost"/> class.
/// </summary>
public PolygonalIsovistVisualHost()
{
_isovistPolygons = new List<IsovistPolygon>();
_children = new VisualCollection(this);
this.fillBrush = Brushes.Khaki.Clone();
this.fillBrush.Opacity = .6;
this.centerSize = 3;
this.centerBrush = Brushes.DarkRed;
this.boarderThickness = 1;
this.boarderBrush = Brushes.Black;
this.visualization_Menu = new MenuItem() { Header = "Polygonal Isovist" };
this.boarderBrush_Menu = new MenuItem() { Header = "Boarder Brush" };
this.boarderThickness_Menu = new MenuItem() { Header = "Boarder Thickness" };
this.fillBrush_Menu = new MenuItem() { Header = "Fill Brush" };
this.hide_Show_Menu = new MenuItem() { Header = "Hide" };
this.centerSize_Menu = new MenuItem() { Header = "Center Size" };
this.centerBrush_Menu = new MenuItem() { Header = "Center Brush" };
this.clear_Menu = new MenuItem() { Header = "Clear Isovists" };
this.getIsovist_Menu = new MenuItem() { Header = "Get Polygonal Isovist" };
this.visualization_Menu.Items.Add(this.getIsovist_Menu);
this.visualization_Menu.Items.Add(this.hide_Show_Menu);
this.visualization_Menu.Items.Add(this.boarderThickness_Menu);
this.visualization_Menu.Items.Add(this.fillBrush_Menu);
this.visualization_Menu.Items.Add(this.boarderBrush_Menu);
this.visualization_Menu.Items.Add(this.centerBrush_Menu);
this.visualization_Menu.Items.Add(this.centerSize_Menu);
this.visualization_Menu.Items.Add(this.clear_Menu);
this.getIsovist_Menu.Click += new RoutedEventHandler(getPolygonalIsovist_Click);
this.boarderThickness_Menu.Click += new RoutedEventHandler(boarderThickness_Menu_Click);
this.fillBrush_Menu.Click += new RoutedEventHandler(fillBrush_Menu_Click);
this.boarderBrush_Menu.Click += new RoutedEventHandler(boarderBrush_Menu_Click);
this.hide_Show_Menu.Click += new RoutedEventHandler(hide_Show_Menu_Click);
this.centerSize_Menu.Click += new RoutedEventHandler(centerSize_Menu_Click);
this.centerBrush_Menu.Click += new RoutedEventHandler(centerBrush_Menu_Click);
this.clear_Menu.Click += new RoutedEventHandler(clear_Menu_Click);
}
#region polygonal isovist
private void drawInRevit()
{
var timer = new System.Diagnostics.Stopwatch();
this._host.Hide();
UV p = this._host.OSM_to_BIM.PickPoint("Pick a vantage point to draw polygonal Isovist");
Cell cell = this._host.cellularFloor.FindCell(p);
if (cell == null)
{
MessageBox.Show("Pick a point on the walkable field and try again!\n");
this._host.ShowDialog();
return;
}
switch (this._host.IsovistBarrierType)
{
case BarrierType.Visual:
if (cell.VisualOverlapState != OverlapState.Outside)
{
MessageBox.Show("Pick a point outside visual barriers.\nTry again!");
this._host.ShowDialog();
return;
}
break;
case BarrierType.Physical:
if (cell.PhysicalOverlapState != OverlapState.Outside)
{
MessageBox.Show("Pick a point outside physical barriers.\nTry again!");
this._host.ShowDialog();
return;
}
break;
case BarrierType.Field:
if (cell.FieldOverlapState != OverlapState.Inside)
{
MessageBox.Show("Pick a point inside the walkable field.\nTry again!");
this._host.ShowDialog();
return;
}
break;
case BarrierType.BarrierBuffer:
if (cell.BarrierBufferOverlapState != OverlapState.Outside)
{
MessageBox.Show("Pick a point outside barrier buffers.\nTry again!");
this._host.ShowDialog();
return;
}
break;
default:
break;
}
try
{
timer.Start();
HashSet<UVLine> blocks = this._host.cellularFloor.PolygonalIsovistVisualObstacles(p, this._host.IsovistDepth, this._host.IsovistBarrierType);
BarrierPolygon isovistPolygon = this._host.BIM_To_OSM.IsovistPolygon(p, this._host.IsovistDepth, blocks);
timer.Stop();
isovistPolygon.Visualize(this._host.OSM_to_BIM, this._host.BIM_To_OSM.PlanElevation);
this._host.IsovistInformation = new IsovistInformation(IsovistInformation.IsovistType.Polygonal,
timer.Elapsed.TotalMilliseconds, isovistPolygon.GetArea(), isovistPolygon.GetPerimeter());
}
catch (Exception error0)
{
this._host.IsovistInformation = null;
MessageBox.Show(error0.Message);
}
timer = null;
this._host.ShowDialog();
}
private void getPolygonalIsovist_Click(object sender, RoutedEventArgs e)
{
this._host.IsovistInformation = null;
if (this._host.RevitEnv.IsChecked)
{
this.drawInRevit();
}
else
{
if (this.Visibility != System.Windows.Visibility.Visible)
{
this.hide_Show();
}
this._host.Menues.IsEnabled = false;
this._host.UIMessage.Text = "Click on your desired vantage point on screen";
this._host.UIMessage.Visibility = System.Windows.Visibility.Visible;
this._host.Cursor = Cursors.Pen;
this._host.FloorScene.MouseLeftButtonDown += mouseLeftButtonDown_GetPolygonalIsovist;
this._host.MouseBtn.MouseDown += releasePolygonalIsovistMode;
}
}
private void releasePolygonalIsovistMode(object sender, MouseButtonEventArgs e)
{
this._host.Menues.IsEnabled = true;
this._host.Cursor = Cursors.Arrow;
this._host.UIMessage.Visibility = System.Windows.Visibility.Hidden;
this._host.FloorScene.MouseLeftButtonDown -= mouseLeftButtonDown_GetPolygonalIsovist;
this._host.CommandReset.MouseDown -= releasePolygonalIsovistMode;
}
private void mouseLeftButtonDown_GetPolygonalIsovist(object sender, MouseButtonEventArgs e)
{
var point = this._host.InverseRenderTransform.Transform(Mouse.GetPosition(this._host.FloorScene));
UV p = new UV(point.X, point.Y);
Cell cell = this._host.cellularFloor.FindCell(p);
if (cell == null)
{
MessageBox.Show("Pick a point on the walkable field and try again!\n");
return;
}
switch (this._host.IsovistBarrierType)
{
case BarrierType.Visual:
if (cell.VisualOverlapState != OverlapState.Outside)
{
MessageBox.Show("Pick a point outside visual barriers.\nTry again!");
return;
}
break;
case BarrierType.Physical:
if (cell.PhysicalOverlapState != OverlapState.Outside)
{
MessageBox.Show("Pick a point outside physical barriers.\nTry again!");
return;
}
break;
case BarrierType.Field:
if (cell.FieldOverlapState != OverlapState.Inside)
{
MessageBox.Show("Pick a point inside the walkable field.\nTry again!");
return;
}
break;
case BarrierType.BarrierBuffer:
if (cell.BarrierBufferOverlapState != OverlapState.Outside)
{
MessageBox.Show("Pick a point outside barrier buffers.\nTry again!");
return;
}
break;
default:
break;
}
this._children.Clear();
var timer = new System.Diagnostics.Stopwatch();
try
{
timer.Start();
HashSet<UVLine> blocks = this._host.cellularFloor.PolygonalIsovistVisualObstacles(p, this._host.IsovistDepth, this._host.IsovistBarrierType);
BarrierPolygon isovistPolygon = this._host.BIM_To_OSM.IsovistPolygon(p, this._host.IsovistDepth, blocks);
IsovistPolygon newIsovistPolygon = new IsovistPolygon(isovistPolygon.BoundaryPoints, p);
timer.Stop();
this._host.IsovistInformation = new IsovistInformation(IsovistInformation.IsovistType.Polygonal,
timer.Elapsed.TotalMilliseconds, isovistPolygon.GetArea(), isovistPolygon.GetPerimeter());
this.draw(newIsovistPolygon);
}
catch (Exception error0)
{
this._host.IsovistInformation = null;
MessageBox.Show(error0.Message);
}
timer = null;
}
#endregion
private void clear_Menu_Click(object sender, RoutedEventArgs e)
{
this._children.Clear();
this._isovistPolygons.Clear();
}
/// <summary>
/// Clears this instance.
/// </summary>
public void Clear()
{
this._host = null;
this.visualization_Menu.Items.Clear();
this.visualization_Menu = null;
this.getIsovist_Menu.Click -= getPolygonalIsovist_Click;
this.boarderThickness_Menu.Click -= boarderThickness_Menu_Click;
this.fillBrush_Menu.Click -= fillBrush_Menu_Click;
this.boarderBrush_Menu.Click -= boarderBrush_Menu_Click;
this.hide_Show_Menu.Click -= hide_Show_Menu_Click;
this.centerSize_Menu.Click -= centerSize_Menu_Click;
this.centerBrush_Menu.Click -= centerBrush_Menu_Click;
this.clear_Menu.Click -= clear_Menu_Click;
this._isovistPolygons.Clear();
this._children.Clear();
this.boarderBrush = null;
this.fillBrush = null;
this.centerBrush = null;
this.visualization_Menu = null;
this.hide_Show_Menu = null;
this.boarderThickness_Menu = null;
this.boarderBrush_Menu = null;
this.fillBrush_Menu = null;
this.centerBrush_Menu = null;
this.centerSize_Menu = null;
this.clear_Menu = null;
this.getIsovist_Menu = null;
this._isovistPolygons = null;
this._children = null;
}
private void centerBrush_Menu_Click(object sender, RoutedEventArgs e)
{
BrushPicker colorPicker = new BrushPicker(this.centerBrush);
colorPicker.Owner = this._host;
colorPicker.ShowDialog();
this.centerBrush = colorPicker._Brush;
this.redraw();
colorPicker = null;
}
private void centerSize_Menu_Click(object sender, RoutedEventArgs e)
{
GetNumber gn = new GetNumber("Enter New Center Size", "New square size will be applied to the edges of Isovists", this.centerSize);
gn.Owner = this._host;
gn.ShowDialog();
this.centerSize = gn.NumberValue;
this.redraw();
gn = null;
}
private void hide_Show()
{
if (this.Visibility == System.Windows.Visibility.Visible)
{
this.Visibility = System.Windows.Visibility.Collapsed;
this.hide_Show_Menu.Header = "Show";
this.boarderBrush_Menu.IsEnabled = false;
this.fillBrush_Menu.IsEnabled = false;
this.boarderThickness_Menu.IsEnabled = false;
this.clear_Menu.IsEnabled = false;
this.centerSize_Menu.IsEnabled = false;
this.centerBrush_Menu.IsEnabled = false;
}
else
{
this.Visibility = System.Windows.Visibility.Visible;
this.hide_Show_Menu.Header = "Hide";
this.boarderBrush_Menu.IsEnabled = true;
this.fillBrush_Menu.IsEnabled = true;
this.boarderThickness_Menu.IsEnabled = true;
this.clear_Menu.IsEnabled = true;
this.centerSize_Menu.IsEnabled = true;
this.centerBrush_Menu.IsEnabled = true;
}
}
private void hide_Show_Menu_Click(object sender, RoutedEventArgs e)
{
this.hide_Show();
}
private void boarderBrush_Menu_Click(object sender, RoutedEventArgs e)
{
BrushPicker colorPicker = new BrushPicker(this.boarderBrush);
colorPicker.Owner = this._host;
colorPicker.ShowDialog();
this.boarderBrush = colorPicker._Brush;
this.redraw();
colorPicker = null;
}
private void fillBrush_Menu_Click(object sender, RoutedEventArgs e)
{
BrushPicker colorPicker = new BrushPicker(this.fillBrush);
colorPicker.Owner = this._host;
colorPicker.ShowDialog();
this.fillBrush = colorPicker._Brush;
this.redraw();
colorPicker = null;
}
private void boarderThickness_Menu_Click(object sender, RoutedEventArgs e)
{
GetNumber gn = new GetNumber("Enter New Thickness Value", "New thickness value will be applied to the edges of Isovist", this.boarderThickness);
gn.Owner = this._host;
gn.ShowDialog();
this.boarderThickness = gn.NumberValue;
this.redraw();
gn = null;
}
// Provide a required override for the VisualChildrenCount property.
protected override int VisualChildrenCount
{
get { return _children.Count; }
}
// Provide a required override for the GetVisualChild method.
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index >= _children.Count)
{
throw new ArgumentOutOfRangeException();
}
return _children[index];
}
private double getScaleFactor()
{
double scale = this.RenderTransform.Value.M11 * this.RenderTransform.Value.M11 +
this.RenderTransform.Value.M12 * this.RenderTransform.Value.M12;
return Math.Sqrt(scale);
}
private void draw(IsovistPolygon isovistPolygon)
{
double scale = this.getScaleFactor();
this._isovistPolygons.Add(isovistPolygon);
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
StreamGeometry sg = new StreamGeometry();
using (StreamGeometryContext sgc = sg.Open())
{
sgc.BeginFigure(this.toPoint(isovistPolygon.BoundaryPoints[0]), true, true);
for (int i = 1; i < isovistPolygon.BoundaryPoints.Length; i++)
{
sgc.LineTo(this.toPoint(isovistPolygon.BoundaryPoints[i]), true, true);
}
}
sg.Freeze();
drawingContext.DrawGeometry(this.fillBrush, new Pen(this.boarderBrush, this.boarderThickness / scale), sg);
Point center = this.toPoint(isovistPolygon.VantagePoint);
var p1 = new Point(center.X - this.centerSize / (2 * scale), center.Y);
var p2 = new Point(center.X + this.centerSize / (2 * scale), center.Y);
drawingContext.DrawLine(new Pen(this.centerBrush, this.centerSize / scale), p1, p2);
}
drawingVisual.Drawing.Freeze();
this._children.Add(drawingVisual);
}
private void redraw()
{
this._children.Clear();
double scale = this.getScaleFactor();
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
StreamGeometry sg1 = new StreamGeometry();
using (StreamGeometryContext sgc1 = sg1.Open())
{
foreach (IsovistPolygon isovistPolygon in this._isovistPolygons)
{
sgc1.BeginFigure(this.toPoint(isovistPolygon.BoundaryPoints[0]), true, true);
for (int i = 1; i < isovistPolygon.BoundaryPoints.Length; i++)
{
sgc1.LineTo(this.toPoint(isovistPolygon.BoundaryPoints[i]), true, true);
}
}
}
sg1.FillRule = FillRule.Nonzero;
sg1.Freeze();
drawingContext.DrawGeometry(this.fillBrush, new Pen(this.boarderBrush, this.boarderThickness / scale), sg1);
Pen p_Center = new Pen(this.centerBrush, this.centerSize / scale);
foreach (IsovistPolygon isovistPolygon in this._isovistPolygons)
{
Point center = this.toPoint(isovistPolygon.VantagePoint);
var p1 = new Point(center.X - this.centerSize / (2 * scale), center.Y);
var p2 = new Point(center.X + this.centerSize / (2 * scale), center.Y);
drawingContext.DrawLine(p_Center, p1, p2);
}
}
drawingVisual.Drawing.Freeze();
this._children.Add(drawingVisual);
}
private Point toPoint(UV uv)
{
return new Point(uv.U, uv.V);
}
/// <summary>
/// Sets the host.
/// </summary>
/// <param name="host">The main document to which this control belongs.</param>
public void SetHost(OSMDocument host)
{
this._host = host;
this.RenderTransform = this._host.RenderTransformation;
this._host.IsovistMenu.Items.Insert(2, this.visualization_Menu);
}
}
}
| |
#region OMIT_COMPILEOPTION_DIAGS
#if !OMIT_COMPILEOPTION_DIAGS
using System;
namespace Core
{
public partial class CompileTime
{
static string[] _compileOpt = {
#if _32BIT_ROWID
"32BIT_ROWID",
#endif
#if _4_BYTE_ALIGNED_MALLOC
"4_BYTE_ALIGNED_MALLOC",
#endif
#if CASE_SENSITIVE_LIKE
"CASE_SENSITIVE_LIKE",
#endif
#if CHECK_PAGES
"CHECK_PAGES",
#endif
#if COVERAGE_TEST
"COVERAGE_TEST",
#endif
#if DEBUG
"DEBUG",
#endif
#if DEFAULT_LOCKING_MODE
"DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(DEFAULT_LOCKING_MODE),
#endif
#if DISABLE_DIRSYNC
"DISABLE_DIRSYNC",
#endif
#if DISABLE_LFS
"DISABLE_LFS",
#endif
#if ENABLE_ATOMIC_WRITE
"ENABLE_ATOMIC_WRITE",
#endif
#if ENABLE_CEROD
"ENABLE_CEROD",
#endif
#if ENABLE_COLUMN_METADATA
"ENABLE_COLUMN_METADATA",
#endif
#if ENABLE_EXPENSIVE_ASSERT
"ENABLE_EXPENSIVE_ASSERT",
#endif
#if ENABLE_FTS1
"ENABLE_FTS1",
#endif
#if ENABLE_FTS2
"ENABLE_FTS2",
#endif
#if ENABLE_FTS3
"ENABLE_FTS3",
#endif
#if ENABLE_FTS3_PARENTHESIS
"ENABLE_FTS3_PARENTHESIS",
#endif
#if ENABLE_FTS4
"ENABLE_FTS4",
#endif
#if ENABLE_ICU
"ENABLE_ICU",
#endif
#if ENABLE_IOTRACE
"ENABLE_IOTRACE",
#endif
#if ENABLE_LOAD_EXTENSION
"ENABLE_LOAD_EXTENSION",
#endif
#if ENABLE_LOCKING_STYLE
"ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(ENABLE_LOCKING_STYLE),
#endif
#if ENABLE_MEMORY_MANAGEMENT
"ENABLE_MEMORY_MANAGEMENT",
#endif
#if ENABLE_MEMSYS3
"ENABLE_MEMSYS3",
#endif
#if ENABLE_MEMSYS5
"ENABLE_MEMSYS5",
#endif
#if ENABLE_OVERSIZE_CELL_CHECK
"ENABLE_OVERSIZE_CELL_CHECK",
#endif
#if ENABLE_RTREE
"ENABLE_RTREE",
#endif
#if ENABLE_STAT2
"ENABLE_STAT2",
#endif
#if ENABLE_UNLOCK_NOTIFY
"ENABLE_UNLOCK_NOTIFY",
#endif
#if ENABLE_UPDATE_DELETE_LIMIT
"ENABLE_UPDATE_DELETE_LIMIT",
#endif
#if HAS_CODEC
"HAS_CODEC",
#endif
#if HAVE_ISNAN
"HAVE_ISNAN",
#endif
#if HOMEGROWN_RECURSIVE_MUTEX
"HOMEGROWN_RECURSIVE_MUTEX",
#endif
#if IGNORE_AFP_LOCK_ERRORS
"IGNORE_AFP_LOCK_ERRORS",
#endif
#if IGNORE_FLOCK_LOCK_ERRORS
"IGNORE_FLOCK_LOCK_ERRORS",
#endif
#if INT64_TYPE
"INT64_TYPE",
#endif
#if LOCK_TRACE
"LOCK_TRACE",
#endif
#if MEMDEBUG
"MEMDEBUG",
#endif
#if MIXED_ENDIAN_64BIT_FLOAT
"MIXED_ENDIAN_64BIT_FLOAT",
#endif
#if NO_SYNC
"NO_SYNC",
#endif
#if OMIT_ALTERTABLE
"OMIT_ALTERTABLE",
#endif
#if OMIT_ANALYZE
"OMIT_ANALYZE",
#endif
#if OMIT_ATTACH
"OMIT_ATTACH",
#endif
#if OMIT_AUTHORIZATION
"OMIT_AUTHORIZATION",
#endif
#if OMIT_AUTOINCREMENT
"OMIT_AUTOINCREMENT",
#endif
#if OMIT_AUTOINIT
"OMIT_AUTOINIT",
#endif
#if OMIT_AUTOMATIC_INDEX
"OMIT_AUTOMATIC_INDEX",
#endif
#if OMIT_AUTORESET
"OMIT_AUTORESET",
#endif
#if OMIT_AUTOVACUUM
"OMIT_AUTOVACUUM",
#endif
#if OMIT_BETWEEN_OPTIMIZATION
"OMIT_BETWEEN_OPTIMIZATION",
#endif
#if OMIT_BLOB_LITERAL
"OMIT_BLOB_LITERAL",
#endif
#if OMIT_BTREECOUNT
"OMIT_BTREECOUNT",
#endif
#if OMIT_BUILTIN_TEST
"OMIT_BUILTIN_TEST",
#endif
#if OMIT_CAST
"OMIT_CAST",
#endif
#if OMIT_CHECK
"OMIT_CHECK",
#endif
/* // redundant
** #if OMIT_COMPILEOPTION_DIAGS
** "OMIT_COMPILEOPTION_DIAGS",
** #endif
*/
#if OMIT_COMPLETE
"OMIT_COMPLETE",
#endif
#if OMIT_COMPOUND_SELECT
"OMIT_COMPOUND_SELECT",
#endif
#if OMIT_DATETIME_FUNCS
"OMIT_DATETIME_FUNCS",
#endif
#if OMIT_DECLTYPE
"OMIT_DECLTYPE",
#endif
#if OMIT_DEPRECATED
"OMIT_DEPRECATED",
#endif
#if OMIT_DISKIO
"OMIT_DISKIO",
#endif
#if OMIT_EXPLAIN
"OMIT_EXPLAIN",
#endif
#if OMIT_FLAG_PRAGMAS
"OMIT_FLAG_PRAGMAS",
#endif
#if OMIT_FLOATING_POINT
"OMIT_FLOATING_POINT",
#endif
#if OMIT_FOREIGN_KEY
"OMIT_FOREIGN_KEY",
#endif
#if OMIT_GET_TABLE
"OMIT_GET_TABLE",
#endif
#if OMIT_INCRBLOB
"OMIT_INCRBLOB",
#endif
#if OMIT_INTEGRITY_CHECK
"OMIT_INTEGRITY_CHECK",
#endif
#if OMIT_LIKE_OPTIMIZATION
"OMIT_LIKE_OPTIMIZATION",
#endif
#if OMIT_LOAD_EXTENSION
"OMIT_LOAD_EXTENSION",
#endif
#if OMIT_LOCALTIME
"OMIT_LOCALTIME",
#endif
#if OMIT_LOOKASIDE
"OMIT_LOOKASIDE",
#endif
#if OMIT_MEMORYDB
"OMIT_MEMORYDB",
#endif
#if OMIT_OR_OPTIMIZATION
"OMIT_OR_OPTIMIZATION",
#endif
#if OMIT_PAGER_PRAGMAS
"OMIT_PAGER_PRAGMAS",
#endif
#if OMIT_PRAGMA
"OMIT_PRAGMA",
#endif
#if OMIT_PROGRESS_CALLBACK
"OMIT_PROGRESS_CALLBACK",
#endif
#if OMIT_QUICKBALANCE
"OMIT_QUICKBALANCE",
#endif
#if OMIT_REINDEX
"OMIT_REINDEX",
#endif
#if OMIT_SCHEMA_PRAGMAS
"OMIT_SCHEMA_PRAGMAS",
#endif
#if OMIT_SCHEMA_VERSION_PRAGMAS
"OMIT_SCHEMA_VERSION_PRAGMAS",
#endif
#if OMIT_SHARED_CACHE
"OMIT_SHARED_CACHE",
#endif
#if OMIT_SUBQUERY
"OMIT_SUBQUERY",
#endif
#if OMIT_TCL_VARIABLE
"OMIT_TCL_VARIABLE",
#endif
#if OMIT_TEMPDB
"OMIT_TEMPDB",
#endif
#if OMIT_TRACE
"OMIT_TRACE",
#endif
#if OMIT_TRIGGER
"OMIT_TRIGGER",
#endif
#if OMIT_TRUNCATE_OPTIMIZATION
"OMIT_TRUNCATE_OPTIMIZATION",
#endif
#if OMIT_UTF16
"OMIT_UTF16",
#endif
#if OMIT_VACUUM
"OMIT_VACUUM",
#endif
#if OMIT_VIEW
"OMIT_VIEW",
#endif
#if OMIT_VIRTUALTABLE
"OMIT_VIRTUALTABLE",
#endif
#if OMIT_WAL
"OMIT_WAL",
#endif
#if OMIT_WSD
"OMIT_WSD",
#endif
#if OMIT_XFER_OPT
"OMIT_XFER_OPT",
#endif
#if PERFORMANCE_TRACE
"PERFORMANCE_TRACE",
#endif
#if PROXY_DEBUG
"PROXY_DEBUG",
#endif
#if SECURE_DELETE
"SECURE_DELETE",
#endif
#if SMALL_STACK
"SMALL_STACK",
#endif
#if SOUNDEX
"SOUNDEX",
#endif
#if TCL
"TCL",
#endif
//#if TEMP_STORE
"TEMP_STORE=1",//CTIMEOPT_VAL(TEMP_STORE),
//#endif
#if TEST
"TEST",
#endif
#if THREADSAFE
"THREADSAFE=2", // For C#, hardcode to = 2 CTIMEOPT_VAL(THREADSAFE),
#else
"THREADSAFE=0", // For C#, hardcode to = 0
#endif
#if USE_ALLOCA
"USE_ALLOCA",
#endif
#if ZERO_MALLOC
"ZERO_MALLOC"
#endif
};
public static bool OptionUsed(string optName)
{
if (optName.EndsWith("=")) return false;
int length = 0;
if (optName.StartsWith("", StringComparison.InvariantCultureIgnoreCase)) length = 7;
// Since ArraySize(azCompileOpt) is normally in single digits, a linear search is adequate. No need for a binary search.
if (!string.IsNullOrEmpty(optName))
for (int i = 0; i < _compileOpt.Length; i++)
{
int n1 = (optName.Length - length < _compileOpt[i].Length) ? optName.Length - length : _compileOpt[i].Length;
if (string.Compare(optName, length, _compileOpt[i], 0, n1, StringComparison.InvariantCultureIgnoreCase) == 0)
return true;
}
return false;
}
public static string Get(int id)
{
return (id >= 0 && id < _compileOpt.Length ? _compileOpt[id] : null);
}
}
}
#endif
#endregion
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client;
[TestFixture]
[Category("group1")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientRegionInterestTests : ThinClientRegionSteps
{
#region Private members and methods
private UnitProcess m_client1, m_client2, m_client3, m_feeder;
private static string[] m_regexes = { "Key-*1", "Key-*2",
"Key-*3", "Key-*4" };
private const string m_regex23 = "Key-[23]";
private const string m_regexWildcard = "Key-.*";
private const int m_numUnicodeStrings = 5;
private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" };
private static string[] m_keysForRegex = {"key-regex-1",
"key-regex-2", "key-regex-3" };
private static string[] RegionNamesForInterestNotify =
{ "RegionTrue", "RegionFalse", "RegionOther" };
string GetUnicodeString(int index)
{
return new string('\x0905', 40) + index.ToString("D10");
}
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
m_feeder = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder };
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
m_client1.Call(DestroyRegions);
m_client2.Call(DestroyRegions);
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
#region Steps for Thin Client IRegion<object, object> with Interest
public void StepFourIL()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepFourRegex3()
{
IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
try
{
Util.Log("Registering empty regular expression.");
region0.GetSubscriptionService().RegisterRegex(string.Empty);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering null regular expression.");
region1.GetSubscriptionService().RegisterRegex(null);
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
try
{
Util.Log("Registering non-existent regular expression.");
region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
}
public void StepFourFailoverRegex()
{
VerifyCreated(m_regionNames[0], m_keys[0]);
VerifyCreated(m_regionNames[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true);
UnregisterRegexes(null, m_regexes[2]);
}
public void StepFiveIL()
{
VerifyCreated(m_regionNames[0], m_keys[1]);
VerifyCreated(m_regionNames[1], m_keys[3]);
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
}
public void StepFiveRegex()
{
CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]);
CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void CreateAllEntries(string regionName)
{
CreateEntry(regionName, m_keys[0], m_vals[0]);
CreateEntry(regionName, m_keys[1], m_vals[1]);
CreateEntry(regionName, m_keys[2], m_vals[2]);
CreateEntry(regionName, m_keys[3], m_vals[3]);
}
public void VerifyAllEntries(string regionName, bool newVal, bool checkVal)
{
string[] vals = newVal ? m_nvals : m_vals;
VerifyEntry(regionName, m_keys[0], vals[0], checkVal);
VerifyEntry(regionName, m_keys[1], vals[1], checkVal);
VerifyEntry(regionName, m_keys[2], vals[2], checkVal);
VerifyEntry(regionName, m_keys[3], vals[3], checkVal);
}
public void VerifyInvalidAll(string regionName, params string[] keys)
{
if (keys != null)
{
foreach (string key in keys)
{
VerifyInvalid(regionName, key);
}
}
}
public void UpdateAllEntries(string regionName, bool checkVal)
{
UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal);
UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal);
UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal);
UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal);
}
public void DoNetsearchAllEntries(string regionName, bool newVal,
bool checkNoKey)
{
string[] vals;
if (newVal)
{
vals = m_nvals;
}
else
{
vals = m_vals;
}
DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey);
DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey);
DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey);
DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey);
}
public void StepFiveFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false);
}
public void StepSixIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]);
IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]);
region0.Remove(m_keys[1]);
region1.Remove(m_keys[3]);
}
public void StepSixRegex()
{
CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]);
CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UnregisterRegexes(null, m_regexes[3]);
}
public void StepSixFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false);
}
public void StepSevenIL()
{
VerifyDestroyed(m_regionNames[0], m_keys[1]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
}
public void StepSevenRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true);
UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true);
UnregisterRegexes(null, m_regexes[1]);
}
public void StepSevenRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]);
DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true);
DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true);
UpdateAllEntries(m_regionNames[1], true);
}
public void StepSevenInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterRegex(m_regex23);
VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]);
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true);
}
public void StepSevenFailoverRegex()
{
UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true);
UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true);
VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]);
}
public void StepEightIL()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]);
}
public void StepEightRegex()
{
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]);
UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true);
UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true);
}
public void StepEightInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]);
region.GetSubscriptionService().RegisterAllKeys();
VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1],
m_keys[2], m_keys[3]);
UpdateAllEntries(m_regionNames[0], true);
}
public void StepEightFailoverRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]);
}
public void StepNineRegex()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]);
VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]);
}
public void StepNineRegex2()
{
VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]);
VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]);
VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]);
VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]);
}
public void StepNineInterestResultPolicyInv()
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().UnregisterRegex(m_regex23);
List<Object> keys = new List<Object>();
keys.Add(m_keys[0]);
keys.Add(m_keys[1]);
keys.Add(m_keys[2]);
region.GetSubscriptionService().RegisterKeys(keys);
VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]);
}
public void PutUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object val;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
val = index + 100;
}
else
{
val = (float)index + 20.0F;
}
region[key] = val;
}
}
public void RegisterUnicodeKeys(string regionName)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string[] keys = new string[m_numUnicodeStrings];
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index);
}
region.GetSubscriptionService().RegisterKeys(keys);
}
public void VerifyUnicodeKeys(string regionName, bool updates)
{
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName);
string key;
object expectedVal;
for (int index = 0; index < m_numUnicodeStrings; ++index)
{
key = GetUnicodeString(index);
if (updates)
{
expectedVal = index + 100;
Assert.AreEqual(expectedVal, region.GetEntry(key).Value,
"Got unexpected value");
}
else
{
expectedVal = (float)index + 20.0F;
Assert.AreEqual(expectedVal, region[key],
"Got unexpected value");
}
}
}
public void CreateRegionsInterestNotify_Pool(string[] regionNames,
string locators, string poolName, bool notify, string nbs)
{
Properties<string, string> props = Properties<string, string>.Create<string, string>();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true,
new TallyListener<object, object>(), locators, poolName, notify);
}
/*
public void CreateRegionsInterestNotify(string[] regionNames,
string endpoints, bool notify, string nbs)
{
Properties props = Properties.Create();
//props.Insert("notify-by-subscription-override", nbs);
CacheHelper.InitConfig(props);
CacheHelper.CreateTCRegion(regionNames[0], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[1], true, false,
new TallyListener(), endpoints, notify);
CacheHelper.CreateTCRegion(regionNames[2], true, false,
new TallyListener(), endpoints, notify);
}
* */
public void DoFeed()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "00";
}
foreach (string key in m_keysForRegex)
{
region[key] = "00";
}
}
}
public void DoFeederOps()
{
foreach (string regionName in RegionNamesForInterestNotify)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
foreach (string key in m_keysNonRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
foreach (string key in m_keysForRegex)
{
region[key] = "11";
region[key] = "22";
region[key] = "33";
region.GetLocalView().Invalidate(key);
region.Remove(key);
}
}
}
public void DoRegister()
{
DoRegisterInterests(RegionNamesForInterestNotify[0], true);
DoRegisterInterests(RegionNamesForInterestNotify[1], false);
// We intentionally do not register interest in Region3
//DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]);
}
public void DoRegisterInterests(string regionName, bool receiveValues)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues);
region.GetSubscriptionService().RegisterRegex("key-regex.*", false, null, false, receiveValues);
}
public void DoUnregister()
{
DoUnregisterInterests(RegionNamesForInterestNotify[0]);
DoUnregisterInterests(RegionNamesForInterestNotify[1]);
}
public void DoUnregisterInterests(string regionName)
{
List<string> keys = new List<string>();
foreach (string key in m_keysNonRegex)
{
keys.Add(key);
}
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
region.GetSubscriptionService().UnregisterKeys(keys.ToArray());
region.GetSubscriptionService().UnregisterRegex("key-regex.*");
}
public void DoValidation(string clientName, string regionName,
int creates, int updates, int invalidates, int destroys)
{
IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName);
TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>;
Util.Log(clientName + ": " + regionName + ": creates expected=" + creates +
", actual=" + listener.Creates);
Util.Log(clientName + ": " + regionName + ": updates expected=" + updates +
", actual=" + listener.Updates);
Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates +
", actual=" + listener.Invalidates);
Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys +
", actual=" + listener.Destroys);
Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName);
Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName);
Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName);
Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName);
}
#endregion
void runInterestList()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
m_client1.Call(RegisterKeys, m_keys[1], m_keys[3]);
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
m_client2.Call(RegisterKeys, m_keys[0], (string)null);
Util.Log("StepFour complete.");
m_client1.Call(StepFiveIL);
m_client1.Call(UnregisterKeys, (string)null, m_keys[3]);
Util.Log("StepFive complete.");
m_client2.Call(StepSixIL);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenIL);
Util.Log("StepSeven complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void RegisterKeysPdx()
{
Serializable.RegisterPdxType(PdxTests.PdxTypes1.CreateDeserializable);
Serializable.RegisterPdxType(PdxTests.PdxTypes8.CreateDeserializable);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region.GetSubscriptionService().RegisterAllKeys();
}
void StepThreePdx()
{
Serializable.RegisterPdxType(PdxTests.PdxTypes1.CreateDeserializable);
Serializable.RegisterPdxType(PdxTests.PdxTypes8.CreateDeserializable);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
region[1] = new PdxTests.PdxTypes8();
}
void StepFourPdx()
{
Thread.Sleep(2000);
IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]);
IRegion<object, object> regionLocal = region.GetLocalView();
object ret = regionLocal[1];
Assert.IsNotNull(ret);
Assert.IsTrue(ret is IPdxSerializable);
}
void runInterestListPdx()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client2.Call(RegisterKeysPdx);
m_client1.Call(StepThreePdx);
Util.Log("StepThreePdx complete.");
m_client2.Call(StepFourPdx);
Util.Log("StepFourPdx complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runInterestList2()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
m_client1.Call(RegisterAllKeys,
new string[] { RegionNames[0], RegionNames[1] });
Util.Log("StepThree complete.");
m_client2.Call(StepFour);
m_client2.Call(RegisterAllKeys, new string[] { RegionNames[0] });
Util.Log("StepFour complete.");
m_client1.Call(StepFiveIL);
m_client1.Call(UnregisterAllKeys, new string[] { RegionNames[1] });
Util.Log("StepFive complete.");
m_client2.Call(StepSixIL);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenIL);
Util.Log("StepSeven complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRegexInterest()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(RegisterRegexes, m_regexes[0], m_regexes[1]);
Util.Log("StepThree complete.");
m_client2.Call(RegisterRegexes, m_regexes[2], m_regexes[3]);
Util.Log("StepFour complete.");
m_client1.Call(StepFiveRegex);
Util.Log("StepFive complete.");
m_client2.Call(StepSixRegex);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenRegex);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightRegex);
Util.Log("StepEight complete.");
m_client1.Call(StepNineRegex);
Util.Log("StepNine complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRegexInterest2()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(RegisterRegexes, m_regex23, (string)null);
Util.Log("StepThree complete.");
m_client2.Call(RegisterRegexes, (string)null, m_regexWildcard);
Util.Log("StepFour complete.");
m_client1.Call(CreateAllEntries, RegionNames[1]);
Util.Log("StepFive complete.");
m_client2.Call(CreateAllEntries, RegionNames[0]);
m_client2.Call(VerifyAllEntries, RegionNames[1], false, false);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenRegex2);
m_client1.Call(UpdateAllEntries, RegionNames[1], true);
Util.Log("StepSeven complete.");
m_client2.Call(VerifyAllEntries, RegionNames[1], true, true);
m_client2.Call(UpdateAllEntries, RegionNames[0], true);
Util.Log("StepEight complete.");
m_client1.Call(StepNineRegex2);
Util.Log("StepNine complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runRegexInterest3()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
try
{
m_client1.Call(RegisterRegexes, "a*", "*[*2-[");
Assert.Fail("Did not get expected exception!");
}
catch (Exception ex)
{
Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message);
}
Util.Log("StepThree complete.");
m_client2.Call(StepFourRegex3);
Util.Log("StepFour complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runInterestResultPolicyInv()
{
CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client1.Call(CreateAllEntries, RegionNames[1]);
Util.Log("StepThree complete.");
m_client2.Call(CreateAllEntries, RegionNames[0]);
Util.Log("StepFour complete.");
m_client2.Call(DoNetsearchAllEntries, RegionNames[1], false, true);
Util.Log("StepFive complete.");
m_client1.Call(DoNetsearchAllEntries, RegionNames[0], false, true);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenInterestResultPolicyInv);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightInterestResultPolicyInv);
Util.Log("StepEight complete.");
m_client1.Call(StepNineInterestResultPolicyInv);
Util.Log("StepNine complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailoverInterest()
{
CacheHelper.SetupJavaServers( true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client2.Call(RegisterKeys, m_keys[0], m_keys[2]);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFourIL);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(StepFiveFailover);
Util.Log("StepFive complete.");
m_client2.Call(StepSixFailover);
Util.Log("StepSix complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailoverInterest2()
{
CacheHelper.SetupJavaServers(true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
Util.Log("StepTwo complete.");
m_client2.Call(RegisterAllKeys, RegionNames);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
Util.Log("StepThree complete.");
m_client2.Call(StepFourIL);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(StepFiveFailover);
Util.Log("StepFive complete.");
m_client2.Call(StepSixFailover);
Util.Log("StepSix complete.");
// Client2, unregister all keys
m_client2.Call(UnregisterAllKeys, RegionNames);
Util.Log("UnregisterAllKeys complete.");
m_client1.Call(StepSevenFailover);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightIL);
Util.Log("StepEight complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runFailoverRegexInterest()
{
CacheHelper.SetupJavaServers(true,
"cacheserver_notify_subscription.xml",
"cacheserver_notify_subscription2.xml");
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver 1 started.");
m_client1.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
m_client1.Call(CreateEntry, RegionNames[1], m_keys[1], m_vals[1]);
Util.Log("StepOne complete.");
m_client2.Call(CreateTCRegions_Pool, RegionNames,
CacheHelper.Locators, "__TESTPOOL1_", true);
m_client2.Call(CreateEntry, RegionNames[1], m_keys[1], m_nvals[1]);
m_client2.Call(RegisterRegexes, m_regexes[0], m_regexes[2]);
Util.Log("StepTwo complete.");
m_client1.Call(StepThree);
m_client1.Call(RegisterRegexes, (string)null, m_regexes[1]);
m_client1.Call(DoNetsearch, RegionNames[1],
m_keys[1], m_nvals[1], false);
Util.Log("StepThree complete.");
m_client2.Call(StepFourFailoverRegex);
Util.Log("StepFour complete.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver 1 stopped.");
m_client1.Call(StepFiveFailoverRegex);
Util.Log("StepFive complete.");
m_client2.Call(StepSixFailoverRegex);
Util.Log("StepSix complete.");
m_client1.Call(StepSevenFailoverRegex);
Util.Log("StepSeven complete.");
m_client2.Call(StepEightFailoverRegex);
Util.Log("StepEight complete.");
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
Util.Log("Cacheserver 2 stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runInterestNotify()
{
CacheHelper.SetupJavaServers(true,
"cacheserver_interest_notify.xml");
// start locator and server
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1);
Util.Log("Cacheserver started.");
// create feeder and 3 clients each with 3 regions and
// populate initial keys
m_feeder.Call(CreateRegionsInterestNotify_Pool, RegionNamesForInterestNotify,
CacheHelper.Locators, "__TESTPOOL1_", false, "server" /* nbs */);
m_feeder.Call(DoFeed);
m_client1.Call(CreateRegionsInterestNotify_Pool, RegionNamesForInterestNotify,
CacheHelper.Locators, "__TESTPOOL1_", true, "true" /* nbs */);
//m_client2.Call(CreateRegionsInterestNotify_Pool, RegionNamesForInterestNotify,
// CacheHelper.Locators, "__TESTPOOL1_", true, "false" /* nbs */);
//m_client3.Call(CreateRegionsInterestNotify_Pool, RegionNamesForInterestNotify,
// CacheHelper.Locators, "__TESTPOOL1_", true, "server" /* nbs */);
// Register interests and get initial values
m_client1.Call(DoRegister);
//m_client2.Call(DoRegister);
//m_client3.Call(DoRegister);
// Do ops while interest is registered
m_feeder.Call(DoFeederOps);
m_client1.Call(DoUnregister);
//m_client2.Call(DoUnregister);
//m_client3.Call(DoUnregister);
// Do ops while interest is no longer registered
m_feeder.Call(DoFeederOps);
m_client1.Call(DoRegister);
//m_client2.Call(DoRegister);
//m_client3.Call(DoRegister);
// Do ops while interest is re-registered
m_feeder.Call(DoFeederOps);
// Validate clients receive relevant expected event counts:
m_client1.Call(DoValidation, "Client1", RegionNamesForInterestNotify[0], 6, 30, 0, 12);
m_client1.Call(DoValidation, "Client1", RegionNamesForInterestNotify[1], 0, 0, 36, 12);
m_client1.Call(DoValidation, "Client1", RegionNamesForInterestNotify[2], 0, 0, 0, 0);
/*
m_client2.Call(DoValidation, "Client2", RegionNamesForInterestNotify[0], 0, 0, 54, 18);
m_client2.Call(DoValidation, "Client2", RegionNamesForInterestNotify[1], 0, 0, 54, 18);
m_client2.Call(DoValidation, "Client2", RegionNamesForInterestNotify[2], 0, 0, 54, 18);
m_client3.Call(DoValidation, "Client3", RegionNamesForInterestNotify[0], 0, 0, 54, 18);
m_client3.Call(DoValidation, "Client3", RegionNamesForInterestNotify[1], 0, 0, 54, 18);
m_client3.Call(DoValidation, "Client3", RegionNamesForInterestNotify[2], 0, 0, 54, 18);
* */
// close down
m_client1.Call(Close);
//m_client2.Call(Close);
//m_client3.Call(Close);
m_feeder.Call(Close);
CacheHelper.StopJavaServer(1);
Util.Log("Cacheserver stopped.");
CacheHelper.StopJavaLocator(1);
Util.Log("Locator stopped");
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
[Test]
public void InterestList()
{
runInterestList();
}
[Test]
public void InterestListWithPdx()
{
runInterestListPdx();
}
[Test]
public void InterestList2()
{
runInterestList2();
}
[Test]
public void RegexInterest()
{
runRegexInterest();
}
[Test]
public void RegexInterest2()
{
runRegexInterest2();
}
[Test]
public void RegexInterest3()
{
runRegexInterest3();
}
[Test]
public void InterestResultPolicyInv()
{
runInterestResultPolicyInv();
}
[Test]
public void FailoverInterest()
{
runFailoverInterest();
}
[Test]
public void FailoverInterest2()
{
runFailoverInterest2();
}
[Test]
public void FailoverRegexInterest()
{
runFailoverRegexInterest();
}
[Test]
public void InterestNotify()
{
runInterestNotify();
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using System.Text;
using SquabPie.Mono.Cecil.PE;
using RVA = System.UInt32;
#if !READ_ONLY
namespace SquabPie.Mono.Cecil.Metadata {
sealed class TableHeapBuffer : HeapBuffer {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
internal MetadataTable [] tables = new MetadataTable [45];
bool large_string;
bool large_blob;
readonly int [] coded_index_sizes = new int [13];
readonly Func<Table, int> counter;
public override bool IsEmpty {
get { return false; }
}
public TableHeapBuffer (ModuleDefinition module, MetadataBuilder metadata)
: base (24)
{
this.module = module;
this.metadata = metadata;
this.counter = GetTableLength;
}
int GetTableLength (Table table)
{
var md_table = tables [(int) table];
return md_table != null ? md_table.Length : 0;
}
public TTable GetTable<TTable> (Table table) where TTable : MetadataTable, new ()
{
var md_table = (TTable) tables [(int) table];
if (md_table != null)
return md_table;
md_table = new TTable ();
tables [(int) table] = md_table;
return md_table;
}
public void WriteBySize (uint value, int size)
{
if (size == 4)
WriteUInt32 (value);
else
WriteUInt16 ((ushort) value);
}
public void WriteBySize (uint value, bool large)
{
if (large)
WriteUInt32 (value);
else
WriteUInt16 ((ushort) value);
}
public void WriteString (uint @string)
{
WriteBySize (@string, large_string);
}
public void WriteBlob (uint blob)
{
WriteBySize (blob, large_blob);
}
public void WriteRID (uint rid, Table table)
{
var md_table = tables [(int) table];
WriteBySize (rid, md_table == null ? false : md_table.IsLarge);
}
int GetCodedIndexSize (CodedIndex coded_index)
{
var index = (int) coded_index;
var size = coded_index_sizes [index];
if (size != 0)
return size;
return coded_index_sizes [index] = coded_index.GetSize (counter);
}
public void WriteCodedRID (uint rid, CodedIndex coded_index)
{
WriteBySize (rid, GetCodedIndexSize (coded_index));
}
public void WriteTableHeap ()
{
WriteUInt32 (0); // Reserved
WriteByte (GetTableHeapVersion ()); // MajorVersion
WriteByte (0); // MinorVersion
WriteByte (GetHeapSizes ()); // HeapSizes
WriteByte (10); // Reserved2
WriteUInt64 (GetValid ()); // Valid
WriteUInt64 (0x0016003301fa00); // Sorted
WriteRowCount ();
WriteTables ();
}
void WriteRowCount ()
{
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
WriteUInt32 ((uint) table.Length);
}
}
void WriteTables ()
{
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
table.Write (this);
}
}
ulong GetValid ()
{
ulong valid = 0;
for (int i = 0; i < tables.Length; i++) {
var table = tables [i];
if (table == null || table.Length == 0)
continue;
table.Sort ();
valid |= (1UL << i);
}
return valid;
}
byte GetHeapSizes ()
{
byte heap_sizes = 0;
if (metadata.string_heap.IsLarge) {
large_string = true;
heap_sizes |= 0x01;
}
if (metadata.blob_heap.IsLarge) {
large_blob = true;
heap_sizes |= 0x04;
}
return heap_sizes;
}
byte GetTableHeapVersion ()
{
switch (module.Runtime) {
case TargetRuntime.Net_1_0:
case TargetRuntime.Net_1_1:
return 1;
default:
return 2;
}
}
public void FixupData (RVA data_rva)
{
var table = GetTable<FieldRVATable> (Table.FieldRVA);
if (table.length == 0)
return;
var field_idx_size = GetTable<FieldTable> (Table.Field).IsLarge ? 4 : 2;
var previous = this.position;
base.position = table.position;
for (int i = 0; i < table.length; i++) {
var rva = ReadUInt32 ();
base.position -= 4;
WriteUInt32 (rva + data_rva);
base.position += field_idx_size;
}
base.position = previous;
}
}
sealed class ResourceBuffer : ByteBuffer {
public ResourceBuffer ()
: base (0)
{
}
public uint AddResource (byte [] resource)
{
var offset = (uint) this.position;
WriteInt32 (resource.Length);
WriteBytes (resource);
return offset;
}
}
sealed class DataBuffer : ByteBuffer {
public DataBuffer ()
: base (0)
{
}
public RVA AddData (byte [] data)
{
var rva = (RVA) position;
WriteBytes (data);
return rva;
}
}
abstract class HeapBuffer : ByteBuffer {
public bool IsLarge {
get { return base.length > 65535; }
}
public abstract bool IsEmpty { get; }
protected HeapBuffer (int length)
: base (length)
{
}
}
class StringHeapBuffer : HeapBuffer {
readonly Dictionary<string, uint> strings = new Dictionary<string, uint> (StringComparer.Ordinal);
public sealed override bool IsEmpty {
get { return length <= 1; }
}
public StringHeapBuffer ()
: base (1)
{
WriteByte (0);
}
public uint GetStringIndex (string @string)
{
uint index;
if (strings.TryGetValue (@string, out index))
return index;
index = (uint) base.position;
WriteString (@string);
strings.Add (@string, index);
return index;
}
protected virtual void WriteString (string @string)
{
WriteBytes (Encoding.UTF8.GetBytes (@string));
WriteByte (0);
}
}
sealed class BlobHeapBuffer : HeapBuffer {
readonly Dictionary<ByteBuffer, uint> blobs = new Dictionary<ByteBuffer, uint> (new ByteBufferEqualityComparer ());
public override bool IsEmpty {
get { return length <= 1; }
}
public BlobHeapBuffer ()
: base (1)
{
WriteByte (0);
}
public uint GetBlobIndex (ByteBuffer blob)
{
uint index;
if (blobs.TryGetValue (blob, out index))
return index;
index = (uint) base.position;
WriteBlob (blob);
blobs.Add (blob, index);
return index;
}
void WriteBlob (ByteBuffer blob)
{
WriteCompressedUInt32 ((uint) blob.length);
WriteBytes (blob);
}
}
sealed class UserStringHeapBuffer : StringHeapBuffer {
protected override void WriteString (string @string)
{
WriteCompressedUInt32 ((uint) @string.Length * 2 + 1);
byte special = 0;
for (int i = 0; i < @string.Length; i++) {
var @char = @string [i];
WriteUInt16 (@char);
if (special == 1)
continue;
if (@char < 0x20 || @char > 0x7e) {
if (@char > 0x7e
|| (@char >= 0x01 && @char <= 0x08)
|| (@char >= 0x0e && @char <= 0x1f)
|| @char == 0x27
|| @char == 0x2d) {
special = 1;
}
}
}
WriteByte (special);
}
}
}
#endif
| |
namespace android.media
{
[global::MonoJavaBridge.JavaClass()]
public partial class MediaPlayer : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static MediaPlayer()
{
InitJNI();
}
protected MediaPlayer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnBufferingUpdateListener_))]
public interface OnBufferingUpdateListener : global::MonoJavaBridge.IJavaObject
{
void onBufferingUpdate(android.media.MediaPlayer arg0, int arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnBufferingUpdateListener))]
public sealed partial class OnBufferingUpdateListener_ : java.lang.Object, OnBufferingUpdateListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnBufferingUpdateListener_()
{
InitJNI();
}
internal OnBufferingUpdateListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onBufferingUpdate4981;
void android.media.MediaPlayer.OnBufferingUpdateListener.onBufferingUpdate(android.media.MediaPlayer arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnBufferingUpdateListener_._onBufferingUpdate4981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnBufferingUpdateListener_.staticClass, global::android.media.MediaPlayer.OnBufferingUpdateListener_._onBufferingUpdate4981, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnBufferingUpdateListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnBufferingUpdateListener"));
global::android.media.MediaPlayer.OnBufferingUpdateListener_._onBufferingUpdate4981 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnBufferingUpdateListener_.staticClass, "onBufferingUpdate", "(Landroid/media/MediaPlayer;I)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnCompletionListener_))]
public interface OnCompletionListener : global::MonoJavaBridge.IJavaObject
{
void onCompletion(android.media.MediaPlayer arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnCompletionListener))]
public sealed partial class OnCompletionListener_ : java.lang.Object, OnCompletionListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnCompletionListener_()
{
InitJNI();
}
internal OnCompletionListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onCompletion4982;
void android.media.MediaPlayer.OnCompletionListener.onCompletion(android.media.MediaPlayer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnCompletionListener_._onCompletion4982, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnCompletionListener_.staticClass, global::android.media.MediaPlayer.OnCompletionListener_._onCompletion4982, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnCompletionListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnCompletionListener"));
global::android.media.MediaPlayer.OnCompletionListener_._onCompletion4982 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnCompletionListener_.staticClass, "onCompletion", "(Landroid/media/MediaPlayer;)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnErrorListener_))]
public interface OnErrorListener : global::MonoJavaBridge.IJavaObject
{
bool onError(android.media.MediaPlayer arg0, int arg1, int arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnErrorListener))]
public sealed partial class OnErrorListener_ : java.lang.Object, OnErrorListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnErrorListener_()
{
InitJNI();
}
internal OnErrorListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onError4983;
bool android.media.MediaPlayer.OnErrorListener.onError(android.media.MediaPlayer arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer.OnErrorListener_._onError4983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer.OnErrorListener_.staticClass, global::android.media.MediaPlayer.OnErrorListener_._onError4983, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnErrorListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnErrorListener"));
global::android.media.MediaPlayer.OnErrorListener_._onError4983 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnErrorListener_.staticClass, "onError", "(Landroid/media/MediaPlayer;II)Z");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnInfoListener_))]
public interface OnInfoListener : global::MonoJavaBridge.IJavaObject
{
bool onInfo(android.media.MediaPlayer arg0, int arg1, int arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnInfoListener))]
public sealed partial class OnInfoListener_ : java.lang.Object, OnInfoListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnInfoListener_()
{
InitJNI();
}
internal OnInfoListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onInfo4984;
bool android.media.MediaPlayer.OnInfoListener.onInfo(android.media.MediaPlayer arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer.OnInfoListener_._onInfo4984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer.OnInfoListener_.staticClass, global::android.media.MediaPlayer.OnInfoListener_._onInfo4984, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnInfoListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnInfoListener"));
global::android.media.MediaPlayer.OnInfoListener_._onInfo4984 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnInfoListener_.staticClass, "onInfo", "(Landroid/media/MediaPlayer;II)Z");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnPreparedListener_))]
public interface OnPreparedListener : global::MonoJavaBridge.IJavaObject
{
void onPrepared(android.media.MediaPlayer arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnPreparedListener))]
public sealed partial class OnPreparedListener_ : java.lang.Object, OnPreparedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnPreparedListener_()
{
InitJNI();
}
internal OnPreparedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onPrepared4985;
void android.media.MediaPlayer.OnPreparedListener.onPrepared(android.media.MediaPlayer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnPreparedListener_._onPrepared4985, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnPreparedListener_.staticClass, global::android.media.MediaPlayer.OnPreparedListener_._onPrepared4985, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnPreparedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnPreparedListener"));
global::android.media.MediaPlayer.OnPreparedListener_._onPrepared4985 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnPreparedListener_.staticClass, "onPrepared", "(Landroid/media/MediaPlayer;)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnSeekCompleteListener_))]
public interface OnSeekCompleteListener : global::MonoJavaBridge.IJavaObject
{
void onSeekComplete(android.media.MediaPlayer arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnSeekCompleteListener))]
public sealed partial class OnSeekCompleteListener_ : java.lang.Object, OnSeekCompleteListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnSeekCompleteListener_()
{
InitJNI();
}
internal OnSeekCompleteListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onSeekComplete4986;
void android.media.MediaPlayer.OnSeekCompleteListener.onSeekComplete(android.media.MediaPlayer arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnSeekCompleteListener_._onSeekComplete4986, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnSeekCompleteListener_.staticClass, global::android.media.MediaPlayer.OnSeekCompleteListener_._onSeekComplete4986, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnSeekCompleteListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnSeekCompleteListener"));
global::android.media.MediaPlayer.OnSeekCompleteListener_._onSeekComplete4986 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnSeekCompleteListener_.staticClass, "onSeekComplete", "(Landroid/media/MediaPlayer;)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.media.MediaPlayer.OnVideoSizeChangedListener_))]
public interface OnVideoSizeChangedListener : global::MonoJavaBridge.IJavaObject
{
void onVideoSizeChanged(android.media.MediaPlayer arg0, int arg1, int arg2);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.media.MediaPlayer.OnVideoSizeChangedListener))]
public sealed partial class OnVideoSizeChangedListener_ : java.lang.Object, OnVideoSizeChangedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnVideoSizeChangedListener_()
{
InitJNI();
}
internal OnVideoSizeChangedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onVideoSizeChanged4987;
void android.media.MediaPlayer.OnVideoSizeChangedListener.onVideoSizeChanged(android.media.MediaPlayer arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnVideoSizeChangedListener_._onVideoSizeChanged4987, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.OnVideoSizeChangedListener_.staticClass, global::android.media.MediaPlayer.OnVideoSizeChangedListener_._onVideoSizeChanged4987, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.OnVideoSizeChangedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer$OnVideoSizeChangedListener"));
global::android.media.MediaPlayer.OnVideoSizeChangedListener_._onVideoSizeChanged4987 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.OnVideoSizeChangedListener_.staticClass, "onVideoSizeChanged", "(Landroid/media/MediaPlayer;II)V");
}
}
internal static global::MonoJavaBridge.MethodId _finalize4988;
protected override void finalize()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._finalize4988);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._finalize4988);
}
internal static global::MonoJavaBridge.MethodId _start4989;
public virtual void start()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._start4989);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._start4989);
}
internal static global::MonoJavaBridge.MethodId _stop4990;
public virtual void stop()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._stop4990);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._stop4990);
}
internal static global::MonoJavaBridge.MethodId _reset4991;
public virtual void reset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._reset4991);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._reset4991);
}
internal static global::MonoJavaBridge.MethodId _release4992;
public virtual void release()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._release4992);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._release4992);
}
internal static global::MonoJavaBridge.MethodId _create4993;
public static global::android.media.MediaPlayer create(android.content.Context arg0, android.net.Uri arg1, android.view.SurfaceHolder arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._create4993, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.media.MediaPlayer;
}
internal static global::MonoJavaBridge.MethodId _create4994;
public static global::android.media.MediaPlayer create(android.content.Context arg0, android.net.Uri arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._create4994, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.media.MediaPlayer;
}
internal static global::MonoJavaBridge.MethodId _create4995;
public static global::android.media.MediaPlayer create(android.content.Context arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._create4995, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.media.MediaPlayer;
}
internal static global::MonoJavaBridge.MethodId _prepare4996;
public virtual void prepare()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._prepare4996);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._prepare4996);
}
internal static global::MonoJavaBridge.MethodId _getDuration4997;
public virtual int getDuration()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.MediaPlayer._getDuration4997);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._getDuration4997);
}
internal static global::MonoJavaBridge.MethodId _pause4998;
public virtual void pause()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._pause4998);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._pause4998);
}
internal static global::MonoJavaBridge.MethodId _setDisplay4999;
public virtual void setDisplay(android.view.SurfaceHolder arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setDisplay4999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setDisplay4999, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDataSource5000;
public virtual void setDataSource(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setDataSource5000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setDataSource5000, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDataSource5001;
public virtual void setDataSource(java.io.FileDescriptor arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setDataSource5001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setDataSource5001, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setDataSource5002;
public virtual void setDataSource(java.io.FileDescriptor arg0, long arg1, long arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setDataSource5002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setDataSource5002, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setDataSource5003;
public virtual void setDataSource(android.content.Context arg0, android.net.Uri arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setDataSource5003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setDataSource5003, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _prepareAsync5004;
public virtual void prepareAsync()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._prepareAsync5004);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._prepareAsync5004);
}
internal static global::MonoJavaBridge.MethodId _setWakeMode5005;
public virtual void setWakeMode(android.content.Context arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setWakeMode5005, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setWakeMode5005, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setScreenOnWhilePlaying5006;
public virtual void setScreenOnWhilePlaying(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setScreenOnWhilePlaying5006, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setScreenOnWhilePlaying5006, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getVideoWidth5007;
public virtual int getVideoWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.MediaPlayer._getVideoWidth5007);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._getVideoWidth5007);
}
internal static global::MonoJavaBridge.MethodId _getVideoHeight5008;
public virtual int getVideoHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.MediaPlayer._getVideoHeight5008);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._getVideoHeight5008);
}
internal static global::MonoJavaBridge.MethodId _isPlaying5009;
public virtual bool isPlaying()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer._isPlaying5009);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._isPlaying5009);
}
internal static global::MonoJavaBridge.MethodId _seekTo5010;
public virtual void seekTo(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._seekTo5010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._seekTo5010, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getCurrentPosition5011;
public virtual int getCurrentPosition()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.media.MediaPlayer._getCurrentPosition5011);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._getCurrentPosition5011);
}
internal static global::MonoJavaBridge.MethodId _setAudioStreamType5012;
public virtual void setAudioStreamType(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setAudioStreamType5012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setAudioStreamType5012, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setLooping5013;
public virtual void setLooping(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setLooping5013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setLooping5013, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isLooping5014;
public virtual bool isLooping()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer._isLooping5014);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._isLooping5014);
}
internal static global::MonoJavaBridge.MethodId _setVolume5015;
public virtual void setVolume(float arg0, float arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setVolume5015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setVolume5015, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _setOnPreparedListener5016;
public virtual void setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnPreparedListener5016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnPreparedListener5016, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnCompletionListener5017;
public virtual void setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnCompletionListener5017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnCompletionListener5017, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnBufferingUpdateListener5018;
public virtual void setOnBufferingUpdateListener(android.media.MediaPlayer.OnBufferingUpdateListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnBufferingUpdateListener5018, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnBufferingUpdateListener5018, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnSeekCompleteListener5019;
public virtual void setOnSeekCompleteListener(android.media.MediaPlayer.OnSeekCompleteListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnSeekCompleteListener5019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnSeekCompleteListener5019, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnVideoSizeChangedListener5020;
public virtual void setOnVideoSizeChangedListener(android.media.MediaPlayer.OnVideoSizeChangedListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnVideoSizeChangedListener5020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnVideoSizeChangedListener5020, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnErrorListener5021;
public virtual void setOnErrorListener(android.media.MediaPlayer.OnErrorListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnErrorListener5021, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnErrorListener5021, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setOnInfoListener5022;
public virtual void setOnInfoListener(android.media.MediaPlayer.OnInfoListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.media.MediaPlayer._setOnInfoListener5022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._setOnInfoListener5022, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _MediaPlayer5023;
public MediaPlayer() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.MediaPlayer.staticClass, global::android.media.MediaPlayer._MediaPlayer5023);
Init(@__env, handle);
}
public static int MEDIA_ERROR_UNKNOWN
{
get
{
return 1;
}
}
public static int MEDIA_ERROR_SERVER_DIED
{
get
{
return 100;
}
}
public static int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK
{
get
{
return 200;
}
}
public static int MEDIA_INFO_UNKNOWN
{
get
{
return 1;
}
}
public static int MEDIA_INFO_VIDEO_TRACK_LAGGING
{
get
{
return 700;
}
}
public static int MEDIA_INFO_BAD_INTERLEAVING
{
get
{
return 800;
}
}
public static int MEDIA_INFO_NOT_SEEKABLE
{
get
{
return 801;
}
}
public static int MEDIA_INFO_METADATA_UPDATE
{
get
{
return 802;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.media.MediaPlayer.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/MediaPlayer"));
global::android.media.MediaPlayer._finalize4988 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "finalize", "()V");
global::android.media.MediaPlayer._start4989 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "start", "()V");
global::android.media.MediaPlayer._stop4990 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "stop", "()V");
global::android.media.MediaPlayer._reset4991 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "reset", "()V");
global::android.media.MediaPlayer._release4992 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "release", "()V");
global::android.media.MediaPlayer._create4993 = @__env.GetStaticMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "create", "(Landroid/content/Context;Landroid/net/Uri;Landroid/view/SurfaceHolder;)Landroid/media/MediaPlayer;");
global::android.media.MediaPlayer._create4994 = @__env.GetStaticMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "create", "(Landroid/content/Context;Landroid/net/Uri;)Landroid/media/MediaPlayer;");
global::android.media.MediaPlayer._create4995 = @__env.GetStaticMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "create", "(Landroid/content/Context;I)Landroid/media/MediaPlayer;");
global::android.media.MediaPlayer._prepare4996 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "prepare", "()V");
global::android.media.MediaPlayer._getDuration4997 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "getDuration", "()I");
global::android.media.MediaPlayer._pause4998 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "pause", "()V");
global::android.media.MediaPlayer._setDisplay4999 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setDisplay", "(Landroid/view/SurfaceHolder;)V");
global::android.media.MediaPlayer._setDataSource5000 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setDataSource", "(Ljava/lang/String;)V");
global::android.media.MediaPlayer._setDataSource5001 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setDataSource", "(Ljava/io/FileDescriptor;)V");
global::android.media.MediaPlayer._setDataSource5002 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setDataSource", "(Ljava/io/FileDescriptor;JJ)V");
global::android.media.MediaPlayer._setDataSource5003 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setDataSource", "(Landroid/content/Context;Landroid/net/Uri;)V");
global::android.media.MediaPlayer._prepareAsync5004 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "prepareAsync", "()V");
global::android.media.MediaPlayer._setWakeMode5005 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setWakeMode", "(Landroid/content/Context;I)V");
global::android.media.MediaPlayer._setScreenOnWhilePlaying5006 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setScreenOnWhilePlaying", "(Z)V");
global::android.media.MediaPlayer._getVideoWidth5007 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "getVideoWidth", "()I");
global::android.media.MediaPlayer._getVideoHeight5008 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "getVideoHeight", "()I");
global::android.media.MediaPlayer._isPlaying5009 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "isPlaying", "()Z");
global::android.media.MediaPlayer._seekTo5010 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "seekTo", "(I)V");
global::android.media.MediaPlayer._getCurrentPosition5011 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "getCurrentPosition", "()I");
global::android.media.MediaPlayer._setAudioStreamType5012 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setAudioStreamType", "(I)V");
global::android.media.MediaPlayer._setLooping5013 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setLooping", "(Z)V");
global::android.media.MediaPlayer._isLooping5014 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "isLooping", "()Z");
global::android.media.MediaPlayer._setVolume5015 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setVolume", "(FF)V");
global::android.media.MediaPlayer._setOnPreparedListener5016 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnPreparedListener", "(Landroid/media/MediaPlayer$OnPreparedListener;)V");
global::android.media.MediaPlayer._setOnCompletionListener5017 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnCompletionListener", "(Landroid/media/MediaPlayer$OnCompletionListener;)V");
global::android.media.MediaPlayer._setOnBufferingUpdateListener5018 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnBufferingUpdateListener", "(Landroid/media/MediaPlayer$OnBufferingUpdateListener;)V");
global::android.media.MediaPlayer._setOnSeekCompleteListener5019 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnSeekCompleteListener", "(Landroid/media/MediaPlayer$OnSeekCompleteListener;)V");
global::android.media.MediaPlayer._setOnVideoSizeChangedListener5020 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnVideoSizeChangedListener", "(Landroid/media/MediaPlayer$OnVideoSizeChangedListener;)V");
global::android.media.MediaPlayer._setOnErrorListener5021 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnErrorListener", "(Landroid/media/MediaPlayer$OnErrorListener;)V");
global::android.media.MediaPlayer._setOnInfoListener5022 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "setOnInfoListener", "(Landroid/media/MediaPlayer$OnInfoListener;)V");
global::android.media.MediaPlayer._MediaPlayer5023 = @__env.GetMethodIDNoThrow(global::android.media.MediaPlayer.staticClass, "<init>", "()V");
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;
using System.Diagnostics;
sealed class WorkflowOperationAsyncResult : AsyncResult
{
static readonly object[] emptyObjectArray = new object[] { };
static Action<object> waitCallback = new Action<object>(WorkflowOperationAsyncResult.DoWork);
static SendOrPostCallback sendOrPostCallback = Fx.ThunkCallback(new SendOrPostCallback(waitCallback));
Guid instanceIdGuid;
string instanceIdString;
bool isOneway;
IDictionary<string, string> outgoingContextProperties = SerializableReadOnlyDictionary<string, string>.Empty;
object[] outputs = emptyObjectArray;
object returnValue;
long time;
public WorkflowOperationAsyncResult(WorkflowOperationInvoker workflowOperationInvoker,
WorkflowDurableInstance workflowDurableInstance, object[] inputs,
AsyncCallback callback, object state, long time)
: base(callback, state)
{
if (inputs == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inputs");
}
if (workflowDurableInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workflowDurableInstance");
}
if (workflowOperationInvoker == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("workflowOperationInvoker");
}
string queueName;
WorkflowRequestContext workflowRequestContext = new WorkflowRequestContext(
this,
inputs,
GetContextProperties());
queueName = workflowOperationInvoker.StaticQueueName;
if (workflowRequestContext.ContextProperties.Count > 1) //DurableDispatchContextProperty.
{
queueName = QueueNameHelper.Create(workflowOperationInvoker.StaticQueueName, workflowRequestContext.ContextProperties);
}
WorkflowInstance workflowInstance = workflowDurableInstance.GetWorkflowInstance
(workflowOperationInvoker.CanCreateInstance);
AsyncCallbackState callbackState = new AsyncCallbackState(workflowRequestContext,
workflowInstance, workflowOperationInvoker.DispatchRuntime.SynchronizationContext,
workflowOperationInvoker.InstanceLifetimeManager, queueName);
this.isOneway = workflowOperationInvoker.IsOneWay;
this.instanceIdGuid = workflowInstance.InstanceId;
this.time = time;
ActionItem.Schedule(waitCallback, callbackState);
if (DiagnosticUtility.ShouldTraceVerbose)
{
string traceText = SR2.GetString(SR2.WorkflowOperationInvokerItemQueued, this.InstanceId, queueName);
TraceUtility.TraceEvent(TraceEventType.Verbose,
TraceCode.WorkflowOperationInvokerItemQueued, SR.GetString(SR.TraceCodeWorkflowOperationInvokerItemQueued),
new StringTraceRecord("ItemDetails", traceText),
this, null);
}
}
public long BeginTime
{
get
{
return this.time;
}
}
public bool HasWorkflowRequestContextBeenSerialized
{
get;
set;
}
internal string InstanceId
{
get
{
if (this.instanceIdString == null)
{
Fx.Assert(!this.instanceIdGuid.Equals(Guid.Empty), "WorkflowOperationInvokerAsyncResut.instanceIdGuid != Guid.Empty");
this.instanceIdString = this.instanceIdGuid.ToString();
}
return this.instanceIdString;
}
}
public static object End(WorkflowOperationAsyncResult result, out object[] outputs)
{
if (result == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
}
try
{
AsyncResult.End<WorkflowOperationAsyncResult>(result);
}
finally
{
//Application Fault's should carry Context Properties
result.PromoteContextProperties();
}
outputs = result.outputs;
return result.returnValue;
}
public void SendFault(Exception exception, IDictionary<string, string> contextProperties)
{
if (exception == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exception");
}
if (!IsCompleted)
{
this.outgoingContextProperties = (contextProperties != null) ? new ContextDictionary(contextProperties) : null;
}
base.Complete(false, exception);
}
public void SendResponse(object returnValue, object[] outputs, IDictionary<string, string> contextProperties)
{
if (outputs == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("outputs");
}
if (!IsCompleted)
{
this.returnValue = returnValue;
this.outputs = outputs;
this.outgoingContextProperties = (contextProperties != null) ? new ContextDictionary(contextProperties) : null;
}
base.Complete(false);
}
//No-op for two-ways.
internal void MarkOneWayOperationCompleted()
{
if (this.isOneway && !this.IsCompleted)
{
base.Complete(false);
}
}
static void DoWork(object state)
{
if (state == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("state");
}
AsyncCallbackState callbackState = (AsyncCallbackState) state;
bool executingWork = false;
try
{
//If SyncContext is enabled
//We have to do another post to get to correct thread.
if (callbackState.SynchronizationContext != null)
{
SynchronizationContext synchronizationContext = callbackState.SynchronizationContext;
callbackState.SynchronizationContext = null;
SynchronizationContextWorkflowSchedulerService.SynchronizationContextPostHelper.Post(
synchronizationContext,
WorkflowOperationAsyncResult.sendOrPostCallback,
callbackState);
}
else //We are in correct thread to do the work.
{
using (new WorkflowDispatchContext(true))
{
callbackState.WorkflowRequestContext.SetOperationBegin();
executingWork = true;
if (callbackState.WorkflowInstanceLifeTimeManager != null)
{
callbackState.WorkflowInstanceLifeTimeManager.NotifyMessageArrived(callbackState.WorkflowInstance.InstanceId);
}
callbackState.WorkflowInstance.EnqueueItemOnIdle(
callbackState.QueueName,
callbackState.WorkflowRequestContext,
null,
null);
}
}
}
catch (QueueException e)
{
WorkflowOperationFault operationFault = new WorkflowOperationFault(e.ErrorCode);
try
{
if (callbackState.WorkflowInstanceLifeTimeManager != null)
{
callbackState.WorkflowInstanceLifeTimeManager.ScheduleTimer(callbackState.WorkflowInstance.InstanceId);
}
callbackState.WorkflowRequestContext.SendFault(new FaultException(operationFault), null);
}
catch (Exception unhandled)
{
if (Fx.IsFatal(unhandled))
{
throw;
}
// ignore exception; we made best effort to propagate the exception back to the invoker thread
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
try
{
if (callbackState.WorkflowInstanceLifeTimeManager != null)
{
callbackState.WorkflowInstanceLifeTimeManager.ScheduleTimer(callbackState.WorkflowInstance.InstanceId);
}
//We should field only user code exception; Everything else should go abort path.
callbackState.WorkflowRequestContext.GetAsyncResult().SendFault(e, null);
}
catch (Exception e1)
{
if (Fx.IsFatal(e1))
{
throw;
}
// ignore exception; we made best effort to propagate the exception back to the invoker thread
}
}
finally
{
try
{
if (executingWork)
{
callbackState.WorkflowRequestContext.SetOperationCompleted();
}
}
catch (Exception e1)
{
if (Fx.IsFatal(e1))
{
throw;
}
// ignore exception; we made best effort to propagate the exception back to the invoker thread }
}
}
}
IDictionary<string, string> GetContextProperties()
{
Fx.Assert(OperationContext.Current != null, "Called from non service thread");
ContextMessageProperty incomingContextProperties = null;
if (OperationContext.Current.IncomingMessageProperties != null
&& ContextMessageProperty.TryGet(OperationContext.Current.IncomingMessageProperties, out incomingContextProperties))
{
return incomingContextProperties.Context;
}
else
{
return SerializableReadOnlyDictionary<string, string>.Empty;
}
}
void PromoteContextProperties()
{
Fx.Assert(OperationContext.Current != null, "Called from non service thread");
if (outgoingContextProperties != null)
{
ContextMessageProperty context;
if (!ContextMessageProperty.TryGet(OperationContext.Current.OutgoingMessageProperties, out context))
{
new ContextMessageProperty(this.outgoingContextProperties).AddOrReplaceInMessageProperties(OperationContext.Current.OutgoingMessageProperties);
}
else
{
foreach (KeyValuePair<string, string> contextElement in this.outgoingContextProperties)
{
context.Context[contextElement.Key] = contextElement.Value;
}
}
}
}
class AsyncCallbackState
{
WorkflowInstanceLifetimeManagerExtension instanceLifeTimeManager;
IComparable queueName;
SynchronizationContext synchronizationContext;
WorkflowInstance workflowInstance;
WorkflowRequestContext workflowRequestContext;
public AsyncCallbackState(
WorkflowRequestContext workflowRequestContext,
WorkflowInstance workflowInstance,
SynchronizationContext synchronizationContext,
WorkflowInstanceLifetimeManagerExtension instanceLifeTimeManager,
IComparable queueName)
{
this.workflowInstance = workflowInstance;
this.workflowRequestContext = workflowRequestContext;
this.synchronizationContext = synchronizationContext;
this.queueName = queueName;
this.instanceLifeTimeManager = instanceLifeTimeManager;
}
public IComparable QueueName
{
get
{
return this.queueName;
}
}
public SynchronizationContext SynchronizationContext
{
get
{
return this.synchronizationContext;
}
set
{
this.synchronizationContext = value;
}
}
public WorkflowInstance WorkflowInstance
{
get
{
return this.workflowInstance;
}
}
public WorkflowInstanceLifetimeManagerExtension WorkflowInstanceLifeTimeManager
{
get
{
return this.instanceLifeTimeManager;
}
}
public WorkflowRequestContext WorkflowRequestContext
{
get
{
return this.workflowRequestContext;
}
}
}
}
}
| |
// 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;
using System.Xml;
using System.Collections;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization; // For SR
using System.Security;
using System.Text;
using System.Globalization;
namespace System.Xml
{
public interface IXmlTextReaderInitializer
{
void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose);
}
internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer
{
private const int MaxTextChunk = 2048;
private PrefixHandle _prefix;
private StringHandle _localName;
private int[] _rowOffsets;
private OnXmlDictionaryReaderClose _onClose;
private bool _buffered;
private int _maxBytesPerRead;
private static byte[] s_charType = new byte[256]
{
/* 0 (.) */
CharType.None,
/* 1 (.) */
CharType.None,
/* 2 (.) */
CharType.None,
/* 3 (.) */
CharType.None,
/* 4 (.) */
CharType.None,
/* 5 (.) */
CharType.None,
/* 6 (.) */
CharType.None,
/* 7 (.) */
CharType.None,
/* 8 (.) */
CharType.None,
/* 9 (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace,
/* A (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.SpecialWhitespace,
/* B (.) */
CharType.None,
/* C (.) */
CharType.None,
/* D (.) */
CharType.None|CharType.Comment|CharType.Comment|CharType.Whitespace,
/* E (.) */
CharType.None,
/* F (.) */
CharType.None,
/* 10 (.) */
CharType.None,
/* 11 (.) */
CharType.None,
/* 12 (.) */
CharType.None,
/* 13 (.) */
CharType.None,
/* 14 (.) */
CharType.None,
/* 15 (.) */
CharType.None,
/* 16 (.) */
CharType.None,
/* 17 (.) */
CharType.None,
/* 18 (.) */
CharType.None,
/* 19 (.) */
CharType.None,
/* 1A (.) */
CharType.None,
/* 1B (.) */
CharType.None,
/* 1C (.) */
CharType.None,
/* 1D (.) */
CharType.None,
/* 1E (.) */
CharType.None,
/* 1F (.) */
CharType.None,
/* 20 ( ) */
CharType.None|CharType.Comment|CharType.Whitespace|CharType.Text|CharType.AttributeText|CharType.SpecialWhitespace,
/* 21 (!) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 22 (") */
CharType.None|CharType.Comment|CharType.Text,
/* 23 (#) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 24 ($) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 25 (%) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 26 (&) */
CharType.None|CharType.Comment,
/* 27 (') */
CharType.None|CharType.Comment|CharType.Text,
/* 28 (() */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 29 ()) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2A (*) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2B (+) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2C (,) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 2D (-) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 2E (.) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 2F (/) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 30 (0) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 31 (1) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 32 (2) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 33 (3) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 34 (4) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 35 (5) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 36 (6) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 37 (7) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 38 (8) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 39 (9) */
CharType.None|CharType.Comment|CharType.Name|CharType.Text|CharType.AttributeText,
/* 3A (:) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3B (;) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3C (<) */
CharType.None|CharType.Comment,
/* 3D (=) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3E (>) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 3F (?) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 40 (@) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 41 (A) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 42 (B) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 43 (C) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 44 (D) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 45 (E) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 46 (F) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 47 (G) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 48 (H) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 49 (I) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4A (J) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4B (K) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4C (L) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4D (M) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4E (N) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 4F (O) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 50 (P) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 51 (Q) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 52 (R) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 53 (S) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 54 (T) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 55 (U) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 56 (V) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 57 (W) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 58 (X) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 59 (Y) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 5A (Z) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 5B ([) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5C (\) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5D (]) */
CharType.None|CharType.Comment|CharType.AttributeText,
/* 5E (^) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 5F (_) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 60 (`) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 61 (a) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 62 (b) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 63 (c) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 64 (d) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 65 (e) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 66 (f) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 67 (g) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 68 (h) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 69 (i) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6A (j) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6B (k) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6C (l) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6D (m) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6E (n) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 6F (o) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 70 (p) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 71 (q) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 72 (r) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 73 (s) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 74 (t) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 75 (u) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 76 (v) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 77 (w) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 78 (x) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 79 (y) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 7A (z) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 7B ({) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7C (|) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7D (}) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7E (~) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 7F (.) */
CharType.None|CharType.Comment|CharType.Text|CharType.AttributeText,
/* 80 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 81 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 82 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 83 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 84 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 85 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 86 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 87 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 88 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 89 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8A (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8B (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8C (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8D (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8E (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 8F (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 90 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 91 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 92 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 93 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 94 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 95 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 96 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 97 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 98 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 99 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9A (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9B (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9C (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9D (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9E (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* 9F (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A0 (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* A9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AD (.) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* AF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* B9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* BF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* C9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* CF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* D9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* DF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* E9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* ED (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* EF (?) */
CharType.None|CharType.FirstName|CharType.Name,
/* F0 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F1 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F2 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F3 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F4 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F5 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F6 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F7 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F8 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* F9 (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FA (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FB (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FC (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FD (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FE (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
/* FF (?) */
CharType.None|CharType.Comment|CharType.FirstName|CharType.Name|CharType.Text|CharType.AttributeText,
};
public XmlUTF8TextReader()
{
_prefix = new PrefixHandle(BufferReader);
_localName = new StringHandle(BufferReader);
}
public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, onClose);
ArraySegment<byte> seg = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding);
BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null);
_buffered = true;
}
public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream));
MoveToInitial(quotas, onClose);
stream = new EncodingStreamWrapper(stream, encoding);
BufferReader.SetBuffer(stream, null, null);
_buffered = false;
}
private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
{
MoveToInitial(quotas);
_maxBytesPerRead = quotas.MaxBytesPerRead;
_onClose = onClose;
}
public override void Close()
{
_rowOffsets = null;
base.Close();
OnXmlDictionaryReaderClose onClose = _onClose;
_onClose = null;
if (onClose != null)
{
try
{
onClose(this);
}
catch (Exception e)
{
if (DiagnosticUtility.IsFatal(e)) throw;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e);
}
}
}
private void SkipWhitespace()
{
while (!BufferReader.EndOfFile && (s_charType[BufferReader.GetByte()] & CharType.Whitespace) != 0)
BufferReader.SkipByte();
}
private void ReadDeclaration()
{
if (!_buffered)
BufferElement();
int offset;
byte[] buffer = BufferReader.GetBuffer(5, out offset);
if (buffer[offset + 0] != (byte)'?' ||
buffer[offset + 1] != (byte)'x' ||
buffer[offset + 2] != (byte)'m' ||
buffer[offset + 3] != (byte)'l' ||
(s_charType[buffer[offset + 4]] & CharType.Whitespace) == 0)
{
XmlExceptionHelper.ThrowProcessingInstructionNotSupported(this);
}
// If anything came before the "<?xml ?>" it's an error.
if (this.Node.ReadState != ReadState.Initial)
{
XmlExceptionHelper.ThrowDeclarationNotFirst(this);
}
BufferReader.Advance(5);
int localNameOffset = offset + 1;
int localNameLength = 3;
int valueOffset = BufferReader.Offset;
SkipWhitespace();
ReadAttributes();
int valueLength = BufferReader.Offset - valueOffset;
// Backoff the spaces
while (valueLength > 0)
{
byte ch = BufferReader.GetByte(valueOffset + valueLength - 1);
if ((s_charType[ch] & CharType.Whitespace) == 0)
break;
valueLength--;
}
buffer = BufferReader.GetBuffer(2, out offset);
if (buffer[offset + 0] != (byte)'?' ||
buffer[offset + 1] != (byte)'>')
{
XmlExceptionHelper.ThrowTokenExpected(this, "?>", Encoding.UTF8.GetString(buffer, offset, 2));
}
BufferReader.Advance(2);
XmlDeclarationNode declarationNode = MoveToDeclaration();
declarationNode.LocalName.SetValue(localNameOffset, localNameLength);
declarationNode.Value.SetValue(ValueHandleType.UTF8, valueOffset, valueLength);
}
private void VerifyNCName(string s)
{
try
{
XmlConvert.VerifyNCName(s);
}
catch (XmlException exception)
{
XmlExceptionHelper.ThrowXmlException(this, exception);
}
}
private void ReadQualifiedName(PrefixHandle prefix, StringHandle localName)
{
int offset;
int offsetMax;
byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax);
int ch = 0;
int anyChar = 0;
int prefixChar = 0;
int prefixOffset = offset;
if (offset < offsetMax)
{
ch = buffer[offset];
prefixChar = ch;
if ((s_charType[ch] & CharType.FirstName) == 0)
anyChar |= 0x80;
anyChar |= ch;
offset++;
while (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.Name) == 0)
break;
anyChar |= ch;
offset++;
}
}
else
{
anyChar |= 0x80;
ch = 0;
}
if (ch == ':')
{
int prefixLength = offset - prefixOffset;
if (prefixLength == 1 && prefixChar >= 'a' && prefixChar <= 'z')
prefix.SetValue(PrefixHandle.GetAlphaPrefix(prefixChar - 'a'));
else
prefix.SetValue(prefixOffset, prefixLength);
offset++;
int localNameOffset = offset;
if (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.FirstName) == 0)
anyChar |= 0x80;
anyChar |= ch;
offset++;
while (offset < offsetMax)
{
ch = buffer[offset];
if ((s_charType[ch] & CharType.Name) == 0)
break;
anyChar |= ch;
offset++;
}
}
else
{
anyChar |= 0x80;
ch = 0;
}
localName.SetValue(localNameOffset, offset - localNameOffset);
if (anyChar >= 0x80)
{
VerifyNCName(prefix.GetString());
VerifyNCName(localName.GetString());
}
}
else
{
prefix.SetValue(PrefixHandleType.Empty);
localName.SetValue(prefixOffset, offset - prefixOffset);
if (anyChar >= 0x80)
{
VerifyNCName(localName.GetString());
}
}
BufferReader.Advance(offset - prefixOffset);
}
private int ReadAttributeText(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.AttributeText) != 0)
offset++;
return offset - textOffset;
}
private void ReadAttributes()
{
int startOffset = 0;
if (_buffered)
startOffset = BufferReader.Offset;
while (true)
{
byte ch;
ReadQualifiedName(_prefix, _localName);
if (BufferReader.GetByte() != '=')
{
SkipWhitespace();
if (BufferReader.GetByte() != '=')
XmlExceptionHelper.ThrowTokenExpected(this, "=", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
byte quoteChar = BufferReader.GetByte();
if (quoteChar != '"' && quoteChar != '\'')
{
SkipWhitespace();
quoteChar = BufferReader.GetByte();
if (quoteChar != '"' && quoteChar != '\'')
XmlExceptionHelper.ThrowTokenExpected(this, "\"", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
bool escaped = false;
int valueOffset = BufferReader.Offset;
while (true)
{
int offset, offsetMax;
byte[] buffer = BufferReader.GetBuffer(out offset, out offsetMax);
int length = ReadAttributeText(buffer, offset, offsetMax);
BufferReader.Advance(length);
ch = BufferReader.GetByte();
if (ch == quoteChar)
break;
if (ch == '&')
{
ReadCharRef();
escaped = true;
}
else if (ch == '\'' || ch == '"')
{
BufferReader.SkipByte();
}
else if (ch == '\n' || ch == '\r' || ch == '\t')
{
BufferReader.SkipByte();
escaped = true;
}
else if (ch == 0xEF)
{
ReadNonFFFE();
}
else
{
XmlExceptionHelper.ThrowTokenExpected(this, ((char)quoteChar).ToString(), (char)ch);
}
}
int valueLength = BufferReader.Offset - valueOffset;
XmlAttributeNode attributeNode;
if (_prefix.IsXmlns)
{
Namespace ns = AddNamespace();
_localName.ToPrefixHandle(ns.Prefix);
ns.Uri.SetValue(valueOffset, valueLength, escaped);
attributeNode = AddXmlnsAttribute(ns);
}
else if (_prefix.IsEmpty && _localName.IsXmlns)
{
Namespace ns = AddNamespace();
ns.Prefix.SetValue(PrefixHandleType.Empty);
ns.Uri.SetValue(valueOffset, valueLength, escaped);
attributeNode = AddXmlnsAttribute(ns);
}
else if (_prefix.IsXml)
{
attributeNode = AddXmlAttribute();
attributeNode.Prefix.SetValue(_prefix);
attributeNode.LocalName.SetValue(_localName);
attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength);
FixXmlAttribute(attributeNode);
}
else
{
attributeNode = AddAttribute();
attributeNode.Prefix.SetValue(_prefix);
attributeNode.LocalName.SetValue(_localName);
attributeNode.Value.SetValue((escaped ? ValueHandleType.EscapedUTF8 : ValueHandleType.UTF8), valueOffset, valueLength);
}
attributeNode.QuoteChar = (char)quoteChar;
BufferReader.SkipByte();
ch = BufferReader.GetByte();
bool space = false;
while ((s_charType[ch] & CharType.Whitespace) != 0)
{
space = true;
BufferReader.SkipByte();
ch = BufferReader.GetByte();
}
if (ch == '>' || ch == '/' || ch == '?')
break;
if (!space)
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlSpaceBetweenAttributes)));
}
if (_buffered && (BufferReader.Offset - startOffset) > _maxBytesPerRead)
XmlExceptionHelper.ThrowMaxBytesPerReadExceeded(this, _maxBytesPerRead);
ProcessAttributes();
}
// NOTE: Call only if 0xEF has been seen in the stream AND there are three valid bytes to check (buffer[offset], buffer[offset + 1], buffer[offset + 2]).
// 0xFFFE and 0xFFFF are not valid characters per Unicode specification. The first byte in the UTF8 representation is 0xEF.
private bool IsNextCharacterNonFFFE(byte[] buffer, int offset)
{
Fx.Assert(buffer[offset] == 0xEF, "buffer[offset] MUST be 0xEF.");
if (buffer[offset + 1] == 0xBF && (buffer[offset + 2] == 0xBE || buffer[offset + 2] == 0xBF))
{
// 0xFFFE : 0xEF 0xBF 0xBE
// 0xFFFF : 0xEF 0xBF 0xBF
// we know that buffer[offset] is already 0xEF, don't bother checking it.
return false;
}
// no bad characters
return true;
}
private void ReadNonFFFE()
{
int off;
byte[] buff = BufferReader.GetBuffer(3, out off);
if (buff[off + 1] == 0xBF && (buff[off + 2] == 0xBE || buff[off + 2] == 0xBF))
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE)));
}
BufferReader.Advance(3);
}
private void BufferElement()
{
int elementOffset = BufferReader.Offset;
const int byteCount = 128;
bool done = false;
byte quoteChar = 0;
while (!done)
{
int offset;
int offsetMax;
byte[] buffer = BufferReader.GetBuffer(byteCount, out offset, out offsetMax);
if (offset + byteCount != offsetMax)
break;
for (int i = offset; i < offsetMax && !done; i++)
{
byte b = buffer[i];
if (quoteChar == 0)
{
if (b == '\'' || b == '"')
quoteChar = b;
if (b == '>')
done = true;
}
else
{
if (b == quoteChar)
{
quoteChar = 0;
}
}
}
BufferReader.Advance(byteCount);
}
BufferReader.Offset = elementOffset;
}
private new void ReadStartElement()
{
if (!_buffered)
BufferElement();
XmlElementNode elementNode = EnterScope();
elementNode.NameOffset = BufferReader.Offset;
ReadQualifiedName(elementNode.Prefix, elementNode.LocalName);
elementNode.NameLength = BufferReader.Offset - elementNode.NameOffset;
byte ch = BufferReader.GetByte();
while ((s_charType[ch] & CharType.Whitespace) != 0)
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
}
if (ch != '>' && ch != '/')
{
ReadAttributes();
ch = BufferReader.GetByte();
}
elementNode.Namespace = LookupNamespace(elementNode.Prefix);
bool isEmptyElement = false;
if (ch == '/')
{
isEmptyElement = true;
BufferReader.SkipByte();
}
elementNode.IsEmptyElement = isEmptyElement;
elementNode.ExitScope = isEmptyElement;
if (BufferReader.GetByte() != '>')
XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte());
BufferReader.SkipByte();
elementNode.BufferOffset = BufferReader.Offset;
}
private new void ReadEndElement()
{
BufferReader.SkipByte();
XmlElementNode elementNode = this.ElementNode;
int nameOffset = elementNode.NameOffset;
int nameLength = elementNode.NameLength;
int offset;
byte[] buffer = BufferReader.GetBuffer(nameLength, out offset);
for (int i = 0; i < nameLength; i++)
{
if (buffer[offset + i] != buffer[nameOffset + i])
{
ReadQualifiedName(_prefix, _localName);
XmlExceptionHelper.ThrowTagMismatch(this, elementNode.Prefix.GetString(), elementNode.LocalName.GetString(), _prefix.GetString(), _localName.GetString());
}
}
BufferReader.Advance(nameLength);
if (BufferReader.GetByte() != '>')
{
SkipWhitespace();
if (BufferReader.GetByte() != '>')
XmlExceptionHelper.ThrowTokenExpected(this, ">", (char)BufferReader.GetByte());
}
BufferReader.SkipByte();
MoveToEndElement();
}
private void ReadComment()
{
BufferReader.SkipByte();
if (BufferReader.GetByte() != '-')
XmlExceptionHelper.ThrowTokenExpected(this, "--", (char)BufferReader.GetByte());
BufferReader.SkipByte();
int commentOffset = BufferReader.Offset;
while (true)
{
while (true)
{
byte b = BufferReader.GetByte();
if (b == '-')
break;
if ((s_charType[b] & CharType.Comment) == 0)
{
if (b == 0xEF)
ReadNonFFFE();
else
XmlExceptionHelper.ThrowInvalidXml(this, b);
}
else
{
BufferReader.SkipByte();
}
}
int offset;
byte[] buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)'-' &&
buffer[offset + 1] == (byte)'-')
{
if (buffer[offset + 2] == (byte)'>')
break;
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidCommentChars)));
}
BufferReader.SkipByte();
}
int commentLength = BufferReader.Offset - commentOffset;
MoveToComment().Value.SetValue(ValueHandleType.UTF8, commentOffset, commentLength);
BufferReader.Advance(3);
}
private void ReadCData()
{
int offset;
byte[] buffer = BufferReader.GetBuffer(7, out offset);
if (buffer[offset + 0] != (byte)'[' ||
buffer[offset + 1] != (byte)'C' ||
buffer[offset + 2] != (byte)'D' ||
buffer[offset + 3] != (byte)'A' ||
buffer[offset + 4] != (byte)'T' ||
buffer[offset + 5] != (byte)'A' ||
buffer[offset + 6] != (byte)'[')
{
XmlExceptionHelper.ThrowTokenExpected(this, "[CDATA[", Encoding.UTF8.GetString(buffer, offset, 7));
}
BufferReader.Advance(7);
int cdataOffset = BufferReader.Offset;
while (true)
{
byte b;
while (true)
{
b = BufferReader.GetByte();
if (b == ']')
break;
if (b == 0xEF)
ReadNonFFFE();
else
BufferReader.SkipByte();
}
buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)']' &&
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
break;
BufferReader.SkipByte();
}
int cdataLength = BufferReader.Offset - cdataOffset;
MoveToCData().Value.SetValue(ValueHandleType.UTF8, cdataOffset, cdataLength);
BufferReader.Advance(3);
}
private int ReadCharRef()
{
DiagnosticUtility.DebugAssert(BufferReader.GetByte() == '&', "");
int charEntityOffset = BufferReader.Offset;
BufferReader.SkipByte();
while (BufferReader.GetByte() != ';')
BufferReader.SkipByte();
BufferReader.SkipByte();
int charEntityLength = BufferReader.Offset - charEntityOffset;
BufferReader.Offset = charEntityOffset;
int ch = BufferReader.GetCharEntity(charEntityOffset, charEntityLength);
BufferReader.Advance(charEntityLength);
return ch;
}
private void ReadWhitespace()
{
byte[] buffer;
int offset;
int offsetMax;
int length;
if (_buffered)
{
buffer = BufferReader.GetBuffer(out offset, out offsetMax);
length = ReadWhitespace(buffer, offset, offsetMax);
}
else
{
buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax);
length = ReadWhitespace(buffer, offset, offsetMax);
length = BreakText(buffer, offset, length);
}
BufferReader.Advance(length);
MoveToWhitespaceText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
private int ReadWhitespace(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int wsOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.SpecialWhitespace) != 0)
offset++;
return offset - wsOffset;
}
private int ReadText(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && (charType[buffer[offset]] & CharType.Text) != 0)
offset++;
return offset - textOffset;
}
// Read Unicode codepoints 0xFvvv
private int ReadTextAndWatchForInvalidCharacters(byte[] buffer, int offset, int offsetMax)
{
byte[] charType = XmlUTF8TextReader.s_charType;
int textOffset = offset;
while (offset < offsetMax && ((charType[buffer[offset]] & CharType.Text) != 0 || buffer[offset] == 0xEF))
{
if (buffer[offset] != 0xEF)
{
offset++;
}
else
{
// Ensure that we have three bytes (buffer[offset], buffer[offset + 1], buffer[offset + 2])
// available for IsNextCharacterNonFFFE to check.
if (offset + 2 < offsetMax)
{
if (IsNextCharacterNonFFFE(buffer, offset))
{
// if first byte is 0xEF, UTF8 mandates a 3-byte character representation of this Unicode code point
offset += 3;
}
else
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE)));
}
}
else
{
if (BufferReader.Offset < offset)
{
// We have read some characters already
// Let the outer ReadText advance the bufferReader and return text node to caller
break;
}
else
{
// Get enough bytes for us to process next character, then go back to top of while loop
int dummy;
BufferReader.GetBuffer(3, out dummy);
}
}
}
}
return offset - textOffset;
}
// bytes bits UTF-8 representation
// ----- ---- -----------------------------------
// 1 7 0vvvvvvv
// 2 11 110vvvvv 10vvvvvv
// 3 16 1110vvvv 10vvvvvv 10vvvvvv
// 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
// ----- ---- -----------------------------------
private int BreakText(byte[] buffer, int offset, int length)
{
// See if we might be breaking a utf8 sequence
if (length > 0 && (buffer[offset + length - 1] & 0x80) == 0x80)
{
// Find the lead char of the utf8 sequence (0x11xxxxxx)
int originalLength = length;
do
{
length--;
}
while (length > 0 && (buffer[offset + length] & 0xC0) != 0xC0);
// Couldn't find the lead char
if (length == 0)
return originalLength; // Invalid utf8 sequence - can't break
// Count how many bytes follow the lead char
byte b = unchecked((byte)(buffer[offset + length] << 2));
int byteCount = 2;
while ((b & 0x80) == 0x80)
{
b = unchecked((byte)(b << 1));
byteCount++;
// There shouldn't be more than 3 bytes following the lead char
if (byteCount > 4)
return originalLength; // Invalid utf8 sequence - can't break
}
if (length + byteCount == originalLength)
return originalLength; // sequence fits exactly
}
return length;
}
private void ReadText(bool hasLeadingByteOf0xEF)
{
byte[] buffer;
int offset;
int offsetMax;
int length;
if (_buffered)
{
buffer = BufferReader.GetBuffer(out offset, out offsetMax);
if (hasLeadingByteOf0xEF)
{
length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax);
}
else
{
length = ReadText(buffer, offset, offsetMax);
}
}
else
{
buffer = BufferReader.GetBuffer(MaxTextChunk, out offset, out offsetMax);
if (hasLeadingByteOf0xEF)
{
length = ReadTextAndWatchForInvalidCharacters(buffer, offset, offsetMax);
}
else
{
length = ReadText(buffer, offset, offsetMax);
}
length = BreakText(buffer, offset, length);
}
BufferReader.Advance(length);
if (offset < offsetMax - 1 - length && (buffer[offset + length] == (byte)'<' && buffer[offset + length + 1] != (byte)'!'))
{
MoveToAtomicText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
else
{
MoveToComplexText().Value.SetValue(ValueHandleType.UTF8, offset, length);
}
}
private void ReadEscapedText()
{
int ch = ReadCharRef();
if (ch < 256 && (s_charType[ch] & CharType.Whitespace) != 0)
MoveToWhitespaceText().Value.SetCharValue(ch);
else
MoveToComplexText().Value.SetCharValue(ch);
}
public override bool Read()
{
if (this.Node.ReadState == ReadState.Closed)
return false;
if (this.Node.CanMoveToElement)
{
// If we're positioned on an attribute or attribute text on an empty element, we need to move back
// to the element in order to get the correct setting of ExitScope
MoveToElement();
}
if (this.Node.ExitScope)
{
ExitScope();
}
if (!_buffered)
BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead);
if (BufferReader.EndOfFile)
{
MoveToEndOfFile();
return false;
}
byte ch = BufferReader.GetByte();
if (ch == (byte)'<')
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
if (ch == (byte)'/')
ReadEndElement();
else if (ch == (byte)'!')
{
BufferReader.SkipByte();
ch = BufferReader.GetByte();
if (ch == '-')
{
ReadComment();
}
else
{
if (OutsideRootElement)
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCDATAInvalidAtTopLevel)));
ReadCData();
}
}
else if (ch == (byte)'?')
ReadDeclaration();
else
ReadStartElement();
}
else if ((s_charType[ch] & CharType.SpecialWhitespace) != 0)
{
ReadWhitespace();
}
else if (OutsideRootElement && ch != '\r')
{
XmlExceptionHelper.ThrowInvalidRootData(this);
}
else if ((s_charType[ch] & CharType.Text) != 0)
{
ReadText(false);
}
else if (ch == '&')
{
ReadEscapedText();
}
else if (ch == '\r')
{
BufferReader.SkipByte();
if (!BufferReader.EndOfFile && BufferReader.GetByte() == '\n')
ReadWhitespace();
else
MoveToComplexText().Value.SetCharValue('\n');
}
else if (ch == ']')
{
int offset;
byte[] buffer = BufferReader.GetBuffer(3, out offset);
if (buffer[offset + 0] == (byte)']' &&
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
{
XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCloseCData)));
}
BufferReader.SkipByte();
MoveToComplexText().Value.SetCharValue(']'); // Need to get past the ']' and keep going.
}
else if (ch == 0xEF) // Watch for invalid characters 0xfffe and 0xffff
{
ReadText(true);
}
else
{
XmlExceptionHelper.ThrowInvalidXml(this, ch);
}
return true;
}
public bool HasLineInfo()
{
return true;
}
public int LineNumber
{
get
{
int row, column;
GetPosition(out row, out column);
return row;
}
}
public int LinePosition
{
get
{
int row, column;
GetPosition(out row, out column);
return column;
}
}
private void GetPosition(out int row, out int column)
{
if (_rowOffsets == null)
{
_rowOffsets = BufferReader.GetRows();
}
int offset = BufferReader.Offset;
int j = 0;
while (j < _rowOffsets.Length - 1 && _rowOffsets[j + 1] < offset)
j++;
row = j + 1;
column = offset - _rowOffsets[j] + 1;
}
private static class CharType
{
public const byte None = 0x00;
public const byte FirstName = 0x01;
public const byte Name = 0x02;
public const byte Whitespace = 0x04;
public const byte Text = 0x08;
public const byte AttributeText = 0x10;
public const byte SpecialWhitespace = 0x20;
public const byte Comment = 0x40;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See license-pdn.txt for full licensing and attribution details. //
// //
// Ported to Pinta by: Jonathan Pobst <[email protected]> //
/////////////////////////////////////////////////////////////////////////////////
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Pinta.ImageManipulation
{
/// <summary>
/// Defines a way to operate on a pixel, or a region of pixels, in a binary fashion.
/// That is, it is a simple function F that takes two parameters and returns a
/// result of the form: c = F(a, b)
/// </summary>
public unsafe abstract class BinaryPixelOp : PixelOp
{
public abstract ColorBgra Apply (ColorBgra lhs, ColorBgra rhs);
public void Apply (ISurface src, ISurface dst)
{
if (dst.Size != src.Size)
throw new ArgumentException ("dst.Size != src.Size");
ApplyLoop (src, dst, dst.Bounds, CancellationToken.None, null);
}
public void Apply (ISurface src, ISurface dst, Rectangle roi)
{
ApplyLoop (src, dst, roi, CancellationToken.None, null);
}
public void Apply (ISurface lhs, ISurface rhs, ISurface dst)
{
if (dst.Size != lhs.Size)
throw new ArgumentException ("dst.Size != lhs.Size");
if (lhs.Size != rhs.Size)
throw new ArgumentException ("lhs.Size != rhs.Size");
ApplyLoop (lhs, rhs, dst, dst.Bounds, CancellationToken.None, null);
}
public void Apply (ISurface lhs, ISurface rhs, ISurface dst, Rectangle roi)
{
ApplyLoop (lhs, rhs, dst, roi, CancellationToken.None, null);
}
public Task ApplyAsync (ISurface src, ISurface dst)
{
if (dst.Size != src.Size)
throw new ArgumentException ("dst.Size != src.Size");
return ApplyAsync (src, dst, dst.Bounds, CancellationToken.None);
}
public Task ApplyAsync (ISurface src, ISurface dst, CancellationToken token)
{
if (dst.Size != src.Size)
throw new ArgumentException ("dst.Size != src.Size");
return ApplyAsync (src, dst, dst.Bounds, token);
}
public Task ApplyAsync (ISurface src, ISurface dst, CancellationToken token, IRenderProgress progress)
{
if (dst.Size != src.Size)
throw new ArgumentException ("dst.Size != src.Size");
return ApplyAsync (src, dst, dst.Bounds, token, progress);
}
public Task ApplyAsync (ISurface src, ISurface dst, Rectangle roi)
{
return ApplyAsync (src, dst, dst.Bounds, CancellationToken.None);
}
public Task ApplyAsync (ISurface src, ISurface dst, Rectangle roi, CancellationToken token)
{
return Task.Factory.StartNew (() => ApplyLoop (src, dst, dst.Bounds, token, null));
}
public Task ApplyAsync (ISurface src, ISurface dst, Rectangle roi, CancellationToken token, IRenderProgress progress)
{
return Task.Factory.StartNew (() => ApplyLoop (src, dst, dst.Bounds, token, progress));
}
public Task ApplyAsync (ISurface lhs, ISurface rhs, ISurface dst)
{
if (dst.Size != lhs.Size)
throw new ArgumentException ("dst.Size != lhs.Size");
if (lhs.Size != rhs.Size)
throw new ArgumentException ("lhs.Size != rhs.Size");
return ApplyAsync (lhs, rhs, dst, dst.Bounds, CancellationToken.None);
}
public Task ApplyAsync (ISurface lhs, ISurface rhs, ISurface dst, CancellationToken token)
{
if (dst.Size != lhs.Size)
throw new ArgumentException ("dst.Size != lhs.Size");
if (lhs.Size != rhs.Size)
throw new ArgumentException ("lhs.Size != rhs.Size");
return ApplyAsync (lhs, rhs, dst, dst.Bounds, token);
}
public Task ApplyAsync (ISurface lhs, ISurface rhs, ISurface dst, Rectangle roi)
{
return ApplyAsync (lhs, rhs, dst, roi, CancellationToken.None);
}
public Task ApplyAsync (ISurface lhs, ISurface rhs, ISurface dst, Rectangle roi, CancellationToken token)
{
return Task.Factory.StartNew (() => ApplyLoop (lhs, rhs, dst, dst.Bounds, token, null));
}
public Task ApplyAsync (ISurface lhs, ISurface rhs, ISurface dst, Rectangle roi, CancellationToken token, IRenderProgress progress)
{
return Task.Factory.StartNew (() => ApplyLoop (lhs, rhs, dst, dst.Bounds, token, progress));
}
public virtual void Apply (ColorBgra* lhs, ColorBgra* rhs, ColorBgra* dst, int length)
{
unsafe {
while (length > 0) {
*dst = Apply (*lhs, *rhs);
++dst;
++lhs;
++rhs;
--length;
}
}
}
public unsafe override void Apply (ColorBgra* src, ColorBgra* dst, int length)
{
unsafe {
while (length > 0) {
*dst = Apply (*dst, *src);
++dst;
++src;
--length;
}
}
}
protected void ApplyLoop (ISurface src, ISurface dst, Rectangle roi, CancellationToken token, IRenderProgress progress)
{
src.BeginUpdate ();
dst.BeginUpdate ();
var completed_lines = new bool[roi.Height];
var last_completed_index = 0;
if (Settings.SingleThreaded || roi.Height <= 1) {
for (var y = roi.Y; y <= roi.Bottom; ++y) {
if (token.IsCancellationRequested)
return;
var dstPtr = dst.GetRowAddress (y);
var srcPtr = src.GetRowAddress (y);
Apply (srcPtr, dstPtr, roi.Width);
completed_lines[y - roi.Top] = true;
if (progress != null) {
var last_y = FindLastCompletedLine (completed_lines, last_completed_index);
last_completed_index = last_y;
progress.CompletedRoi = new Rectangle (roi.X, roi.Y, roi.Width, last_y);
progress.PercentComplete = (float)last_y / (float)roi.Height;
}
}
} else {
ParallelExtensions.OrderedFor (roi.Y, roi.Bottom + 1, token, (y) => {
var dstPtr = dst.GetRowAddress (y);
var srcPtr = src.GetRowAddress (y);
Apply (srcPtr, dstPtr, roi.Width);
completed_lines[y - roi.Top] = true;
if (progress != null) {
var last_y = FindLastCompletedLine (completed_lines, last_completed_index);
last_completed_index = last_y;
progress.CompletedRoi = new Rectangle (roi.X, roi.Y, roi.Width, last_y);
progress.PercentComplete = (float)last_y / (float)roi.Height;
}
});
}
src.EndUpdate ();
dst.EndUpdate ();
}
protected void ApplyLoop (ISurface lhs, ISurface rhs, ISurface dst, Rectangle roi, CancellationToken token, IRenderProgress progress)
{
var completed_lines = new bool[roi.Height];
var last_completed_index = 0;
if (Settings.SingleThreaded || roi.Height <= 1) {
for (var y = roi.Y; y <= roi.Bottom; ++y) {
if (token.IsCancellationRequested)
return;
var dstPtr = dst.GetRowAddress (y);
var lhsPtr = lhs.GetRowAddress (y);
var rhsPtr = rhs.GetRowAddress (y);
Apply (lhsPtr, rhsPtr, dstPtr, roi.Width);
completed_lines[y - roi.Top] = true;
if (progress != null) {
var last_y = FindLastCompletedLine (completed_lines, last_completed_index);
last_completed_index = last_y;
progress.CompletedRoi = new Rectangle (roi.X, roi.Y, roi.Width, last_y);
progress.PercentComplete = (float)last_y / (float)roi.Height;
}
}
} else {
ParallelExtensions.OrderedFor (roi.Y, roi.Bottom + 1, token, (y) => {
var dstPtr = dst.GetRowAddress (y);
var lhsPtr = lhs.GetRowAddress (y);
var rhsPtr = rhs.GetRowAddress (y);
Apply (lhsPtr, rhsPtr, dstPtr, roi.Width);
completed_lines[y - roi.Top] = true;
if (progress != null) {
var last_y = FindLastCompletedLine (completed_lines, last_completed_index);
last_completed_index = last_y;
progress.CompletedRoi = new Rectangle (roi.X, roi.Y, roi.Width, last_y);
progress.PercentComplete = (float)last_y / (float)roi.Height;
}
});
}
}
// We always want to return a contiguous roi of lines completed, even
// if it means we don't report some lines that we've already completed.
private int FindLastCompletedLine (bool[] lines, int start)
{
for (var i = start; i < lines.Length; i++)
if (!lines[i])
return Math.Max (i - 1, 0);
return lines.Length - 1;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Palmmedia.ReportGenerator.Core.Common;
using Palmmedia.ReportGenerator.Core.Logging;
using Palmmedia.ReportGenerator.Core.Parser.Analysis;
using Palmmedia.ReportGenerator.Core.Properties;
using Palmmedia.ReportGenerator.Core.Reporting.Builders.Rendering;
namespace Palmmedia.ReportGenerator.Core.Reporting.Builders
{
/// <summary>
/// Creates summary report in XML format (no reports for classes are generated).
/// </summary>
public class XmlSummaryReportBuilder : IReportBuilder
{
/// <summary>
/// The Logger.
/// </summary>
private static readonly ILogger Logger = LoggerFactory.GetLogger(typeof(XmlSummaryReportBuilder));
/// <summary>
/// Gets the report type.
/// </summary>
/// <value>
/// The report format.
/// </value>
public virtual string ReportType => "XmlSummary";
/// <summary>
/// Gets or sets the report context.
/// </summary>
/// <value>
/// The report context.
/// </value>
public IReportContext ReportContext { get; set; }
/// <summary>
/// Creates a class report.
/// </summary>
/// <param name="class">The class.</param>
/// <param name="fileAnalyses">The file analyses that correspond to the class.</param>
public virtual void CreateClassReport(Class @class, IEnumerable<FileAnalysis> fileAnalyses)
{
}
/// <summary>
/// Creates the summary report.
/// </summary>
/// <param name="summaryResult">The summary result.</param>
public void CreateSummaryReport(SummaryResult summaryResult)
{
var rootElement = new XElement("CoverageReport", new XAttribute("scope", "Summary"));
var summaryElement = new XElement("Summary");
summaryElement.Add(new XElement("Generatedon", DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToLongTimeString()));
summaryElement.Add(new XElement("Parser", summaryResult.UsedParser));
summaryElement.Add(new XElement("Assemblies", summaryResult.Assemblies.Count().ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Classes", summaryResult.Assemblies.SelectMany(a => a.Classes).Count().ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Files", summaryResult.Assemblies.SelectMany(a => a.Classes).SelectMany(a => a.Files).Distinct().Count().ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Coveredlines", summaryResult.CoveredLines.ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Uncoveredlines", (summaryResult.CoverableLines - summaryResult.CoveredLines).ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Coverablelines", summaryResult.CoverableLines.ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Totallines", summaryResult.TotalLines.GetValueOrDefault().ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Linecoverage", summaryResult.CoverageQuota.HasValue ? summaryResult.CoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
if (summaryResult.CoveredBranches.HasValue && summaryResult.TotalBranches.HasValue)
{
summaryElement.Add(new XElement("Coveredbranches", summaryResult.CoveredBranches.GetValueOrDefault().ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Totalbranches", summaryResult.TotalBranches.GetValueOrDefault().ToString(CultureInfo.InvariantCulture)));
if (summaryResult.BranchCoverageQuota.HasValue)
{
summaryElement.Add(new XElement("Branchcoverage", summaryResult.BranchCoverageQuota.Value.ToString(CultureInfo.InvariantCulture)));
}
}
summaryElement.Add(new XElement("Coveredmethods", summaryResult.CoveredCodeElements.ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Totalmethods", summaryResult.TotalCodeElements.ToString(CultureInfo.InvariantCulture)));
summaryElement.Add(new XElement("Methodcoverage", summaryResult.CodeElementCoverageQuota.HasValue ? summaryResult.CodeElementCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
if (this.ReportContext.ReportConfiguration.Title != null)
{
summaryElement.Add(new XElement("Title", this.ReportContext.ReportConfiguration.Title));
}
if (this.ReportContext.ReportConfiguration.Tag != null)
{
summaryElement.Add(new XElement("Tag", this.ReportContext.ReportConfiguration.Tag));
}
rootElement.Add(summaryElement);
var sumableMetrics = summaryResult.SumableMetrics;
if (sumableMetrics.Count > 0)
{
var metricsElement = new XElement("Metrics");
var metricElement = new XElement("Element", new XAttribute("name", "Total"));
foreach (var m in sumableMetrics)
{
var element = new XElement(StringHelper.ReplaceNonLetterChars(m.Name));
if (m.Value.HasValue)
{
element.Value = m.Value.Value.ToString(CultureInfo.InvariantCulture);
}
metricElement.Add(element);
}
metricsElement.Add(metricElement);
rootElement.Add(metricsElement);
}
var coverageElement = new XElement("Coverage");
foreach (var assembly in summaryResult.Assemblies)
{
var assemblyElement = new XElement("Assembly");
assemblyElement.Add(new XAttribute("name", assembly.Name));
assemblyElement.Add(new XAttribute("classes", assembly.Classes.Count().ToString(CultureInfo.InvariantCulture)));
assemblyElement.Add(new XAttribute("coverage", assembly.CoverageQuota.HasValue ? assembly.CoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
assemblyElement.Add(new XAttribute("coveredlines", assembly.CoveredLines.ToString(CultureInfo.InvariantCulture)));
assemblyElement.Add(new XAttribute("coverablelines", assembly.CoverableLines.ToString(CultureInfo.InvariantCulture)));
assemblyElement.Add(new XAttribute("totallines", assembly.TotalLines.HasValue ? assembly.TotalLines.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
assemblyElement.Add(new XAttribute("branchcoverage", assembly.BranchCoverageQuota.HasValue ? assembly.BranchCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
assemblyElement.Add(new XAttribute("coveredbranches", assembly.CoveredBranches.HasValue ? assembly.CoveredBranches.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
assemblyElement.Add(new XAttribute("totalbranches", assembly.TotalBranches.HasValue ? assembly.TotalBranches.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
assemblyElement.Add(new XAttribute("coveredmethods", assembly.CoveredCodeElements.ToString(CultureInfo.InvariantCulture)));
assemblyElement.Add(new XAttribute("totalmethods", assembly.TotalCodeElements.ToString(CultureInfo.InvariantCulture)));
assemblyElement.Add(new XAttribute("methodcoverage", assembly.CodeElementCoverageQuota.HasValue ? assembly.CodeElementCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
foreach (var @class in assembly.Classes)
{
var classElement = new XElement("Class");
classElement.Add(new XAttribute("name", @class.Name));
classElement.Add(new XAttribute("coverage", @class.CoverageQuota.HasValue ? @class.CoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
classElement.Add(new XAttribute("coveredlines", @class.CoveredLines.ToString(CultureInfo.InvariantCulture)));
classElement.Add(new XAttribute("coverablelines", @class.CoverableLines.ToString(CultureInfo.InvariantCulture)));
classElement.Add(new XAttribute("totallines", @class.TotalLines.HasValue ? @class.TotalLines.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
classElement.Add(new XAttribute("branchcoverage", @class.BranchCoverageQuota.HasValue ? @class.BranchCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
classElement.Add(new XAttribute("coveredbranches", @class.CoveredBranches.HasValue ? @class.CoveredBranches.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
classElement.Add(new XAttribute("totalbranches", @class.TotalBranches.HasValue ? @class.TotalBranches.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
classElement.Add(new XAttribute("coveredmethods", @class.CoveredCodeElements.ToString(CultureInfo.InvariantCulture)));
classElement.Add(new XAttribute("totalmethods", @class.TotalCodeElements.ToString(CultureInfo.InvariantCulture)));
classElement.Add(new XAttribute("methodcoverage", @class.CodeElementCoverageQuota.HasValue ? @class.CodeElementCoverageQuota.Value.ToString(CultureInfo.InvariantCulture) : string.Empty));
assemblyElement.Add(classElement);
}
coverageElement.Add(assemblyElement);
}
rootElement.Add(coverageElement);
XDocument result = new XDocument(new XDeclaration("1.0", "utf-8", null), rootElement);
string targetPath = Path.Combine(
this.CreateTargetDirectory(),
"Summary.xml");
Logger.InfoFormat(Resources.WritingReportFile, targetPath);
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = new UTF8Encoding(false),
Indent = true
};
using (XmlWriter writer = XmlWriter.Create(targetPath, settings))
{
result.Save(writer);
}
}
/// <summary>
/// Creates the target directory.
/// </summary>
/// <returns>The target directory.</returns>
protected string CreateTargetDirectory()
{
string targetDirectory = this.ReportContext.ReportConfiguration.TargetDirectory;
if (this.ReportContext.Settings.CreateSubdirectoryForAllReportTypes)
{
targetDirectory = Path.Combine(targetDirectory, this.ReportType);
if (!Directory.Exists(targetDirectory))
{
try
{
Directory.CreateDirectory(targetDirectory);
}
catch (Exception ex)
{
Logger.ErrorFormat(Resources.TargetDirectoryCouldNotBeCreated, targetDirectory, ex.GetExceptionMessageForDisplay());
throw;
}
}
}
return targetDirectory;
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.IO;
using System.Reflection.Internal;
using System.Reflection.Metadata;
using System.Threading;
namespace System.Reflection.PortableExecutable
{
/// <summary>
/// Portable Executable format reader.
/// </summary>
/// <remarks>
/// The implementation is thread-safe, that is multiple threads can read data from the reader in parallel.
/// Disposal of the reader is not thread-safe (see <see cref="Dispose"/>).
/// </remarks>
public sealed class PEReader : IDisposable
{
// May be null in the event that the entire image is not
// deemed necessary and we have been instructed to read
// the image contents without being lazy.
private MemoryBlockProvider _peImage;
// If we read the data from the image lazily (peImage != null) we defer reading the PE headers.
private PEHeaders _lazyPEHeaders;
private AbstractMemoryBlock _lazyMetadataBlock;
private AbstractMemoryBlock _lazyImageBlock;
private AbstractMemoryBlock[] _lazyPESectionBlocks;
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in memory.
/// </summary>
/// <param name="peImage">Pointer to the start of the PE image.</param>
/// <param name="size">The size of the PE image.</param>
/// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception>
/// <remarks>
/// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>.
/// The caller is responsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>.
/// The content of the image is not read during the construction of the <see cref="PEReader"/>
/// </remarks>
public unsafe PEReader(byte* peImage, int size)
{
if (peImage == null)
{
throw new ArgumentNullException(nameof(peImage));
}
if (size < 0)
{
throw new ArgumentOutOfRangeException(nameof(size));
}
_peImage = new ExternalMemoryBlockProvider(peImage, size);
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a stream.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <remarks>
/// Ownership of the stream is transferred to the <see cref="PEReader"/> upon successful validation of constructor arguments. It will be
/// disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
/// </remarks>
public PEReader(Stream peStream)
: this(peStream, PEStreamOptions.Default)
{
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a stream beginning at its current position and ending at the end of the stream.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <param name="options">
/// Options specifying how sections of the PE image are read from the stream.
///
/// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/>
/// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
///
/// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data
/// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated
/// by caller while the <see cref="PEReader"/> is alive and undisposed.
///
/// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/>
/// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also
/// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/>
/// after construction.
/// </param>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception>
/// <exception cref="BadImageFormatException">
/// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid.
/// </exception>
public PEReader(Stream peStream, PEStreamOptions options)
: this(peStream, options, 0)
{
}
/// <summary>
/// Creates a Portable Executable reader over a PE image of the given size beginning at the stream's current position.
/// </summary>
/// <param name="peStream">PE image stream.</param>
/// <param name="size">PE image size.</param>
/// <param name="options">
/// Options specifying how sections of the PE image are read from the stream.
///
/// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/>
/// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it.
///
/// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data
/// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated
/// by caller while the <see cref="PEReader"/> is alive and undisposed.
///
/// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/>
/// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also
/// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/>
/// after construction.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
public unsafe PEReader(Stream peStream, PEStreamOptions options, int size)
{
if (peStream == null)
{
throw new ArgumentNullException(nameof(peStream));
}
if (!peStream.CanRead || !peStream.CanSeek)
{
throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream));
}
if (!options.IsValid())
{
throw new ArgumentOutOfRangeException(nameof(options));
}
long start = peStream.Position;
int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream));
bool closeStream = true;
try
{
bool isFileStream = FileStreamReadLightUp.IsFileStream(peStream);
if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0)
{
_peImage = new StreamMemoryBlockProvider(peStream, start, actualSize, isFileStream, (options & PEStreamOptions.LeaveOpen) != 0);
closeStream = false;
}
else
{
// Read in the entire image or metadata blob:
if ((options & PEStreamOptions.PrefetchEntireImage) != 0)
{
var imageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, start, actualSize);
_lazyImageBlock = imageBlock;
_peImage = new ExternalMemoryBlockProvider(imageBlock.Pointer, imageBlock.Size);
// if the caller asked for metadata initialize the PE headers (calculates metadata offset):
if ((options & PEStreamOptions.PrefetchMetadata) != 0)
{
InitializePEHeaders();
}
}
else
{
// The peImage is left null, but the lazyMetadataBlock is initialized up front.
_lazyPEHeaders = new PEHeaders(peStream);
_lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, _lazyPEHeaders.MetadataStartOffset, _lazyPEHeaders.MetadataSize);
}
// We read all we need, the stream is going to be closed.
}
}
finally
{
if (closeStream && (options & PEStreamOptions.LeaveOpen) == 0)
{
peStream.Dispose();
}
}
}
/// <summary>
/// Creates a Portable Executable reader over a PE image stored in a byte array.
/// </summary>
/// <param name="peImage">PE image.</param>
/// <remarks>
/// The content of the image is not read during the construction of the <see cref="PEReader"/>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception>
public PEReader(ImmutableArray<byte> peImage)
{
if (peImage.IsDefault)
{
throw new ArgumentNullException(nameof(peImage));
}
_peImage = new ByteArrayMemoryProvider(peImage);
}
/// <summary>
/// Disposes all memory allocated by the reader.
/// </summary>
/// <remarks>
/// <see cref="Dispose"/> can be called multiple times (but not in parallel).
/// It is not safe to call <see cref="Dispose"/> in parallel with any other operation on the <see cref="PEReader"/>
/// or reading from <see cref="PEMemoryBlock"/>s retrieved from the reader.
/// </remarks>
public void Dispose()
{
_peImage?.Dispose();
_peImage = null;
_lazyImageBlock?.Dispose();
_lazyImageBlock = null;
_lazyMetadataBlock?.Dispose();
_lazyMetadataBlock = null;
var peSectionBlocks = _lazyPESectionBlocks;
if (peSectionBlocks != null)
{
foreach (var block in peSectionBlocks)
{
block?.Dispose();
}
_lazyPESectionBlocks = null;
}
}
/// <summary>
/// Gets the PE headers.
/// </summary>
/// <exception cref="BadImageFormatException">The headers contain invalid data.</exception>
public PEHeaders PEHeaders
{
get
{
if (_lazyPEHeaders == null)
{
InitializePEHeaders();
}
return _lazyPEHeaders;
}
}
private void InitializePEHeaders()
{
Debug.Assert(_peImage != null);
StreamConstraints constraints;
Stream stream = _peImage.GetStream(out constraints);
PEHeaders headers;
if (constraints.GuardOpt != null)
{
lock (constraints.GuardOpt)
{
headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize);
}
}
else
{
headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize);
}
Interlocked.CompareExchange(ref _lazyPEHeaders, headers, null);
}
private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize)
{
Debug.Assert(imageStartPosition >= 0 && imageStartPosition <= stream.Length);
stream.Seek(imageStartPosition, SeekOrigin.Begin);
return new PEHeaders(stream, imageSize);
}
/// <summary>
/// Returns a view of the entire image as a pointer and length.
/// </summary>
/// <exception cref="InvalidOperationException">PE image not available.</exception>
private AbstractMemoryBlock GetEntireImageBlock()
{
if (_lazyImageBlock == null)
{
if (_peImage == null)
{
throw new InvalidOperationException(SR.PEImageNotAvailable);
}
var newBlock = _peImage.GetMemoryBlock();
if (Interlocked.CompareExchange(ref _lazyImageBlock, newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
}
return _lazyImageBlock;
}
private AbstractMemoryBlock GetMetadataBlock()
{
if (!HasMetadata)
{
throw new InvalidOperationException(SR.PEImageDoesNotHaveMetadata);
}
if (_lazyMetadataBlock == null)
{
Debug.Assert(_peImage != null, "We always have metadata if peImage is not available.");
var newBlock = _peImage.GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize);
if (Interlocked.CompareExchange(ref _lazyMetadataBlock, newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
}
return _lazyMetadataBlock;
}
private AbstractMemoryBlock GetPESectionBlock(int index)
{
Debug.Assert(index >= 0 && index < PEHeaders.SectionHeaders.Length);
Debug.Assert(_peImage != null);
if (_lazyPESectionBlocks == null)
{
Interlocked.CompareExchange(ref _lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null);
}
var newBlock = _peImage.GetMemoryBlock(
PEHeaders.SectionHeaders[index].PointerToRawData,
PEHeaders.SectionHeaders[index].SizeOfRawData);
if (Interlocked.CompareExchange(ref _lazyPESectionBlocks[index], newBlock, null) != null)
{
// another thread created the block already, we need to dispose ours:
newBlock.Dispose();
}
return _lazyPESectionBlocks[index];
}
/// <summary>
/// Return true if the reader can access the entire PE image.
/// </summary>
/// <remarks>
/// Returns false if the <see cref="PEReader"/> is constructed from a stream and only part of it is prefetched into memory.
/// </remarks>
public bool IsEntireImageAvailable
{
get { return _lazyImageBlock != null || _peImage != null; }
}
/// <summary>
/// Gets a pointer to and size of the PE image if available (<see cref="IsEntireImageAvailable"/>).
/// </summary>
/// <exception cref="InvalidOperationException">The entire PE image is not available.</exception>
public PEMemoryBlock GetEntireImage()
{
return new PEMemoryBlock(GetEntireImageBlock());
}
/// <summary>
/// Returns true if the PE image contains CLI metadata.
/// </summary>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public bool HasMetadata
{
get { return PEHeaders.MetadataSize > 0; }
}
/// <summary>
/// Loads PE section that contains CLI metadata.
/// </summary>
/// <exception cref="InvalidOperationException">The PE image doesn't contain metadata (<see cref="HasMetadata"/> returns false).</exception>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public PEMemoryBlock GetMetadata()
{
return new PEMemoryBlock(GetMetadataBlock());
}
/// <summary>
/// Loads PE section that contains the specified <paramref name="relativeVirtualAddress"/> into memory
/// and returns a memory block that starts at <paramref name="relativeVirtualAddress"/> and ends at the end of the containing section.
/// </summary>
/// <param name="relativeVirtualAddress">Relative Virtual Address of the data to read.</param>
/// <returns>
/// An empty block if <paramref name="relativeVirtualAddress"/> doesn't represent a location in any of the PE sections of this PE image.
/// </returns>
/// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception>
public PEMemoryBlock GetSectionData(int relativeVirtualAddress)
{
var sectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress);
if (sectionIndex < 0)
{
return default(PEMemoryBlock);
}
int relativeOffset = relativeVirtualAddress - PEHeaders.SectionHeaders[sectionIndex].VirtualAddress;
int size = PEHeaders.SectionHeaders[sectionIndex].VirtualSize - relativeOffset;
AbstractMemoryBlock block;
if (_peImage != null)
{
block = GetPESectionBlock(sectionIndex);
}
else
{
block = GetEntireImageBlock();
relativeOffset += PEHeaders.SectionHeaders[sectionIndex].PointerToRawData;
}
return new PEMemoryBlock(block, relativeOffset);
}
/// <summary>
/// Reads all Debug Directory table entries.
/// </summary>
/// <exception cref="BadImageFormatException">Bad format of the entry.</exception>
public unsafe ImmutableArray<DebugDirectoryEntry> ReadDebugDirectory()
{
var debugDirectory = PEHeaders.PEHeader.DebugTableDirectory;
if (debugDirectory.Size == 0)
{
return ImmutableArray<DebugDirectoryEntry>.Empty;
}
int position;
if (!PEHeaders.TryGetDirectoryOffset(debugDirectory, out position))
{
throw new BadImageFormatException(SR.InvalidDirectoryRVA);
}
const int entrySize = 0x1c;
if (debugDirectory.Size % entrySize != 0)
{
throw new BadImageFormatException(SR.InvalidDirectorySize);
}
using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(position, debugDirectory.Size))
{
var reader = new BlobReader(block.Pointer, block.Size);
int entryCount = debugDirectory.Size / entrySize;
var builder = ImmutableArray.CreateBuilder<DebugDirectoryEntry>(entryCount);
for (int i = 0; i < entryCount; i++)
{
// Reserved, must be zero.
int characteristics = reader.ReadInt32();
if (characteristics != 0)
{
throw new BadImageFormatException(SR.InvalidDebugDirectoryEntryCharacteristics);
}
uint stamp = reader.ReadUInt32();
ushort majorVersion = reader.ReadUInt16();
ushort minorVersion = reader.ReadUInt16();
var type = (DebugDirectoryEntryType)reader.ReadInt32();
int dataSize = reader.ReadInt32();
int dataRva = reader.ReadInt32();
int dataPointer = reader.ReadInt32();
builder.Add(new DebugDirectoryEntry(stamp, majorVersion, minorVersion, type, dataSize, dataRva, dataPointer));
}
return builder.MoveToImmutable();
}
}
/// <summary>
/// Reads the data pointed to by the specified Debug Directory entry and interprets them as CodeView.
/// </summary>
/// <exception cref="ArgumentException"><paramref name="entry"/> is not a CodeView entry.</exception>
/// <exception cref="BadImageFormatException">Bad format of the data.</exception>
public unsafe CodeViewDebugDirectoryData ReadCodeViewDebugDirectoryData(DebugDirectoryEntry entry)
{
if (entry.Type != DebugDirectoryEntryType.CodeView)
{
throw new ArgumentException(SR.NotCodeViewEntry, nameof(entry));
}
using (AbstractMemoryBlock block = _peImage.GetMemoryBlock(entry.DataPointer, entry.DataSize))
{
var reader = new BlobReader(block.Pointer, block.Size);
if (reader.ReadByte() != (byte)'R' ||
reader.ReadByte() != (byte)'S' ||
reader.ReadByte() != (byte)'D' ||
reader.ReadByte() != (byte)'S')
{
throw new BadImageFormatException(SR.UnexpectedCodeViewDataSignature);
}
Guid guid = reader.ReadGuid();
int age = reader.ReadInt32();
string path = reader.ReadUtf8NullTerminated();
// path may be padded with NULs
while (reader.RemainingBytes > 0)
{
if (reader.ReadByte() != 0)
{
throw new BadImageFormatException(SR.InvalidPathPadding);
}
}
return new CodeViewDebugDirectoryData(guid, age, path);
}
}
}
}
| |
// 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.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using CFStringRef = System.IntPtr;
using CFArrayRef = System.IntPtr;
using FSEventStreamRef = System.IntPtr;
using size_t = System.IntPtr;
using FSEventStreamEventId = System.UInt64;
using CFTimeInterval = System.Double;
using CFRunLoopRef = System.IntPtr;
internal static partial class Interop
{
internal static partial class EventStream
{
/// <summary>
/// This constant specifies that we don't want historical file system events, only new ones
/// </summary>
internal const ulong kFSEventStreamEventIdSinceNow = 0xFFFFFFFFFFFFFFFF;
/// <summary>
/// Flags that describe what happened in the event that was received. These come from the FSEvents.h header file in the CoreServices framework.
/// </summary>
[Flags]
internal enum FSEventStreamEventFlags : uint
{
/* flags when creating the stream. */
kFSEventStreamEventFlagNone = 0x00000000,
kFSEventStreamEventFlagMustScanSubDirs = 0x00000001,
kFSEventStreamEventFlagUserDropped = 0x00000002,
kFSEventStreamEventFlagKernelDropped = 0x00000004,
kFSEventStreamEventFlagEventIdsWrapped = 0x00000008,
kFSEventStreamEventFlagHistoryDone = 0x00000010,
kFSEventStreamEventFlagRootChanged = 0x00000020,
kFSEventStreamEventFlagMount = 0x00000040,
kFSEventStreamEventFlagUnmount = 0x00000080,
/* These flags are only set if you specified the FileEvents */
kFSEventStreamEventFlagItemCreated = 0x00000100,
kFSEventStreamEventFlagItemRemoved = 0x00000200,
kFSEventStreamEventFlagItemInodeMetaMod = 0x00000400,
kFSEventStreamEventFlagItemRenamed = 0x00000800,
kFSEventStreamEventFlagItemModified = 0x00001000,
kFSEventStreamEventFlagItemFinderInfoMod = 0x00002000,
kFSEventStreamEventFlagItemChangeOwner = 0x00004000,
kFSEventStreamEventFlagItemXattrMod = 0x00008000,
kFSEventStreamEventFlagItemIsFile = 0x00010000,
kFSEventStreamEventFlagItemIsDir = 0x00020000,
kFSEventStreamEventFlagItemIsSymlink = 0x00040000,
kFSEventStreamEventFlagOwnEvent = 0x00080000,
kFSEventStreamEventFlagItemIsHardlink = 0x00100000,
kFSEventStreamEventFlagItemIsLastHardlink = 0x00200000,
}
/// <summary>
/// Flags that describe what kind of event stream should be created (and therefore what events should be
/// piped into this stream). These come from the FSEvents.h header file in the CoreServices framework.
/// </summary>
[Flags]
internal enum FSEventStreamCreateFlags : uint
{
kFSEventStreamCreateFlagNone = 0x00000000,
kFSEventStreamCreateFlagUseCFTypes = 0x00000001,
kFSEventStreamCreateFlagNoDefer = 0x00000002,
kFSEventStreamCreateFlagWatchRoot = 0x00000004,
kFSEventStreamCreateFlagIgnoreSelf = 0x00000008,
kFSEventStreamCreateFlagFileEvents = 0x00000010
}
/// <summary>
/// The EventStream callback that will be called for every event batch.
/// </summary>
/// <param name="streamReference">The stream that was created for this callback.</param>
/// <param name="clientCallBackInfo">A pointer to optional context info; otherwise, IntPtr.Zero.</param>
/// <param name="numEvents">The number of paths, events, and IDs. Path[2] corresponds to Event[2] and ID[2], etc.</param>
/// <param name="eventPaths">The paths that have changed somehow, according to their corresponding event.</param>
/// <param name="eventFlags">The events for the corresponding path.</param>
/// <param name="eventIds">The machine-and-disk-drive-unique Event ID for the specific event.</param>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void FSEventStreamCallback(
FSEventStreamRef streamReference,
IntPtr clientCallBackInfo,
size_t numEvents,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
String[] eventPaths,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
FSEventStreamEventFlags[] eventFlags,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)]
FSEventStreamEventId[] eventIds);
/// <summary>
/// Internal wrapper to create a new EventStream to listen to events from the core OS (such as File System events).
/// </summary>
/// <param name="allocator">Should be IntPtr.Zero</param>
/// <param name="cb">A callback instance that will be called for every event batch.</param>
/// <param name="context">Should be IntPtr.Zero</param>
/// <param name="pathsToWatch">A CFArray of the path(s) to watch for events.</param>
/// <param name="sinceWhen">
/// The start point to receive events from. This can be to retrieve historical events or only new events.
/// To get historical events, pass in the corresponding ID of the event you want to start from.
/// To get only new events, pass in kFSEventStreamEventIdSinceNow.
/// </param>
/// <param name="latency">Coalescing period to wait before sending events.</param>
/// <param name="flags">Flags to say what kind of events should be sent through this stream.</param>
/// <returns>On success, returns a pointer to an FSEventStream object; otherwise, returns IntPtr.Zero</returns>
/// <remarks>For *nix systems, the CLR maps ANSI to UTF-8, so be explicit about that</remarks>
[DllImport(Interop.Libraries.CoreServicesLibrary, CharSet = CharSet.Ansi)]
private static extern SafeEventStreamHandle FSEventStreamCreate(
IntPtr allocator,
FSEventStreamCallback cb,
IntPtr context,
SafeCreateHandle pathsToWatch,
FSEventStreamEventId sinceWhen,
CFTimeInterval latency,
FSEventStreamCreateFlags flags);
/// <summary>
/// Creates a new EventStream to listen to events from the core OS (such as File System events).
/// </summary>
/// <param name="cb">A callback instance that will be called for every event batch.</param>
/// <param name="pathsToWatch">A CFArray of the path(s) to watch for events.</param>
/// <param name="sinceWhen">
/// The start point to receive events from. This can be to retrieve historical events or only new events.
/// To get historical events, pass in the corresponding ID of the event you want to start from.
/// To get only new events, pass in kFSEventStreamEventIdSinceNow.
/// </param>
/// <param name="latency">Coalescing period to wait before sending events.</param>
/// <param name="flags">Flags to say what kind of events should be sent through this stream.</param>
/// <returns>On success, returns a valid SafeCreateHandle to an FSEventStream object; otherwise, returns an invalid SafeCreateHandle</returns>
internal static SafeEventStreamHandle FSEventStreamCreate(
FSEventStreamCallback cb,
SafeCreateHandle pathsToWatch,
FSEventStreamEventId sinceWhen,
CFTimeInterval latency,
FSEventStreamCreateFlags flags)
{
return FSEventStreamCreate(IntPtr.Zero, cb, IntPtr.Zero, pathsToWatch, sinceWhen, latency, flags);
}
/// <summary>
/// Attaches an EventStream to a RunLoop so events can be received. This should usually be the current thread's RunLoop.
/// </summary>
/// <param name="streamRef">The stream to attach to the RunLoop</param>
/// <param name="runLoop">The RunLoop to attach the stream to</param>
/// <param name="runLoopMode">The mode of the RunLoop; this should usually be kCFRunLoopDefaultMode. See the documentation for RunLoops for more info.</param>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern void FSEventStreamScheduleWithRunLoop(
SafeEventStreamHandle streamRef,
CFRunLoopRef runLoop,
SafeCreateHandle runLoopMode);
/// <summary>
/// Starts receiving events on the specified stream.
/// </summary>
/// <param name="streamRef">The stream to receive events on.</param>
/// <returns>Returns true if the stream was started; otherwise, returns false and no events will be received.</returns>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern bool FSEventStreamStart(SafeEventStreamHandle streamRef);
/// <summary>
/// Stops receiving events on the specified stream. The stream can be restarted and not miss any events.
/// </summary>
/// <param name="streamRef">The stream to stop receiving events on.</param>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern void FSEventStreamStop(SafeEventStreamHandle streamRef);
/// <summary>
/// Stops receiving events on the specified stream. The stream can be restarted and not miss any events.
/// </summary>
/// <param name="streamRef">The stream to stop receiving events on.</param>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern void FSEventStreamStop(IntPtr streamRef);
/// <summary>
/// Invalidates an EventStream and removes it from any RunLoops.
/// </summary>
/// <param name="streamRef">The FSEventStream to invalidate</param>
/// <remarks>This can only be called after FSEventStreamScheduleWithRunLoop has be called</remarks>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern void FSEventStreamInvalidate(IntPtr streamRef);
/// <summary>
/// Removes the event stream from the RunLoop.
/// </summary>
/// <param name="streamRef">The stream to remove from the RunLoop</param>
/// <param name="runLoop">The RunLoop to remove the stream from.</param>
/// <param name="runLoopMode">The mode of the RunLoop; this should usually be kCFRunLoopDefaultMode. See the documentation for RunLoops for more info.</param>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern void FSEventStreamUnscheduleFromRunLoop(
SafeEventStreamHandle streamRef,
CFRunLoopRef runLoop,
SafeCreateHandle runLoopMode);
/// <summary>
/// Releases a reference count on the specified EventStream and, if necessary, cleans the stream up.
/// </summary>
/// <param name="streamRef">The stream on which to decrement the reference count.</param>
[DllImport(Interop.Libraries.CoreServicesLibrary)]
internal static extern void FSEventStreamRelease(IntPtr streamRef);
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines.CSharpRethrowToPreserveStackDetailsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines.BasicRethrowToPreserveStackDetailsAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests
{
public class RethrowToPreserveStackDetailsTests
{
[Fact]
public async Task CA2200_NoDiagnosticsForRethrow()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowImplicitly()
{
try
{
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
throw;
}
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New ArithmeticException()
Catch ex As Exception
Throw
End Try
End Sub
End Class
");
}
[Fact]
public async Task CA2200_NoDiagnosticsForThrowAnotherException()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitly()
{
try
{
throw new ArithmeticException();
throw new Exception();
}
catch (ArithmeticException e)
{
var i = new Exception();
throw i;
}
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New ArithmeticException()
Throw New Exception()
Catch ex As Exception
Dim i As New Exception()
Throw i
End Try
End Sub
End Class
");
}
[Fact]
public async Task CA2200_DiagnosticForThrowCaughtException()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitly()
{
try
{
ThrowException();
}
catch (ArithmeticException e)
{
throw e;
}
}
void ThrowException()
{
throw new ArithmeticException();
}
}
",
GetCA2200CSharpResultAt(14, 13));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New ArithmeticException()
Catch e As ArithmeticException
Throw e
End Try
End Sub
End Class
",
GetCA2200BasicResultAt(9, 13));
}
[Fact]
public async Task CA2200_NoDiagnosticsForThrowCaughtReassignedException()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitlyReassigned()
{
try
{
ThrowException();
}
catch (SystemException e)
{
e = new ArithmeticException();
throw e;
}
}
void ThrowException()
{
throw new SystemException();
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New Exception()
Catch e As Exception
e = New ArithmeticException()
Throw e
End Try
End Sub
End Class
");
}
[Fact]
public async Task CA2200_NoDiagnosticsForEmptyBlock()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitlyReassigned()
{
try
{
ThrowException();
}
catch (SystemException e)
{
}
}
void ThrowException()
{
throw new SystemException();
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New Exception()
Catch e As Exception
End Try
End Sub
End Class
");
}
[Fact]
public async Task CA2200_NoDiagnosticsForThrowCaughtExceptionInAnotherScope()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitly()
{
try
{
ThrowException();
}
catch (ArithmeticException e)
{
[|throw e;|]
}
}
void ThrowException()
{
throw new ArithmeticException();
}
}
");
}
[Fact]
public async Task CA2200_SingleDiagnosticForThrowCaughtExceptionInSpecificScope()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New ArithmeticException()
Catch e As ArithmeticException
[|Throw e|]
Catch e As Exception
Throw e
End Try
End Sub
End Class
",
GetCA2200BasicResultAt(11, 13));
}
[Fact]
public async Task CA2200_MultipleDiagnosticsForThrowCaughtExceptionAtMultiplePlaces()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitly()
{
try
{
ThrowException();
}
catch (ArithmeticException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
void ThrowException()
{
throw new ArithmeticException();
}
}
",
GetCA2200CSharpResultAt(14, 13),
GetCA2200CSharpResultAt(18, 13));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New ArithmeticException()
Catch e As ArithmeticException
Throw e
Catch e As Exception
Throw e
End Try
End Sub
End Class
",
GetCA2200BasicResultAt(9, 13),
GetCA2200BasicResultAt(11, 13));
}
[Fact]
public async Task CA2200_DiagnosticForThrowOuterCaughtException()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitly()
{
try
{
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
try
{
throw new ArithmeticException();
}
catch (ArithmeticException i)
{
throw e;
}
}
}
}
",
GetCA2200CSharpResultAt(20, 17));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Throw New ArithmeticException()
Catch e As ArithmeticException
Try
Throw New ArithmeticException()
Catch ex As Exception
Throw e
End Try
End Try
End Sub
End Class
",
GetCA2200BasicResultAt(12, 17));
}
[Fact]
public async Task CA2200_NoDiagnosticsForNestingWithCompileErrors()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrowExplicitly()
{
try
{
try
{
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
throw;
}
catch ({|CS0160:ArithmeticException|})
{
try
{
throw new ArithmeticException();
}
catch (ArithmeticException i)
{
throw {|CS0103:e|};
}
}
}
catch (Exception e)
{
throw;
}
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrowExplicitly()
Try
Try
Throw New ArithmeticException()
Catch ex As ArithmeticException
Throw
Catch i As ArithmeticException
Try
Throw New ArithmeticException()
Catch e As Exception
Throw {|BC30451:ex|}
End Try
End Try
Catch ex As Exception
Throw
End Try
End Sub
End Class
");
}
[Fact]
public async Task CA2200_NoDiagnosticsForCatchWithoutIdentifier()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrow(Exception exception)
{
try
{
}
catch (Exception)
{
var finalException = new InvalidOperationException(""aaa"", exception);
throw finalException;
}
}
}
");
}
[Fact]
[WorkItem(2167, "https://github.com/dotnet/roslyn-analyzers/issues/2167")]
public async Task CA2200_NoDiagnosticsForCatchWithoutArgument()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
class Program
{
void CatchAndRethrow(Exception exception)
{
try
{
}
catch
{
var finalException = new InvalidOperationException(""aaa"", exception);
throw finalException;
}
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Class Program
Sub CatchAndRethrow(exception As Exception)
Try
Catch
Dim finalException = new InvalidOperationException(""aaa"", exception)
Throw finalException
End Try
End Sub
End Class
");
}
private static DiagnosticResult GetCA2200BasicResultAt(int line, int column)
=> VerifyVB.Diagnostic()
.WithLocation(line, column);
private static DiagnosticResult GetCA2200CSharpResultAt(int line, int column)
=> VerifyCS.Diagnostic()
.WithLocation(line, column);
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Reflection;
using System.Threading;
using Gallio.Common.Collections;
using Gallio.Common;
using Gallio.Common.IO;
using Gallio.Common.Policies;
using Gallio.Runtime.Debugging;
namespace Gallio.Runtime.Hosting
{
/// <summary>
/// Specifies a collection of parameters for setting up a <see cref="IHost" />.
/// </summary>
[Serializable]
public sealed class HostSetup : IPropertySetContainer
{
private string applicationBaseDirectory;
private string workingDirectory;
private readonly List<string> hintDirectories;
private bool shadowCopy;
private DebuggerSetup debuggerSetup;
private string runtimeVersion;
private bool elevated;
private ConfigurationFileLocation configurationFileLocation = ConfigurationFileLocation.Temp;
private HostConfiguration configuration;
private ProcessorArchitecture processorArchitecture = ProcessorArchitecture.MSIL;
private readonly PropertySet properties;
/// <summary>
/// Creates a default host setup.
/// </summary>
public HostSetup()
{
hintDirectories = new List<string>();
properties = new PropertySet();
}
/// <summary>
/// Gets a read-only collection of configuration properties for the host.
/// </summary>
public PropertySet Properties
{
get { return properties.AsReadOnly(); }
}
/// <summary>
/// Gets or sets the relative or absolute path of the application base directory,
/// or null to use a default value selected by the consumer.
/// </summary>
/// <remarks>
/// <para>
/// If relative, the path is based on the current working directory,
/// so a value of "" causes the current working directory to be used.
/// </para>
/// <para>
/// Relative paths should be canonicalized as soon as possible.
/// See <see cref="Canonicalize" />.
/// </para>
/// </remarks>
/// <value>
/// The application base directory. Default is <c>null</c>.
/// </value>
public string ApplicationBaseDirectory
{
get { return applicationBaseDirectory; }
set { applicationBaseDirectory = value; }
}
/// <summary>
/// Gets or sets the relative or absolute path of the working directory
/// or null to use a default value selected by the consumer.
/// </summary>
/// <remarks>
/// <para>
/// If relative, the path is based on the current working directory,
/// so a value of "" causes the current working directory to be used.
/// </para>
/// <para>
/// Relative paths should be canonicalized as soon as possible.
/// See <see cref="Canonicalize" />.
/// </para>
/// </remarks>
/// <value>
/// The working directory. Default is <c>null</c>.
/// </value>
public string WorkingDirectory
{
get { return workingDirectory; }
set { workingDirectory = value; }
}
/// <summary>
/// Gets the read-only list of relative or absolute paths of
/// hint directories used to resolve assemblies.
/// </summary>
/// <remarks>
/// <para>
/// If relative, the path is based on the current working directory,
/// so a value of "" causes the current working directory to be used.
/// </para>
/// <para>
/// Relative paths should be canonicalized as soon as possible.
/// See <see cref="Canonicalize" />.
/// </para>
/// </remarks>
public IList<string> HintDirectories
{
get { return new ReadOnlyCollection<string>(hintDirectories); }
}
/// <summary>
/// Gets or sets whether assembly shadow copying is enabled.
/// </summary>
/// <value>True if shadow copying is enabled. Default is <c>false</c>.</value>
public bool ShadowCopy
{
get { return shadowCopy; }
set { shadowCopy = value; }
}
/// <summary>
/// Gets or sets the debugger setup options, or null if not debugging.
/// </summary>
/// <value>The debugger setup options. Default is <c>null</c>.</value>
public DebuggerSetup DebuggerSetup
{
get { return debuggerSetup; }
set { debuggerSetup = value; }
}
/// <summary>
/// Gets or sets the .Net runtime version of the host, or null to auto-detect.
/// </summary>
/// <value>The runtime version, eg. "v2.0.50727". Default is <c>null</c>.</value>
public string RuntimeVersion
{
get { return runtimeVersion; }
set { runtimeVersion = value; }
}
/// <summary>
/// Gets or sets whether the host should run with elevated privileges.
/// </summary>
/// <value>True if the host should have elevated privileges. Default is <c>false</c>.</value>
public bool Elevated
{
get { return elevated; }
set { elevated = value; }
}
/// <summary>
/// Gets or sets where the host should write out the configuration file for the hosted components.
/// </summary>
/// <value>The configuration file location. Default is <see cref="Hosting.ConfigurationFileLocation.Temp" />.</value>
public ConfigurationFileLocation ConfigurationFileLocation
{
get { return configurationFileLocation; }
set { configurationFileLocation = value; }
}
/// <summary>
/// Gets or sets the host configuration information.
/// </summary>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
public HostConfiguration Configuration
{
get
{
if (configuration == null)
Interlocked.CompareExchange(ref configuration, new HostConfiguration(), null);
return configuration;
}
set
{
if (value == null)
throw new ArgumentNullException("value");
configuration = value;
}
}
/// <summary>
/// Gets or sets the processor architecture that the host should target, when supported.
/// </summary>
/// <value>The processor architecture. Default is <see cref="System.Reflection.ProcessorArchitecture.MSIL" /></value>
public ProcessorArchitecture ProcessorArchitecture
{
get { return processorArchitecture; }
set { processorArchitecture = value; }
}
/// <summary>
/// Clears the list of hint directories.
/// </summary>
public void ClearHintDirectories()
{
hintDirectories.Clear();
}
/// <summary>
/// Adds the relative or absolute path of a hint directory if it is not already in the host setup.
/// </summary>
/// <remarks>
/// <para>
/// If relative, the path is based on the current working directory,
/// so a value of "" causes the current working directory to be used.
/// </para>
/// <para>
/// Relative paths should be canonicalized as soon as possible.
/// See <see cref="Canonicalize" />.
/// </para>
/// </remarks>
/// <param name="directory">The directory to add.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="directory"/> is null.</exception>
public void AddHintDirectory(string directory)
{
if (directory == null)
throw new ArgumentNullException("directory");
if (! hintDirectories.Contains(directory))
hintDirectories.Add(directory);
}
/// <summary>
/// Removes a hint directory.
/// </summary>
/// <param name="directory">The directory to remove.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="directory"/> is null.</exception>
public void RemoveHintDirectory(string directory)
{
if (directory == null)
throw new ArgumentNullException("directory");
hintDirectories.Remove(directory);
}
/// <summary>
/// Clears the collection of properties.
/// </summary>
public void ClearProperties()
{
properties.Clear();
}
/// <summary>
/// Adds a property key/value pair.
/// </summary>
/// <param name="key">The property key.</param>
/// <param name="value">The property value.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="key"/> or <paramref name="value"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown if <paramref name="key"/> is already in the property set.</exception>
public void AddProperty(string key, string value)
{
properties.Add(key, value); // note: implicitly checks arguments
}
/// <summary>
/// Removes a property key/value pair.
/// </summary>
/// <param name="key">The property key.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="key"/> is null.</exception>
public void RemoveProperty(string key)
{
properties.Remove(key); // note: implicitly checks arguments
}
/// <summary>
/// Creates a copy of the host setup information.
/// </summary>
/// <returns>The copy.</returns>
public HostSetup Copy()
{
HostSetup copy = new HostSetup();
copy.applicationBaseDirectory = applicationBaseDirectory;
copy.workingDirectory = workingDirectory;
copy.hintDirectories.AddRange(hintDirectories);
copy.shadowCopy = shadowCopy;
if (debuggerSetup != null)
copy.debuggerSetup = debuggerSetup.Copy();
copy.processorArchitecture = processorArchitecture;
copy.runtimeVersion = runtimeVersion;
copy.elevated = elevated;
copy.configurationFileLocation = configurationFileLocation;
copy.properties.AddAll(properties);
if (configuration != null)
copy.configuration = configuration.Copy();
return copy;
}
/// <summary>
/// Makes all paths in this instance absolute.
/// </summary>
/// <param name="baseDirectory">The base directory for resolving relative paths,
/// or null to use the current directory.</param>
public void Canonicalize(string baseDirectory)
{
applicationBaseDirectory = GetCanonicalApplicationBaseDirectory(baseDirectory);
workingDirectory = FileUtils.CanonicalizePath(baseDirectory, workingDirectory);
for (int i = 0; i < hintDirectories.Count; i++)
hintDirectories[i] = FileUtils.CanonicalizePath(baseDirectory, hintDirectories[i]);
}
/// <summary>
/// Writes a temporary configuration file for the application to disk and returns its path
/// based on <see cref="ConfigurationFileLocation" />.
/// </summary>
/// <remarks>
/// <para>
/// The file is created with a unique name each time.
/// </para>
/// <para>
/// The file should be deleted by the caller when no longer required.
/// </para>
/// </remarks>
/// <returns>The full path of the configuration file that was written, or null if no file was written.</returns>
/// <exception cref="InvalidOperationException">Thrown if <see cref="ApplicationBaseDirectory"/>
/// is <c>null</c> but <see cref="ConfigurationFileLocation" /> is <see cref="Hosting.ConfigurationFileLocation.AppBase" />.</exception>
/// <exception cref="IOException">Thrown if the configuration file could not be written.</exception>
public string WriteTemporaryConfigurationFile()
{
string path = GetTemporaryConfigurationFilePath();
if (path != null)
Configuration.WriteToFile(path);
return path;
}
private string GetTemporaryConfigurationFilePath()
{
switch (ConfigurationFileLocation)
{
case ConfigurationFileLocation.None:
return null;
case ConfigurationFileLocation.Temp:
return SpecialPathPolicy.For("Hosting").CreateTempFileWithUniqueName().FullName;
case ConfigurationFileLocation.AppBase:
if (applicationBaseDirectory == null)
throw new InvalidOperationException("The configuration file was to be written to the application base directory but none was specified in the host setup.");
for (; ; )
{
string path = Path.Combine(GetCanonicalApplicationBaseDirectory(null), Hash64.CreateUniqueHash() + ".tmp.config");
if (!File.Exists(path))
return path;
}
default:
throw new ArgumentOutOfRangeException();
}
}
private string GetCanonicalApplicationBaseDirectory(string baseDirectory)
{
return FileUtils.CanonicalizePath(baseDirectory, applicationBaseDirectory);
}
}
}
| |
using System;
using System.Collections.Generic;
using Lucene.Net.Documents;
using Lucene.Net.Support;
using NUnit.Framework;
using System.IO;
namespace Lucene.Net.Index
{
using BaseDirectory = Lucene.Net.Store.BaseDirectory;
using BufferedIndexInput = Lucene.Net.Store.BufferedIndexInput;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using DocumentStoredFieldVisitor = DocumentStoredFieldVisitor;
using Field = Field;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestFieldsReader : LuceneTestCase
{
private static Directory Dir;
private static Document TestDoc;
private static FieldInfos.Builder FieldInfos = null;
/// <summary>
/// LUCENENET specific
/// Is non-static because NewIndexWriterConfig is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
TestDoc = new Document();
FieldInfos = new FieldInfos.Builder();
DocHelper.SetupDoc(TestDoc);
foreach (IIndexableField field in TestDoc)
{
FieldInfos.AddOrUpdate(field.Name, field.IndexableFieldType);
}
Dir = NewDirectory();
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy());
conf.MergePolicy.NoCFSRatio = 0.0;
IndexWriter writer = new IndexWriter(Dir, conf);
writer.AddDocument(TestDoc);
writer.Dispose();
FaultyIndexInput.DoFail = false;
}
[OneTimeTearDown]
public override void AfterClass()
{
Dir.Dispose();
Dir = null;
FieldInfos = null;
TestDoc = null;
base.AfterClass();
}
[Test]
public virtual void Test()
{
Assert.IsTrue(Dir != null);
Assert.IsTrue(FieldInfos != null);
IndexReader reader = DirectoryReader.Open(Dir);
Document doc = reader.Document(0);
Assert.IsTrue(doc != null);
Assert.IsTrue(doc.GetField(DocHelper.TEXT_FIELD_1_KEY) != null);
Field field = (Field)doc.GetField(DocHelper.TEXT_FIELD_2_KEY);
Assert.IsTrue(field != null);
Assert.IsTrue(field.IndexableFieldType.StoreTermVectors);
Assert.IsFalse(field.IndexableFieldType.OmitNorms);
Assert.IsTrue(field.IndexableFieldType.IndexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
field = (Field)doc.GetField(DocHelper.TEXT_FIELD_3_KEY);
Assert.IsTrue(field != null);
Assert.IsFalse(field.IndexableFieldType.StoreTermVectors);
Assert.IsTrue(field.IndexableFieldType.OmitNorms);
Assert.IsTrue(field.IndexableFieldType.IndexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
field = (Field)doc.GetField(DocHelper.NO_TF_KEY);
Assert.IsTrue(field != null);
Assert.IsFalse(field.IndexableFieldType.StoreTermVectors);
Assert.IsFalse(field.IndexableFieldType.OmitNorms);
Assert.IsTrue(field.IndexableFieldType.IndexOptions == IndexOptions.DOCS_ONLY);
DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor(DocHelper.TEXT_FIELD_3_KEY);
reader.Document(0, visitor);
IList<IIndexableField> fields = visitor.Document.Fields;
Assert.AreEqual(1, fields.Count);
Assert.AreEqual(DocHelper.TEXT_FIELD_3_KEY, fields[0].Name);
reader.Dispose();
}
public class FaultyFSDirectory : BaseDirectory
{
internal Directory FsDir;
public FaultyFSDirectory(DirectoryInfo dir)
{
FsDir = NewFSDirectory(dir);
m_lockFactory = FsDir.LockFactory;
}
public override IndexInput OpenInput(string name, IOContext context)
{
return new FaultyIndexInput(FsDir.OpenInput(name, context));
}
public override string[] ListAll()
{
return FsDir.ListAll();
}
[Obsolete("this method will be removed in 5.0")]
public override bool FileExists(string name)
{
return FsDir.FileExists(name);
}
public override void DeleteFile(string name)
{
FsDir.DeleteFile(name);
}
public override long FileLength(string name)
{
return FsDir.FileLength(name);
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
return FsDir.CreateOutput(name, context);
}
public override void Sync(ICollection<string> names)
{
FsDir.Sync(names);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
FsDir.Dispose();
}
}
}
private class FaultyIndexInput : BufferedIndexInput
{
internal IndexInput @delegate;
internal static bool DoFail;
internal int Count;
internal FaultyIndexInput(IndexInput @delegate)
: base("FaultyIndexInput(" + @delegate + ")", BufferedIndexInput.BUFFER_SIZE)
{
this.@delegate = @delegate;
}
internal virtual void SimOutage()
{
if (DoFail && Count++ % 2 == 1)
{
throw new IOException("Simulated network outage");
}
}
protected override void ReadInternal(byte[] b, int offset, int length)
{
SimOutage();
@delegate.Seek(GetFilePointer());
@delegate.ReadBytes(b, offset, length);
}
protected override void SeekInternal(long pos)
{
}
public override long Length
{
get { return @delegate.Length; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
@delegate.Dispose();
}
}
public override object Clone()
{
FaultyIndexInput i = new FaultyIndexInput((IndexInput)@delegate.Clone());
// seek the clone to our current position
try
{
i.Seek(GetFilePointer());
}
#pragma warning disable 168
catch (IOException e)
#pragma warning restore 168
{
throw new Exception();
}
return i;
}
}
// LUCENE-1262
[Test]
public virtual void TestExceptions()
{
DirectoryInfo indexDir = CreateTempDir("testfieldswriterexceptions");
try
{
Directory dir = new FaultyFSDirectory(indexDir);
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE);
IndexWriter writer = new IndexWriter(dir, iwc);
for (int i = 0; i < 2; i++)
{
writer.AddDocument(TestDoc);
}
writer.ForceMerge(1);
writer.Dispose();
IndexReader reader = DirectoryReader.Open(dir);
FaultyIndexInput.DoFail = true;
bool exc = false;
for (int i = 0; i < 2; i++)
{
try
{
reader.Document(i);
}
#pragma warning disable 168
catch (IOException ioe)
#pragma warning restore 168
{
// expected
exc = true;
}
try
{
reader.Document(i);
}
#pragma warning disable 168
catch (IOException ioe)
#pragma warning restore 168
{
// expected
exc = true;
}
}
Assert.IsTrue(exc);
reader.Dispose();
dir.Dispose();
}
finally
{
System.IO.Directory.Delete(indexDir.FullName, true);
}
}
}
}
| |
using YAF.Lucene.Net.Documents;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace YAF.Lucene.Net.Search
{
/*
* 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 AttributeSource = YAF.Lucene.Net.Util.AttributeSource;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using FilteredTermsEnum = YAF.Lucene.Net.Index.FilteredTermsEnum;
using NumericUtils = YAF.Lucene.Net.Util.NumericUtils;
using Terms = YAF.Lucene.Net.Index.Terms;
using TermsEnum = YAF.Lucene.Net.Index.TermsEnum;
using ToStringUtils = YAF.Lucene.Net.Util.ToStringUtils;
/// <summary>
/// <para>A <see cref="Query"/> that matches numeric values within a
/// specified range. To use this, you must first index the
/// numeric values using <see cref="Int32Field"/>,
/// <see cref="SingleField"/>, <see cref="Int64Field"/> or <see cref="DoubleField"/> (expert:
/// <see cref="Analysis.NumericTokenStream"/>). If your terms are instead textual,
/// you should use <see cref="TermRangeQuery"/>.
/// <see cref="NumericRangeFilter"/> is the filter equivalent of this
/// query.</para>
///
/// <para>You create a new <see cref="NumericRangeQuery{T}"/> with the static
/// factory methods, eg:
///
/// <code>
/// Query q = NumericRangeQuery.NewFloatRange("weight", 0.03f, 0.10f, true, true);
/// </code>
///
/// matches all documents whose <see cref="float"/> valued "weight" field
/// ranges from 0.03 to 0.10, inclusive.</para>
///
/// <para>The performance of <see cref="NumericRangeQuery{T}"/> is much better
/// than the corresponding <see cref="TermRangeQuery"/> because the
/// number of terms that must be searched is usually far
/// fewer, thanks to trie indexing, described below.</para>
///
/// <para>You can optionally specify a <a
/// href="#precisionStepDesc"><see cref="precisionStep"/></a>
/// when creating this query. This is necessary if you've
/// changed this configuration from its default (4) during
/// indexing. Lower values consume more disk space but speed
/// up searching. Suitable values are between <b>1</b> and
/// <b>8</b>. A good starting point to test is <b>4</b>,
/// which is the default value for all <c>Numeric*</c>
/// classes. See <a href="#precisionStepDesc">below</a> for
/// details.</para>
///
/// <para>This query defaults to
/// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/>.
/// With precision steps of <=4, this query can be run with
/// one of the <see cref="BooleanQuery"/> rewrite methods without changing
/// <see cref="BooleanQuery"/>'s default max clause count.</para>
///
/// <para/><h3>How it works</h3>
///
/// <para>See the publication about <a target="_blank" href="http://www.panfmp.org">panFMP</a>,
/// where this algorithm was described (referred to as <c>TrieRangeQuery</c>):
/// </para>
/// <blockquote><strong>Schindler, U, Diepenbroek, M</strong>, 2008.
/// <em>Generic XML-based Framework for Metadata Portals.</em>
/// Computers & Geosciences 34 (12), 1947-1955.
/// <a href="http://dx.doi.org/10.1016/j.cageo.2008.02.023"
/// target="_blank">doi:10.1016/j.cageo.2008.02.023</a></blockquote>
///
/// <para><em>A quote from this paper:</em> Because Apache Lucene is a full-text
/// search engine and not a conventional database, it cannot handle numerical ranges
/// (e.g., field value is inside user defined bounds, even dates are numerical values).
/// We have developed an extension to Apache Lucene that stores
/// the numerical values in a special string-encoded format with variable precision
/// (all numerical values like <see cref="double"/>s, <see cref="long"/>s, <see cref="float"/>s, and <see cref="int"/>s are converted to
/// lexicographic sortable string representations and stored with different precisions
/// (for a more detailed description of how the values are stored,
/// see <see cref="NumericUtils"/>). A range is then divided recursively into multiple intervals for searching:
/// The center of the range is searched only with the lowest possible precision in the <em>trie</em>,
/// while the boundaries are matched more exactly. This reduces the number of terms dramatically.</para>
///
/// <para>For the variant that stores long values in 8 different precisions (each reduced by 8 bits) that
/// uses a lowest precision of 1 byte, the index contains only a maximum of 256 distinct values in the
/// lowest precision. Overall, a range could consist of a theoretical maximum of
/// <code>7*255*2 + 255 = 3825</code> distinct terms (when there is a term for every distinct value of an
/// 8-byte-number in the index and the range covers almost all of them; a maximum of 255 distinct values is used
/// because it would always be possible to reduce the full 256 values to one term with degraded precision).
/// In practice, we have seen up to 300 terms in most cases (index with 500,000 metadata records
/// and a uniform value distribution).</para>
///
/// <a name="precisionStepDesc"><h3>Precision Step</h3></a>
/// <para/>You can choose any <see cref="precisionStep"/> when encoding values.
/// Lower step values mean more precisions and so more terms in index (and index gets larger). The number
/// of indexed terms per value is (those are generated by <see cref="Analysis.NumericTokenStream"/>):
/// <para>
///   indexedTermsPerValue = <b>ceil</b><big>(</big>bitsPerValue / precisionStep<big>)</big>
/// </para>
/// As the lower precision terms are shared by many values, the additional terms only
/// slightly grow the term dictionary (approx. 7% for <c>precisionStep=4</c>), but have a larger
/// impact on the postings (the postings file will have more entries, as every document is linked to
/// <c>indexedTermsPerValue</c> terms instead of one). The formula to estimate the growth
/// of the term dictionary in comparison to one term per value:
/// <para>
/// <!-- the formula in the alt attribute was transformed from latex to PNG with http://1.618034.com/latex.php (with 110 dpi): -->
///   <img src="doc-files/nrq-formula-1.png" alt="\mathrm{termDictOverhead} = \sum\limits_{i=0}^{\mathrm{indexedTermsPerValue}-1} \frac{1}{2^{\mathrm{precisionStep}\cdot i}}" />
/// </para>
/// <para>On the other hand, if the <see cref="precisionStep"/> is smaller, the maximum number of terms to match reduces,
/// which optimizes query speed. The formula to calculate the maximum number of terms that will be visited while
/// executing the query is:
/// </para>
/// <para>
/// <!-- the formula in the alt attribute was transformed from latex to PNG with http://1.618034.com/latex.php (with 110 dpi): -->
///   <img src="doc-files/nrq-formula-2.png" alt="\mathrm{maxQueryTerms} = \left[ \left( \mathrm{indexedTermsPerValue} - 1 \right) \cdot \left(2^\mathrm{precisionStep} - 1 \right) \cdot 2 \right] + \left( 2^\mathrm{precisionStep} - 1 \right)" />
/// </para>
/// <para>For longs stored using a precision step of 4, <c>maxQueryTerms = 15*15*2 + 15 = 465</c>, and for a precision
/// step of 2, <c>maxQueryTerms = 31*3*2 + 3 = 189</c>. But the faster search speed is reduced by more seeking
/// in the term enum of the index. Because of this, the ideal <see cref="precisionStep"/> value can only
/// be found out by testing. <b>Important:</b> You can index with a lower precision step value and test search speed
/// using a multiple of the original step value.</para>
///
/// <para>Good values for <see cref="precisionStep"/> are depending on usage and data type:</para>
/// <list type="bullet">
/// <item><description>The default for all data types is <b>4</b>, which is used, when no <code>precisionStep</code> is given.</description></item>
/// <item><description>Ideal value in most cases for <em>64 bit</em> data types <em>(long, double)</em> is <b>6</b> or <b>8</b>.</description></item>
/// <item><description>Ideal value in most cases for <em>32 bit</em> data types <em>(int, float)</em> is <b>4</b>.</description></item>
/// <item><description>For low cardinality fields larger precision steps are good. If the cardinality is < 100, it is
/// fair to use <see cref="int.MaxValue"/> (see below).</description></item>
/// <item><description>Steps <b>>=64</b> for <em>long/double</em> and <b>>=32</b> for <em>int/float</em> produces one token
/// per value in the index and querying is as slow as a conventional <see cref="TermRangeQuery"/>. But it can be used
/// to produce fields, that are solely used for sorting (in this case simply use <see cref="int.MaxValue"/> as
/// <see cref="precisionStep"/>). Using <see cref="Int32Field"/>,
/// <see cref="Int64Field"/>, <see cref="SingleField"/> or <see cref="DoubleField"/> for sorting
/// is ideal, because building the field cache is much faster than with text-only numbers.
/// These fields have one term per value and therefore also work with term enumeration for building distinct lists
/// (e.g. facets / preselected values to search for).
/// Sorting is also possible with range query optimized fields using one of the above <see cref="precisionStep"/>s.</description></item>
/// </list>
///
/// <para>Comparisons of the different types of RangeQueries on an index with about 500,000 docs showed
/// that <see cref="TermRangeQuery"/> in boolean rewrite mode (with raised <see cref="BooleanQuery"/> clause count)
/// took about 30-40 secs to complete, <see cref="TermRangeQuery"/> in constant score filter rewrite mode took 5 secs
/// and executing this class took <100ms to complete (on an Opteron64 machine, Java 1.5, 8 bit
/// precision step). This query type was developed for a geographic portal, where the performance for
/// e.g. bounding boxes or exact date/time stamps is important.</para>
///
/// @since 2.9
/// </summary>
public sealed class NumericRangeQuery<T> : MultiTermQuery
where T : struct, IComparable<T> // best equiv constraint for java's number class
{
internal NumericRangeQuery(string field, int precisionStep, NumericType dataType, T? min, T? max, bool minInclusive, bool maxInclusive)
: base(field)
{
if (precisionStep < 1)
{
throw new System.ArgumentException("precisionStep must be >=1");
}
this.precisionStep = precisionStep;
this.dataType = dataType;
this.min = min;
this.max = max;
this.minInclusive = minInclusive;
this.maxInclusive = maxInclusive;
}
// LUCENENET NOTE: Static methods were moved into the NumericRangeQuery class
protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
{
// very strange: java.lang.Number itself is not Comparable, but all subclasses used here are
if (min.HasValue && max.HasValue && (min.Value).CompareTo(max.Value) > 0)
{
return TermsEnum.EMPTY;
}
return new NumericRangeTermsEnum(this, terms.GetIterator(null));
}
/// <summary>
/// Returns <c>true</c> if the lower endpoint is inclusive </summary>
public bool IncludesMin
{
get { return minInclusive; }
}
/// <summary>
/// Returns <c>true</c> if the upper endpoint is inclusive </summary>
public bool IncludesMax
{
get { return maxInclusive; }
}
/// <summary>
/// Returns the lower value of this range query </summary>
public T? Min
{
get
{
return min;
}
}
/// <summary>
/// Returns the upper value of this range query </summary>
public T? Max
{
get
{
return max;
}
}
/// <summary>
/// Returns the precision step. </summary>
public int PrecisionStep
{
get
{
return precisionStep;
}
}
public override string ToString(string field)
{
StringBuilder sb = new StringBuilder();
if (!Field.Equals(field, StringComparison.Ordinal))
{
sb.Append(Field).Append(':');
}
return sb.Append(minInclusive ? '[' : '{').Append((min == null) ? "*" : min.ToString()).Append(" TO ").Append((max == null) ? "*" : max.ToString()).Append(maxInclusive ? ']' : '}').Append(ToStringUtils.Boost(Boost)).ToString();
}
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (!base.Equals(o))
{
return false;
}
if (o is NumericRangeQuery<T>)
{
var q = (NumericRangeQuery<T>)o;
return ((q.min == null ? min == null : q.min.Equals(min)) && (q.max == null ? max == null : q.max.Equals(max)) && minInclusive == q.minInclusive && maxInclusive == q.maxInclusive && precisionStep == q.precisionStep);
}
return false;
}
public override int GetHashCode()
{
int hash = base.GetHashCode();
hash += precisionStep ^ 0x64365465;
if (min != null)
{
hash += min.GetHashCode() ^ 0x14fa55fb;
}
if (max != null)
{
hash += max.GetHashCode() ^ 0x733fa5fe;
}
return hash + (Convert.ToBoolean(minInclusive).GetHashCode() ^ 0x14fa55fb) + (Convert.ToBoolean(maxInclusive).GetHashCode() ^ 0x733fa5fe);
}
// members (package private, to be also fast accessible by NumericRangeTermEnum)
internal readonly int precisionStep;
internal readonly NumericType dataType;
internal readonly T? min, max;
internal readonly bool minInclusive, maxInclusive;
// used to handle float/double infinity correcty
/// <summary>
/// NOTE: This was LONG_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly long INT64_NEGATIVE_INFINITY = NumericUtils.DoubleToSortableInt64(double.NegativeInfinity);
/// <summary>
/// NOTE: This was LONG_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly long INT64_POSITIVE_INFINITY = NumericUtils.DoubleToSortableInt64(double.PositiveInfinity);
/// <summary>
/// NOTE: This was INT_NEGATIVE_INFINITY in Lucene
/// </summary>
internal static readonly int INT32_NEGATIVE_INFINITY = NumericUtils.SingleToSortableInt32(float.NegativeInfinity);
/// <summary>
/// NOTE: This was INT_POSITIVE_INFINITY in Lucene
/// </summary>
internal static readonly int INT32_POSITIVE_INFINITY = NumericUtils.SingleToSortableInt32(float.PositiveInfinity);
/// <summary>
/// Subclass of <see cref="FilteredTermsEnum"/> for enumerating all terms that match the
/// sub-ranges for trie range queries, using flex API.
/// <para/>
/// WARNING: this term enumeration is not guaranteed to be always ordered by
/// <see cref="Index.Term.CompareTo(Index.Term)"/>.
/// The ordering depends on how <see cref="NumericUtils.SplitInt64Range(NumericUtils.Int64RangeBuilder, int, long, long)"/> and
/// <see cref="NumericUtils.SplitInt32Range(NumericUtils.Int32RangeBuilder, int, int, int)"/> generates the sub-ranges. For
/// <see cref="MultiTermQuery"/> ordering is not relevant.
/// </summary>
private sealed class NumericRangeTermsEnum : FilteredTermsEnum
{
private readonly NumericRangeQuery<T> outerInstance;
internal BytesRef currentLowerBound, currentUpperBound;
internal readonly LinkedList<BytesRef> rangeBounds = new LinkedList<BytesRef>();
internal readonly IComparer<BytesRef> termComp;
internal NumericRangeTermsEnum(NumericRangeQuery<T> outerInstance, TermsEnum tenum)
: base(tenum)
{
this.outerInstance = outerInstance;
switch (this.outerInstance.dataType)
{
case NumericType.INT64:
case NumericType.DOUBLE:
{
// lower
long minBound;
if (this.outerInstance.dataType == NumericType.INT64)
{
minBound = (this.outerInstance.min == null) ? long.MinValue : Convert.ToInt64(this.outerInstance.min.Value, CultureInfo.InvariantCulture);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.DOUBLE);
minBound = (this.outerInstance.min == null) ? INT64_NEGATIVE_INFINITY : NumericUtils.DoubleToSortableInt64(Convert.ToDouble(this.outerInstance.min.Value, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.minInclusive && this.outerInstance.min != null)
{
if (minBound == long.MaxValue)
{
break;
}
minBound++;
}
// upper
long maxBound;
if (this.outerInstance.dataType == NumericType.INT64)
{
maxBound = (this.outerInstance.max == null) ? long.MaxValue : Convert.ToInt64(this.outerInstance.max, CultureInfo.InvariantCulture);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.DOUBLE);
maxBound = (this.outerInstance.max == null) ? INT64_POSITIVE_INFINITY : NumericUtils.DoubleToSortableInt64(Convert.ToDouble(this.outerInstance.max, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.maxInclusive && this.outerInstance.max != null)
{
if (maxBound == long.MinValue)
{
break;
}
maxBound--;
}
NumericUtils.SplitInt64Range(new Int64RangeBuilderAnonymousInnerClassHelper(this), this.outerInstance.precisionStep, minBound, maxBound);
break;
}
case NumericType.INT32:
case NumericType.SINGLE:
{
// lower
int minBound;
if (this.outerInstance.dataType == NumericType.INT32)
{
minBound = (this.outerInstance.min == null) ? int.MinValue : Convert.ToInt32(this.outerInstance.min, CultureInfo.InvariantCulture);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.SINGLE);
minBound = (this.outerInstance.min == null) ? INT32_NEGATIVE_INFINITY : NumericUtils.SingleToSortableInt32(Convert.ToSingle(this.outerInstance.min, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.minInclusive && this.outerInstance.min != null)
{
if (minBound == int.MaxValue)
{
break;
}
minBound++;
}
// upper
int maxBound;
if (this.outerInstance.dataType == NumericType.INT32)
{
maxBound = (this.outerInstance.max == null) ? int.MaxValue : Convert.ToInt32(this.outerInstance.max, CultureInfo.InvariantCulture);
}
else
{
Debug.Assert(this.outerInstance.dataType == NumericType.SINGLE);
maxBound = (this.outerInstance.max == null) ? INT32_POSITIVE_INFINITY : NumericUtils.SingleToSortableInt32(Convert.ToSingle(this.outerInstance.max, CultureInfo.InvariantCulture));
}
if (!this.outerInstance.maxInclusive && this.outerInstance.max != null)
{
if (maxBound == int.MinValue)
{
break;
}
maxBound--;
}
NumericUtils.SplitInt32Range(new Int32RangeBuilderAnonymousInnerClassHelper(this), this.outerInstance.precisionStep, minBound, maxBound);
break;
}
default:
// should never happen
throw new System.ArgumentException("Invalid NumericType");
}
termComp = Comparer;
}
private class Int64RangeBuilderAnonymousInnerClassHelper : NumericUtils.Int64RangeBuilder
{
private readonly NumericRangeTermsEnum outerInstance;
public Int64RangeBuilderAnonymousInnerClassHelper(NumericRangeTermsEnum outerInstance)
{
this.outerInstance = outerInstance;
}
public override sealed void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
outerInstance.rangeBounds.AddLast(minPrefixCoded);
outerInstance.rangeBounds.AddLast(maxPrefixCoded);
}
}
private class Int32RangeBuilderAnonymousInnerClassHelper : NumericUtils.Int32RangeBuilder
{
private readonly NumericRangeTermsEnum outerInstance;
public Int32RangeBuilderAnonymousInnerClassHelper(NumericRangeTermsEnum outerInstance)
{
this.outerInstance = outerInstance;
}
public override sealed void AddRange(BytesRef minPrefixCoded, BytesRef maxPrefixCoded)
{
outerInstance.rangeBounds.AddLast(minPrefixCoded);
outerInstance.rangeBounds.AddLast(maxPrefixCoded);
}
}
private void NextRange()
{
Debug.Assert(rangeBounds.Count % 2 == 0);
currentLowerBound = rangeBounds.First.Value;
rangeBounds.Remove(currentLowerBound);
Debug.Assert(currentUpperBound == null || termComp.Compare(currentUpperBound, currentLowerBound) <= 0, "The current upper bound must be <= the new lower bound");
currentUpperBound = rangeBounds.First.Value;
rangeBounds.Remove(currentUpperBound);
}
protected override sealed BytesRef NextSeekTerm(BytesRef term)
{
while (rangeBounds.Count >= 2)
{
NextRange();
// if the new upper bound is before the term parameter, the sub-range is never a hit
if (term != null && termComp.Compare(term, currentUpperBound) > 0)
{
continue;
}
// never seek backwards, so use current term if lower bound is smaller
return (term != null && termComp.Compare(term, currentLowerBound) > 0) ? term : currentLowerBound;
}
// no more sub-range enums available
Debug.Assert(rangeBounds.Count == 0);
currentLowerBound = currentUpperBound = null;
return null;
}
protected override sealed AcceptStatus Accept(BytesRef term)
{
while (currentUpperBound == null || termComp.Compare(term, currentUpperBound) > 0)
{
if (rangeBounds.Count == 0)
{
return AcceptStatus.END;
}
// peek next sub-range, only seek if the current term is smaller than next lower bound
if (termComp.Compare(term, rangeBounds.First.Value) < 0)
{
return AcceptStatus.NO_AND_SEEK;
}
// step forward to next range without seeking, as next lower range bound is less or equal current term
NextRange();
}
return AcceptStatus.YES;
}
}
}
/// <summary>
/// LUCENENET specific class to provide access to static factory metods of <see cref="NumericRangeQuery{T}"/>
/// without referring to its genereic closing type.
/// </summary>
public static class NumericRangeQuery
{
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="long"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newLongRange() in Lucene
/// </summary>
public static NumericRangeQuery<long> NewInt64Range(string field, int precisionStep, long? min, long? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<long>(field, precisionStep, NumericType.INT64, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="long"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newLongRange() in Lucene
/// </summary>
public static NumericRangeQuery<long> NewInt64Range(string field, long? min, long? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<long>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT64, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="int"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newIntRange() in Lucene
/// </summary>
public static NumericRangeQuery<int> NewInt32Range(string field, int precisionStep, int? min, int? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<int>(field, precisionStep, NumericType.INT32, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="int"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newIntRange() in Lucene
/// </summary>
public static NumericRangeQuery<int> NewInt32Range(string field, int? min, int? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<int>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.INT32, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="double"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="double.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Double.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// </summary>
public static NumericRangeQuery<double> NewDoubleRange(string field, int precisionStep, double? min, double? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<double>(field, precisionStep, NumericType.DOUBLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="double"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="double.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Double.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// </summary>
public static NumericRangeQuery<double> NewDoubleRange(string field, double? min, double? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<double>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.DOUBLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="float"/>
/// range using the given <a href="#precisionStepDesc"><see cref="NumericRangeQuery{T}.precisionStep"/></a>.
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="float.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Single.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newFloatRange() in Lucene
/// </summary>
public static NumericRangeQuery<float> NewSingleRange(string field, int precisionStep, float? min, float? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<float>(field, precisionStep, NumericType.SINGLE, min, max, minInclusive, maxInclusive);
}
/// <summary>
/// Factory that creates a <see cref="NumericRangeQuery{T}"/>, that queries a <see cref="float"/>
/// range using the default <see cref="NumericRangeQuery{T}.precisionStep"/> <see cref="NumericUtils.PRECISION_STEP_DEFAULT"/> (4).
/// You can have half-open ranges (which are in fact </<= or >/>= queries)
/// by setting the min or max value to <c>null</c>.
/// <see cref="float.NaN"/> will never match a half-open range, to hit <c>NaN</c> use a query
/// with <c>min == max == System.Single.NaN</c>. By setting inclusive to <c>false</c>, it will
/// match all documents excluding the bounds, with inclusive on, the boundaries are hits, too.
/// <para/>
/// NOTE: This was newFloatRange() in Lucene
/// </summary>
public static NumericRangeQuery<float> NewSingleRange(string field, float? min, float? max, bool minInclusive, bool maxInclusive)
{
return new NumericRangeQuery<float>(field, NumericUtils.PRECISION_STEP_DEFAULT, NumericType.SINGLE, min, max, minInclusive, maxInclusive);
}
}
}
| |
// 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;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Xunit;
namespace System.Security.AccessControl.Tests
{
[Flags]
public enum FlagsForAce : byte
{
None = 0x00,
OI = 0x01,
CI = 0x02,
NP = 0x04,
IO = 0x08,
IH = 0x10,
SA = 0x40,
FA = 0x80,
InheritanceFlags = OI | CI | NP | IO,
AuditFlags = SA | FA,
}
public class Utils
{
public static bool IsAceEqual(GenericAce ace1, GenericAce ace2)
{
bool result = true;
byte[] ace1BinaryForm;
byte[] ace2BinaryForm;
if (null != ace1 && null != ace2)
{
//check the BinaryLength
if (ace1.BinaryLength != ace2.BinaryLength)
{
result = false;
}
else
{
ace1BinaryForm = new byte[ace1.BinaryLength];
ace2BinaryForm = new byte[ace2.BinaryLength];
ace1.GetBinaryForm(ace1BinaryForm, 0);
ace2.GetBinaryForm(ace2BinaryForm, 0);
if (!IsBinaryFormEqual(ace1BinaryForm, ace2BinaryForm))
{
result = false;
}
}
}
else if (null == ace1 && null == ace2)
{
Console.WriteLine("Both aces are null");
}
else
result = false;
return result;
}
public static bool IsBinaryFormEqual(byte[] binaryForm1, int offset, byte[] binaryForm2)
{
bool result = true;
if (null == binaryForm1 && null == binaryForm2)
result = true;
else if (null != binaryForm1 && null != binaryForm2)
{
if (binaryForm1.Length - offset != binaryForm2.Length)
{
result = false;
}
else
{
for (int i = 0; i < binaryForm2.Length; i++)
{
if (binaryForm1[offset + i] != binaryForm2[i])
{
result = false;
break;
}
}
}
}
else
result = false;
return result;
}
public static bool IsBinaryFormEqual(byte[] binaryForm1, byte[] binaryForm2)
{
return IsBinaryFormEqual(binaryForm1, 0, binaryForm2);
}
public static RawAcl CreateRawAclFromString(string rawAclString)
{
RawAcl rawAcl = null;
byte revision = 0;
int capacity = 1;
CommonAce cAce = null;
AceFlags aceFlags = AceFlags.None;
AceQualifier aceQualifier = AceQualifier.AccessAllowed;
int accessMask = 1;
SecurityIdentifier sid = null;
bool isCallback = false;
int opaqueSize = 0;
byte[] opaque = null;
string[] parts = null;
string[] subparts = null;
char[] delimiter1 = new char[] { '#' };
char[] delimiter2 = new char[] { ':' };
if (rawAclString != null)
{
rawAcl = new RawAcl(revision, capacity);
parts = rawAclString.Split(delimiter1);
for (int i = 0; i < parts.Length; i++)
{
subparts = parts[i].Split(delimiter2);
if (subparts.Length != 6)
{
return null;
}
aceFlags = (AceFlags)byte.Parse(subparts[0]);
aceQualifier = (AceQualifier)int.Parse(subparts[1]);
accessMask = int.Parse(subparts[2]);
sid = new SecurityIdentifier(TranslateStringConstFormatSidToStandardFormatSid(subparts[3]));
isCallback = bool.Parse(subparts[4]);
if (!isCallback)
opaque = null;
else
{
opaqueSize = int.Parse(subparts[5]);
opaque = new byte[opaqueSize];
}
cAce = new CommonAce(aceFlags, aceQualifier, accessMask, sid, isCallback, opaque);
rawAcl.InsertAce(rawAcl.Count, cAce);
}
}
return rawAcl;
}
public static string TranslateStringConstFormatSidToStandardFormatSid(string sidStringConst)
{
string stFormatSid = null;
if (sidStringConst == "BA")
stFormatSid = "S-1-5-32-544";
else if (sidStringConst == "BO")
stFormatSid = "S-1-5-32-551";
else if (sidStringConst == "BG")
stFormatSid = "S-1-5-32-546";
else if (sidStringConst == "AN")
stFormatSid = "S-1-5-7";
else if (sidStringConst == "NO")
stFormatSid = "S-1-5-32-556";
else if (sidStringConst == "SO")
stFormatSid = "S-1-5-32-549";
else if (sidStringConst == "RD")
stFormatSid = "S-1-5-32-555";
else if (sidStringConst == "SY")
stFormatSid = "S-1-5-18";
else
stFormatSid = sidStringConst;
return stFormatSid;
}
public static void PrintBinaryForm(byte[] binaryForm)
{
Console.WriteLine();
if (binaryForm != null)
{
Console.WriteLine("BinaryForm:");
for (int i = 0; i < binaryForm.Length; i++)
{
Console.WriteLine("{0}", binaryForm[i]);
}
Console.WriteLine();
}
else
Console.WriteLine("BinaryForm: null");
}
public static int ComputeBinaryLength(CommonSecurityDescriptor commonSecurityDescriptor, bool needCountDacl)
{
int verifierBinaryLength = 0;
if (commonSecurityDescriptor != null)
{
verifierBinaryLength = 20; //initialize the binary length to header length
if (commonSecurityDescriptor.Owner != null)
verifierBinaryLength += commonSecurityDescriptor.Owner.BinaryLength;
if (commonSecurityDescriptor.Group != null)
verifierBinaryLength += commonSecurityDescriptor.Group.BinaryLength;
if ((commonSecurityDescriptor.ControlFlags & ControlFlags.SystemAclPresent) != 0 && commonSecurityDescriptor.SystemAcl != null)
verifierBinaryLength += commonSecurityDescriptor.SystemAcl.BinaryLength;
if ((commonSecurityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0 && commonSecurityDescriptor.DiscretionaryAcl != null && needCountDacl)
verifierBinaryLength += commonSecurityDescriptor.DiscretionaryAcl.BinaryLength;
}
return verifierBinaryLength;
}
//verify the dacl is crafted with one Allow Everyone Everything ACE
public static bool VerifyDaclWithCraftedAce(bool isContainer, bool isDS, DiscretionaryAcl dacl)
{
byte[] craftedBForm;
byte[] binaryForm;
DiscretionaryAcl craftedDacl = new DiscretionaryAcl(isContainer, isDS, 1);
craftedDacl.AddAccess(AccessControlType.Allow,
new SecurityIdentifier("S-1-1-0"),
-1,
isContainer ? InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit : InheritanceFlags.None,
PropagationFlags.None);
craftedBForm = new byte[craftedDacl.BinaryLength];
binaryForm = new byte[dacl.BinaryLength];
Assert.False(craftedBForm == null || binaryForm == null);
craftedDacl.GetBinaryForm(craftedBForm, 0);
dacl.GetBinaryForm(binaryForm, 0);
return Utils.IsBinaryFormEqual(craftedBForm, binaryForm);
}
public static RawAcl CopyRawACL(RawAcl rawAcl)
{
byte[] binaryForm = new byte[rawAcl.BinaryLength];
rawAcl.GetBinaryForm(binaryForm, 0);
return new RawAcl(binaryForm, 0);
}
public static bool AclPartialEqual(GenericAcl acl1, GenericAcl acl2, int acl1StartAceIndex, int acl1EndAceIndex, int acl2StartAceIndex, int acl2EndAceIndex)
{
int index1 = 0;
int index2 = 0;
bool result = true;
if (null != acl1 && null != acl2)
{
if (acl1StartAceIndex < 0 || acl1EndAceIndex < 0 || acl1StartAceIndex > acl1.Count - 1 || acl1EndAceIndex > acl1.Count - 1 ||
acl2StartAceIndex < 0 || acl2EndAceIndex < 0 || acl2StartAceIndex > acl2.Count - 1 || acl2EndAceIndex > acl2.Count - 1)
{
//the caller has garenteeed the index calculation is correct so if any above condition hold,
//that means the range of the index is invalid
return true;
}
if (acl1EndAceIndex - acl1StartAceIndex != acl2EndAceIndex - acl2StartAceIndex)
{
result = false;
}
else
{
for (index1 = acl1StartAceIndex, index2 = acl2StartAceIndex; index1 <= acl1EndAceIndex; index1++, index2++)
{
if (!Utils.IsAceEqual(acl1[index1], acl2[index2]))
{
result = false;
break;
}
}
}
}
else if (null == acl1 && null == acl2)
{
}
else
result = false;
return result;
}
public static bool TestGetEnumerator(IEnumerator enumerator, RawAcl rAcl, bool isExplicit)
{
bool result = false;//assume failure
GenericAce gAce = null;
if (!(isExplicit ? enumerator.MoveNext() : ((AceEnumerator)enumerator).MoveNext()))
{//enumerator is created from empty RawAcl
if (0 != rAcl.Count)
return false;
else
return true;
}
else if (0 == rAcl.Count)
{//rawAcl is empty but enumerator is still enumerable
return false;
}
else//non-empty rAcl, non-empty enumerator
{
//check all aces enumerated are in the RawAcl
if (isExplicit)
{
enumerator.Reset();
}
else
{
((AceEnumerator)enumerator).Reset();
}
while (isExplicit ? enumerator.MoveNext() : ((AceEnumerator)enumerator).MoveNext())
{
gAce = (GenericAce)(isExplicit ? enumerator.Current : ((AceEnumerator)enumerator).Current);
//check this gAce exists in the RawAcl
for (int i = 0; i < rAcl.Count; i++)
{
if (GenericAce.ReferenceEquals(gAce, rAcl[i]))
{//found
result = true;
break;
}
}
if (!result)
{//not exists in the RawAcl, failed
return false;
}
//enumerate to next one
}
//check all aces of rAcl are enumerable by the enumerator
result = false; //assume failure
for (int i = 0; i < rAcl.Count; i++)
{
gAce = rAcl[i];
//check this gAce is enumerable
if (isExplicit)
{
enumerator.Reset();
}
else
{
((AceEnumerator)enumerator).Reset();
}
while (isExplicit ? enumerator.MoveNext() : ((AceEnumerator)enumerator).MoveNext())
{
if (GenericAce.ReferenceEquals((GenericAce)(isExplicit ? enumerator.Current : ((AceEnumerator)enumerator).Current), gAce))
{
result = true;
break;
}
}
if (!result)
{//not enumerable
return false;
}
//check next ace in the rAcl
}
//now all passed
return true;
}
}
public sealed class Win32AclLayer
{
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int VER_PLATFORM_WIN32_NT = 2;
[DllImport("Advapi32.dll", EntryPoint = "InitializeAcl", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int InitializeAclNative(
byte[] acl,
uint aclLength,
uint aclRevision);
[DllImport("Advapi32.dll", EntryPoint = "AddAccessAllowedAceEx", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int AddAccessAllowedAceExNative(
byte[] acl,
uint aclRevision,
uint aceFlags,
uint accessMask,
byte[] sid);
[DllImport("Advapi32.dll", EntryPoint = "AddAccessDeniedAceEx", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int AddAccessDeniedAceExNative(
byte[] acl,
uint aclRevision,
uint aceFlags,
uint accessMask,
byte[] sid);
[DllImport("Advapi32.dll", EntryPoint = "AddAuditAccessAceEx", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int AddAuditAccessAceExNative(
byte[] acl,
uint aclRevision,
uint aceFlags,
uint accessMask,
byte[] sid,
uint bAuditSccess,
uint bAuditFailure);
}
}
}
| |
using J2N.Threading;
using Lucene.Net.Support;
using System;
using System.IO;
using System.Threading;
namespace Lucene.Net.Search
{
/*
* 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 TrackingIndexWriter = Lucene.Net.Index.TrackingIndexWriter;
/// <summary>
/// Utility class that runs a thread to manage periodic
/// reopens of a <see cref="ReferenceManager{T}"/>, with methods to wait for a specific
/// index changes to become visible. To use this class you
/// must first wrap your <see cref="Index.IndexWriter"/> with a
/// <see cref="TrackingIndexWriter"/> and always use it to make changes
/// to the index, saving the returned generation. Then,
/// when a given search request needs to see a specific
/// index change, call the <see cref="WaitForGeneration(long)"/> to wait for
/// that change to be visible. Note that this will only
/// scale well if most searches do not need to wait for a
/// specific index generation.
/// <para/>
/// @lucene.experimental
/// </summary>
public class ControlledRealTimeReopenThread<T> : ThreadJob, IDisposable
where T : class
{
private readonly ReferenceManager<T> manager;
private readonly long targetMaxStaleNS;
private readonly long targetMinStaleNS;
private readonly TrackingIndexWriter writer;
private volatile bool finish;
private long waitingGen;
private long searchingGen;
private long refreshStartGen;
private EventWaitHandle reopenCond = new AutoResetEvent(false);
private EventWaitHandle available = new AutoResetEvent(false);
/// <summary>
/// Create <see cref="ControlledRealTimeReopenThread{T}"/>, to periodically
/// reopen the a <see cref="ReferenceManager{T}"/>.
/// </summary>
/// <param name="targetMaxStaleSec"> Maximum time until a new
/// reader must be opened; this sets the upper bound
/// on how slowly reopens may occur, when no
/// caller is waiting for a specific generation to
/// become visible.
/// </param>
/// <param name="targetMinStaleSec"> Mininum time until a new
/// reader can be opened; this sets the lower bound
/// on how quickly reopens may occur, when a caller
/// is waiting for a specific generation to
/// become visible. </param>
public ControlledRealTimeReopenThread(TrackingIndexWriter writer, ReferenceManager<T> manager, double targetMaxStaleSec, double targetMinStaleSec)
{
if (targetMaxStaleSec < targetMinStaleSec)
{
throw new ArgumentException("targetMaxScaleSec (= " + targetMaxStaleSec.ToString("0.0") + ") < targetMinStaleSec (=" + targetMinStaleSec.ToString("0.0") + ")");
}
this.writer = writer;
this.manager = manager;
this.targetMaxStaleNS = (long)(1000000000 * targetMaxStaleSec);
this.targetMinStaleNS = (long)(1000000000 * targetMinStaleSec);
manager.AddListener(new HandleRefresh(this));
}
private class HandleRefresh : ReferenceManager.IRefreshListener
{
private readonly ControlledRealTimeReopenThread<T> outerInstance;
public HandleRefresh(ControlledRealTimeReopenThread<T> outerInstance)
{
this.outerInstance = outerInstance;
}
public virtual void BeforeRefresh()
{
}
public virtual void AfterRefresh(bool didRefresh)
{
outerInstance.RefreshDone();
}
}
private void RefreshDone()
{
lock (this)
{
// if we're finishing, , make it out so that all waiting search threads will return
searchingGen = finish ? long.MaxValue : refreshStartGen;
available.Set();
}
reopenCond.Reset();
}
public void Dispose()
{
finish = true;
reopenCond.Set();
//#if !NETSTANDARD1_6
// try
// {
//#endif
Join();
//#if !NETSTANDARD1_6 // LUCENENET NOTE: Senseless to catch and rethrow the same exception type
// }
// catch (ThreadInterruptedException ie)
// {
// throw new ThreadInterruptedException(ie.ToString(), ie);
// }
//#endif
// LUCENENET specific: dispose reset event
reopenCond.Dispose();
available.Dispose();
}
/// <summary>
/// Waits for the target generation to become visible in
/// the searcher.
/// If the current searcher is older than the
/// target generation, this method will block
/// until the searcher is reopened, by another via
/// <see cref="ReferenceManager{T}.MaybeRefresh()"/> or until the <see cref="ReferenceManager{T}"/> is closed.
/// </summary>
/// <param name="targetGen"> The generation to wait for </param>
public virtual void WaitForGeneration(long targetGen)
{
WaitForGeneration(targetGen, -1);
}
/// <summary>
/// Waits for the target generation to become visible in
/// the searcher, up to a maximum specified milli-seconds.
/// If the current searcher is older than the target
/// generation, this method will block until the
/// searcher has been reopened by another thread via
/// <see cref="ReferenceManager{T}.MaybeRefresh()"/>, the given waiting time has elapsed, or until
/// the <see cref="ReferenceManager{T}"/> is closed.
/// <para/>
/// NOTE: if the waiting time elapses before the requested target generation is
/// available the current <see cref="SearcherManager"/> is returned instead.
/// </summary>
/// <param name="targetGen">
/// The generation to wait for </param>
/// <param name="maxMS">
/// Maximum milliseconds to wait, or -1 to wait indefinitely </param>
/// <returns> <c>true</c> if the <paramref name="targetGen"/> is now available,
/// or false if <paramref name="maxMS"/> wait time was exceeded </returns>
public virtual bool WaitForGeneration(long targetGen, int maxMS)
{
long curGen = writer.Generation;
if (targetGen > curGen)
{
throw new ArgumentException("targetGen=" + targetGen + " was never returned by the ReferenceManager instance (current gen=" + curGen + ")");
}
lock (this)
if (targetGen <= searchingGen)
return true;
else
{
waitingGen = Math.Max(waitingGen, targetGen);
reopenCond.Set();
available.Reset();
}
long startMS = Time.NanoTime() / 1000000;
// LUCENENET specific - reading searchingGen not thread safe, so use Interlocked.Read()
while (targetGen > Interlocked.Read(ref searchingGen))
{
if (maxMS < 0)
{
available.WaitOne();
}
else
{
long msLeft = (startMS + maxMS) - (Time.NanoTime()) / 1000000;
if (msLeft <= 0)
{
return false;
}
else
{
available.WaitOne(TimeSpan.FromMilliseconds(msLeft));
}
}
}
return true;
}
public override void Run()
{
// TODO: maybe use private thread ticktock timer, in
// case clock shift messes up nanoTime?
long lastReopenStartNS = DateTime.UtcNow.Ticks * 100;
//System.out.println("reopen: start");
while (!finish)
{
bool hasWaiting;
lock (this)
hasWaiting = waitingGen > searchingGen;
long nextReopenStartNS = lastReopenStartNS + (hasWaiting ? targetMinStaleNS : targetMaxStaleNS);
long sleepNS = nextReopenStartNS - Time.NanoTime();
if (sleepNS > 0)
#if !NETSTANDARD1_6
try
{
#endif
reopenCond.WaitOne(TimeSpan.FromMilliseconds(sleepNS / Time.MILLISECONDS_PER_NANOSECOND));//Convert NS to Ticks
#if !NETSTANDARD1_6
}
#pragma warning disable 168
catch (ThreadInterruptedException ie)
#pragma warning restore 168
{
Thread.CurrentThread.Interrupt();
return;
}
#endif
if (finish)
{
break;
}
lastReopenStartNS = Time.NanoTime();
// Save the gen as of when we started the reopen; the
// listener (HandleRefresh above) copies this to
// searchingGen once the reopen completes:
refreshStartGen = writer.GetAndIncrementGeneration();
try
{
manager.MaybeRefreshBlocking();
}
catch (IOException ioe)
{
throw new Exception(ioe.ToString(), ioe);
}
}
// this will set the searchingGen so that all waiting threads will exit
RefreshDone();
}
}
}
| |
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 xStudio.Web.Areas.HelpPage.ModelDescriptions;
using xStudio.Web.Areas.HelpPage.Models;
namespace xStudio.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging
{
public class LocationInfoGetterTests
{
private async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null)
{
using (var workspace = TestWorkspace.CreateCSharp(markup, parseOptions))
{
var testDocument = workspace.Documents.Single();
var position = testDocument.CursorPosition.Value;
var locationInfo = await LocationInfoGetter.GetInfoAsync(
workspace.CurrentSolution.Projects.Single().Documents.Single(),
position,
CancellationToken.None);
Assert.Equal(expectedName, locationInfo.Name);
Assert.Equal(expectedLineOffset, locationInfo.LineOffset);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestClass()
{
await TestAsync("class F$$oo { }", "Foo", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")]
public async Task TestMethod()
{
await TestAsync(
@"class Class
{
public static void Meth$$od()
{
}
}
", "Class.Method()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestNamespace()
{
await TestAsync(
@"namespace Namespace
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestDottedNamespace()
{
await TestAsync(
@"namespace Namespace.Another
{
class Class
{
void Method()
{
}$$
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestNestedNamespace()
{
await TestAsync(
@"namespace Namespace
{
namespace Another
{
class Class
{
void Method()
{
}$$
}
}
}", "Namespace.Another.Class.Method()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestNestedType()
{
await TestAsync(
@"class Outer
{
class Inner
{
void Quux()
{$$
}
}
}", "Outer.Inner.Quux()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestPropertyGetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;$$
}
}
}", "Class.Property", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")]
public async Task TestPropertySetter()
{
await TestAsync(
@"class Class
{
string Property
{
get
{
return null;
}
set
{
string s = $$value;
}
}
}", "Class.Property", 9);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")]
public async Task TestField()
{
await TestAsync(
@"class Class
{
int fi$$eld;
}", "Class.field", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
public async Task TestLambdaInFieldInitializer()
{
await TestAsync(
@"class Class
{
Action<int> a = b => { in$$t c; };
}", "Class.a", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
public async Task TestMultipleFields()
{
await TestAsync(
@"class Class
{
int a1, a$$2;
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConstructor()
{
await TestAsync(
@"class C1
{
C1()
{
$$}
}
", "C1.C1()", 3);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestDestructor()
{
await TestAsync(
@"class C1
{
~C1()
{
$$}
}
", "C1.~C1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static int operator +(C1 x, C1 y)
{
$$return 42;
}
}
}
", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestConversionOperator()
{
await TestAsync(
@"namespace N1
{
class C1
{
public static explicit operator N1.C2(N1.C1 x)
{
$$return null;
}
}
class C2
{
}
}
", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestEvent()
{
await TestAsync(
@"class C1
{
delegate void D1();
event D1 e1$$;
}
", "C1.e1", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextExplicitInterfaceImplementation()
{
await TestAsync(
@"interface I1
{
void M1();
}
class C1
{
void I1.M1()
{
$$}
}
", "C1.M1()", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TextIndexer()
{
await TestAsync(
@"class C1
{
C1 this[int x]
{
get
{
$$return null;
}
}
}
", "C1.this[int x]", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestParamsParameter()
{
await TestAsync(
@"class C1
{
void M1(params int[] x) { $$ }
}
", "C1.M1(params int[] x)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestArglistParameter()
{
await TestAsync(
@"class C1
{
void M1(__arglist) { $$ }
}
", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestRefAndOutParameters()
{
await TestAsync(
@"class C1
{
void M1( ref int x, out int y )
{
$$y = x;
}
}
", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestOptionalParameters()
{
await TestAsync(
@"class C1
{
void M1(int x =1)
{
$$y = x;
}
}
", "C1.M1(int x =1)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestExtensionMethod()
{
await TestAsync(
@"static class C1
{
static void M1(this int x)
{
}$$
}
", "C1.M1(this int x)", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericType()
{
await TestAsync(
@"class C1<T, U>
{
static void M1() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericMethod()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>() { $$ }
}
", "C1.M1()", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestGenericParameters()
{
await TestAsync(
@"class C1<T, U>
{
static void M1<V>(C1<int, V> x, V y) { $$ }
}
", "C1.M1(C1<int, V> x, V y)", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespace()
{
await TestAsync(
@"{
class Class
{
int a1, a$$2;
}
}", "Class.a2", 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingNamespaceName()
{
await TestAsync(
@"namespace
{
class C1
{
int M1()
$${
}
}
}", "?.C1.M1()", 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingClassName()
{
await TestAsync(
@"namespace N1
class
{
int M1()
$${
}
}
}", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree...
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingMethodName()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void (ref int x)
{
$$}
}
}", "N1.C1", 4);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TestMissingParameterList()
{
await TestAsync(
@"namespace N1
{
class C1
{
static void M1
{
$$}
}
}", "N1.C1.M1", 2);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelField()
{
await TestAsync(
@"$$int f1;
", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelMethod()
{
await TestAsync(
@"int M1(int x)
{
$$}
", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)]
public async Task TopLevelStatement()
{
await TestAsync(
@"
$$System.Console.WriteLine(""Hello"")
", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script));
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
namespace System.Management.Automation
{
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections;
/// <summary>
/// PSListModifier is a simple helper class created by the update-list cmdlet.
/// The update-list cmdlet will either return an instance of this class, or
/// it will internally use an instance of this class to implement the updates.
///
/// Cmdlets can also take a PSListModifier as a parameter. Usage might look like:
///
/// Get-Mailbox | Set-Mailbox -Alias @{Add='jim'}
///
/// Alias would take a PSListModifier and the Cmdlet code would be responsible
/// for apply updates (possibly using PSListModifier.ApplyTo or else using custom logic).
/// </summary>
public class PSListModifier
{
/// <summary>
/// Create a new PSListModifier with empty lists for Add/Remove.
/// </summary>
public PSListModifier()
{
_itemsToAdd = new Collection<object>();
_itemsToRemove = new Collection<object>();
_replacementItems = new Collection<object>();
}
/// <summary>
/// Create a new PSListModifier with the specified add and remove lists.
/// </summary>
/// <param name="removeItems">The items to remove</param>
/// <param name="addItems">The items to add</param>
public PSListModifier(Collection<object> removeItems, Collection<object> addItems)
{
_itemsToAdd = addItems ?? new Collection<object>();
_itemsToRemove = removeItems ?? new Collection<object>();
_replacementItems = new Collection<object>();
}
/// <summary>
/// Create a new PSListModifier to replace a given list with replaceItems.
/// </summary>
/// <param name="replacementItems">The item(s) to replace an existing list with</param>
public PSListModifier(object replacementItems)
{
_itemsToAdd = new Collection<object>();
_itemsToRemove = new Collection<object>();
if (replacementItems == null)
{
_replacementItems = new Collection<object>();
}
else if (replacementItems is Collection<object>)
{
_replacementItems = (Collection<object>)replacementItems;
}
else if (replacementItems is IList<object>)
{
_replacementItems = new Collection<object>((IList<object>)replacementItems);
}
else if (replacementItems is IList)
{
_replacementItems = new Collection<object>();
foreach (object item in (IList)replacementItems)
{
_replacementItems.Add(item);
}
}
else
{
_replacementItems = new Collection<object>();
_replacementItems.Add(replacementItems);
}
}
/// <summary>
/// Create a new PSListModifier with the specified add and remove lists (in the hash.)
/// </summary>
/// <param name="hash">A hashtable, where the value for key Add is the list to add
/// and the value for Remove is the list to remove.</param>
public PSListModifier(Hashtable hash)
{
if (hash == null)
{
throw PSTraceSource.NewArgumentNullException("hash");
}
_itemsToAdd = new Collection<object>();
_itemsToRemove = new Collection<object>();
_replacementItems = new Collection<object>();
foreach (DictionaryEntry entry in hash)
{
if (entry.Key is string)
{
string key = entry.Key as string;
bool isAdd = key.Equals(AddKey, StringComparison.OrdinalIgnoreCase);
bool isRemove = key.Equals(RemoveKey, StringComparison.OrdinalIgnoreCase);
bool isReplace = key.Equals(ReplaceKey, StringComparison.OrdinalIgnoreCase);
if (!isAdd && !isRemove && !isReplace)
{
throw PSTraceSource.NewArgumentException("hash", PSListModifierStrings.ListModifierDisallowedKey, key);
}
Collection<object> collection;
if (isRemove)
{
collection = _itemsToRemove;
}
else if (isAdd)
{
collection = _itemsToAdd;
}
else
{
collection = _replacementItems;
}
IEnumerable enumerable = LanguagePrimitives.GetEnumerable(entry.Value);
if (enumerable != null)
{
foreach (object obj in enumerable)
{
collection.Add(obj);
}
}
else
{
collection.Add(entry.Value);
}
}
else
{
throw PSTraceSource.NewArgumentException("hash", PSListModifierStrings.ListModifierDisallowedKey, entry.Key);
}
}
}
/// <summary>
/// The list of items to add when ApplyTo is called.
/// </summary>
public Collection<object> Add
{
get { return _itemsToAdd; }
}
private Collection<object> _itemsToAdd;
/// <summary>
/// The list of items to remove when AppyTo is called.
/// </summary>
public Collection<object> Remove
{
get { return _itemsToRemove; }
}
private Collection<object> _itemsToRemove;
/// <summary>
/// The list of items to replace an existing list with.
/// </summary>
public Collection<object> Replace
{
get { return _replacementItems; }
}
private Collection<Object> _replacementItems;
/// <summary>
/// Update the given collection with the items in Add and Remove.
/// </summary>
/// <param name="collectionToUpdate">The collection to update</param>
public void ApplyTo(IList collectionToUpdate)
{
if (collectionToUpdate == null)
{
throw PSTraceSource.NewArgumentNullException("collectionToUpdate");
}
if (_replacementItems.Count > 0)
{
collectionToUpdate.Clear();
foreach (object obj in _replacementItems)
{
collectionToUpdate.Add(PSObject.Base(obj));
}
}
else
{
foreach (object obj in _itemsToRemove)
{
collectionToUpdate.Remove(PSObject.Base(obj));
}
foreach (object obj in _itemsToAdd)
{
collectionToUpdate.Add(PSObject.Base(obj));
}
}
}
/// <summary>
/// Update the given collection with the items in Add and Remove.
/// </summary>
/// <param name="collectionToUpdate">The collection to update</param>
public void ApplyTo(object collectionToUpdate)
{
if (collectionToUpdate == null)
{
throw new ArgumentNullException("collectionToUpdate");
}
collectionToUpdate = PSObject.Base(collectionToUpdate);
IList list = collectionToUpdate as IList;
if (list == null)
{
throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed);
}
ApplyTo(list);
}
internal Hashtable ToHashtable()
{
Hashtable result = new Hashtable(2);
if (_itemsToAdd.Count > 0)
{
result.Add(AddKey, _itemsToAdd);
}
if (_itemsToRemove.Count > 0)
{
result.Add(RemoveKey, _itemsToRemove);
}
if (_replacementItems.Count > 0)
{
result.Add(ReplaceKey, _replacementItems);
}
return result;
}
internal const string AddKey = "Add";
internal const string RemoveKey = "Remove";
internal const string ReplaceKey = "Replace";
}
/// <summary>
/// A generic version of PSListModifier that exists for the sole purpose of making
/// cmdlets that accept a PSListModifier more usable. Users that look at the syntax
/// of the command will see something like PSListModifier[Mailbox] and know they need
/// to pass in Mailboxes.
/// </summary>
/// <typeparam name="T">The list element type</typeparam>
public class PSListModifier<T> : PSListModifier
{
/// <summary>
/// Create a new PSListModifier with empty lists for Add/Remove.
/// </summary>
public PSListModifier()
: base()
{
}
/// <summary>
/// Create a new PSListModifier with the specified add and remove lists.
/// </summary>
/// <param name="removeItems">The items to remove</param>
/// <param name="addItems">The items to add</param>
public PSListModifier(Collection<object> removeItems, Collection<object> addItems)
: base(removeItems, addItems)
{
}
/// <summary>
/// Create a new PSListModifier to replace a given list with replaceItems.
/// </summary>
/// <param name="replacementItems">The items to replace an existing list with</param>
public PSListModifier(object replacementItems)
: base(replacementItems)
{
}
/// <summary>
/// Create a new PSListModifier with the specified add and remove lists (in the hash.)
/// </summary>
/// <param name="hash">A hashtable, where the value for key Add is the list to add
/// and the value for Remove is the list to remove.</param>
public PSListModifier(Hashtable hash)
: base(hash)
{
}
}
}
| |
using IntuiLab.Kinect.DataUserTracking.Events;
using Microsoft.Kinect.Toolkit.Interaction;
using System;
using System.Drawing;
namespace IntuiLab.Kinect.DataUserTracking
{
internal class HandData
{
#region Properties
#region HandType
/// <summary>
/// Indicates the hand type
/// </summary>
private InteractionHandType m_refHandType;
public InteractionHandType HandType
{
get
{
return m_refHandType;
}
set
{
if (m_refHandType != value)
{
m_refHandType = value;
}
}
}
#endregion
#region HandRawPosition
/// <summary>
/// Indicates the hand's raw position
/// Raw position correspond at the normalize coordinate ( [0,1] ) send to MGRE
/// </summary>
private PointF m_HandRawPosition;
public PointF HandRawPosition
{
get
{
return m_HandRawPosition;
}
set
{
m_HandRawPosition = value;
}
}
#endregion
#region HandScreenPosition
/// <summary>
/// Indicates the hand's screen position
/// Screen position correspond at the hand's coordinate to the screen in pixel.
/// </summary>
private PointF m_HandScreenPosition;
public PointF HandScreenPosition
{
get
{
return m_HandScreenPosition;
}
set
{
if (m_HandScreenPosition != value)
{
m_HandScreenPosition = value;
if (IsActive)
{
// Notify that the hand moved
RaiseHandMove(this, new HandMoveEventArgs
{
HandType = this.HandType,
PositionOnScreen = m_HandScreenPosition,
RawPosition = HandRawPosition,
IsGrip = this.IsGrip
});
}
}
}
}
#endregion
#region IsPrimaryHand
/// <summary>
/// Indicate if the hand is primary or not.
/// The first hand enter in the pointing area is the primary hand.
/// </summary>
private bool m_IsPrimaryHand;
public bool IsPrimaryHand
{
get
{
return m_IsPrimaryHand;
}
set
{
if (m_IsPrimaryHand != value)
{
m_IsPrimaryHand = value;
}
}
}
#endregion
#region IsActive
/// <summary>
/// Indicate if the hand is active or not.
/// For activate a hand, it must be in the pointing area
/// </summary>
private bool m_IsActive;
public bool IsActive
{
get
{
return m_IsActive;
}
set
{
if (m_IsActive != value)
{
m_IsActive = value;
// Notify that the hand is active
RaiseHandIsActive(this, new HandActiveEventArgs
{
HandType = this.HandType,
IsActive = this.IsActive,
PositionOnScreen = this.HandScreenPosition
});
if (m_IsActive)
{
// Notify the grip state for that the feedback display is good
RaiseHandGripStateChanged(this, new HandGripStateChangeEventArgs
{
HandType = this.HandType,
IsGrip = this.IsGrip
});
}
}
}
}
#endregion
#region IsGrip
/// <summary>
/// Indicates if the hand is grip or not.
/// The grip state correspond to the close/open hand
/// IsGrip = true => hand opened
/// IsGrip = false => hand closed
/// </summary>
private bool m_IsGrip;
public bool IsGrip
{
get
{
return m_IsGrip;
}
set
{
if (m_IsGrip != value)
{
m_IsGrip = value;
if (IsActive)
{
// Notify the hand's grip state is changed
RaiseHandGripStateChanged(this, new HandGripStateChangeEventArgs
{
HandType = this.HandType,
IsGrip = this.IsGrip,
RawPosition = HandRawPosition
});
}
}
}
}
#endregion
#endregion
#region Events
#region HandIsActive
/// <summary>
/// Event triggered when the hand is active
/// </summary>
public event EventHandler<HandActiveEventArgs> HandIsActive;
/// <summary>
/// Raise event HandIsActive
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RaiseHandIsActive(object sender, HandActiveEventArgs e)
{
if (HandIsActive != null)
{
HandIsActive(sender, e);
}
}
#endregion
#region HandMove
/// <summary>
/// Event triggered when the hand moved
/// </summary>
public event EventHandler<HandMoveEventArgs> HandMove;
/// <summary>
/// Raise event HandMove
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RaiseHandMove(object sender, HandMoveEventArgs e)
{
if (HandMove != null)
{
HandMove(sender, e);
}
}
#endregion
#region HandGripStateChanged
/// <summary>
/// Event triggered whend the hand's grip state changed
/// </summary>
public event EventHandler<HandGripStateChangeEventArgs> HandGripStateChanged;
/// <summary>
/// Raise event HandGripStateChanged
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RaiseHandGripStateChanged(object sender, HandGripStateChangeEventArgs e)
{
if (HandGripStateChanged != null)
{
HandGripStateChanged(sender, e);
}
}
#endregion
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="type">Hand typer</param>
/// <param name="tracked">Hand is active or not</param>
/// <param name="position">Hand position</param>
public HandData(InteractionHandType type)
{
HandType = type;
m_IsActive = false;
m_IsPrimaryHand = false;
m_IsGrip = false;
m_HandRawPosition = new PointF();
m_HandScreenPosition = new PointF();
}
#endregion
#region Public Methods
/// <summary>
/// Update the hand datas
/// </summary>
/// <param name="rawPosition">Hand's raw position</param>
/// <param name="handEventType">Event on the hand</param>
/// <param name="isActive">Hand is active or not</param>
/// <param name="isPrimaryHand">Hand is primary or not</param>
public void UpdateHandData(PointF rawPosition, InteractionHandEventType handEventType, bool isActive, bool isPrimaryHand)
{
// Get the hand's raw position in the kinect hand landmark
HandRawPosition = rawPosition;
// Transform the hand's raw position in the kinec hand landmark to the MGRE landmark
// This transformation take account the parameters 'SpaceBetweenHands' and 'PointingHandsAmplitude'
if (HandType == InteractionHandType.Left)
{
// I consider the hand left landmark corresponding to the left half of the screen (/2)
m_HandRawPosition.X = ((m_HandRawPosition.X + PropertiesPluginKinect.Instance.PointingSpaceBetweenHands + PropertiesPluginKinect.Instance.PointingHandsAmplitude)
/
( (1-PropertiesPluginKinect.Instance.PointingSpaceBetweenHands) +
(PropertiesPluginKinect.Instance.PointingHandsAmplitude + PropertiesPluginKinect.Instance.PointingSpaceBetweenHands))
) / 2;
}
else
{
// I concider the hand right landmark corresponding to the right half of the screen (/2 + 0.5f)
m_HandRawPosition.X = ((m_HandRawPosition.X - PropertiesPluginKinect.Instance.PointingSpaceBetweenHands) / ((1 - PropertiesPluginKinect.Instance.PointingSpaceBetweenHands) +
(PropertiesPluginKinect.Instance.PointingHandsAmplitude + PropertiesPluginKinect.Instance.PointingSpaceBetweenHands))) / 2 + 0.5f;
}
PointF handScreen = new PointF();
// Transform the hand's raw position to the hand's screen position
handScreen.X = m_HandRawPosition.X * PropertiesPluginKinect.Instance.ExperienceIntuiFaceWidth;
handScreen.Y = m_HandRawPosition.Y * PropertiesPluginKinect.Instance.ExperienceIntuifaceHeight;
HandScreenPosition = handScreen;
// Get the hand's event type
if (handEventType == InteractionHandEventType.Grip)
{
IsGrip = true;
}
else if (handEventType == InteractionHandEventType.GripRelease)
{
IsGrip = false;
}
// Update the primary hand and active hand
IsPrimaryHand = isPrimaryHand;
IsActive = isActive;
}
#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.Runtime.InteropServices;
using System.Diagnostics;
using System.ComponentModel;
namespace System.DirectoryServices.ActiveDirectory
{
public enum NotificationStatus
{
NoNotification = 0,
IntraSiteOnly = 1,
NotificationAlways = 2
}
public enum ReplicationSpan
{
IntraSite = 0,
InterSite = 1
}
public class ReplicationConnection : IDisposable
{
internal readonly DirectoryContext context = null;
internal readonly DirectoryEntry cachedDirectoryEntry = null;
internal bool existingConnection = false;
private bool _disposed = false;
private bool _checkADAM = false;
private bool _isADAMServer = false;
private int _options = 0;
private readonly string _connectionName = null;
private string _sourceServerName = null;
private string _destinationServerName = null;
private readonly ActiveDirectoryTransportType _transport = ActiveDirectoryTransportType.Rpc;
private const string ADAMGuid = "1.2.840.113556.1.4.1851";
public static ReplicationConnection FindByName(DirectoryContext context, string name)
{
ValidateArgument(context, name);
// work with copy of the context
context = new DirectoryContext(context);
// bind to the rootdse to get the servername property
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName);
string connectionContainer = "CN=NTDS Settings," + serverDN;
de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer);
// doing the search to find the connection object based on its name
ADSearcher adSearcher = new ADSearcher(de,
"(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)(name=" + Utils.GetEscapedFilterValue(name) + "))",
new string[] { "distinguishedName" },
SearchScope.OneLevel,
false, /* no paged search */
false /* don't cache results */);
SearchResult srchResult = null;
try
{
srchResult = adSearcher.FindOne();
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// object is not found since we cannot even find the container in which to search
throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
if (srchResult == null)
{
// no such connection object
Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ReplicationConnection), name);
throw e;
}
else
{
DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry();
return new ReplicationConnection(context, connectionEntry, name);
}
}
finally
{
de.Dispose();
}
}
internal ReplicationConnection(DirectoryContext context, DirectoryEntry connectionEntry, string name)
{
this.context = context;
cachedDirectoryEntry = connectionEntry;
_connectionName = name;
// this is an exising connection object
existingConnection = true;
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer) : this(context, name, sourceServer, null, ActiveDirectoryTransportType.Rpc)
{
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule) : this(context, name, sourceServer, schedule, ActiveDirectoryTransportType.Rpc)
{
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectoryTransportType transport) : this(context, name, sourceServer, null, transport)
{
}
public ReplicationConnection(DirectoryContext context, string name, DirectoryServer sourceServer, ActiveDirectorySchedule schedule, ActiveDirectoryTransportType transport)
{
ValidateArgument(context, name);
if (sourceServer == null)
throw new ArgumentNullException("sourceServer");
if (transport < ActiveDirectoryTransportType.Rpc || transport > ActiveDirectoryTransportType.Smtp)
throw new InvalidEnumArgumentException("value", (int)transport, typeof(ActiveDirectoryTransportType));
// work with copy of the context
context = new DirectoryContext(context);
ValidateTargetAndSourceServer(context, sourceServer);
this.context = context;
_connectionName = name;
_transport = transport;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName);
string connectionContainer = "CN=NTDS Settings," + serverDN;
de = DirectoryEntryManager.GetDirectoryEntry(context, connectionContainer);
// create the connection entry
string rdn = "cn=" + _connectionName;
rdn = Utils.GetEscapedPath(rdn);
cachedDirectoryEntry = de.Children.Add(rdn, "nTDSConnection");
// set all the properties
// sourceserver property
DirectoryContext sourceServerContext = sourceServer.Context;
de = DirectoryEntryManager.GetDirectoryEntry(sourceServerContext, WellKnownDN.RootDSE);
string serverName = (string)PropertyManager.GetPropertyValue(sourceServerContext, de, PropertyManager.ServerName);
serverName = "CN=NTDS Settings," + serverName;
cachedDirectoryEntry.Properties["fromServer"].Add(serverName);
// schedule property
if (schedule != null)
cachedDirectoryEntry.Properties["schedule"].Value = schedule.GetUnmanagedSchedule();
// transporttype property
string transportPath = Utils.GetDNFromTransportType(TransportType, context);
// verify that the transport is supported
de = DirectoryEntryManager.GetDirectoryEntry(context, transportPath);
try
{
de.Bind(true);
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// if it is ADAM and transport type is SMTP, throw NotSupportedException.
DirectoryEntry tmpDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
if (Utils.CheckCapability(tmpDE, Capability.ActiveDirectoryApplicationMode) && transport == ActiveDirectoryTransportType.Smtp)
{
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
cachedDirectoryEntry.Properties["transportType"].Add(transportPath);
// enabledConnection property
cachedDirectoryEntry.Properties["enabledConnection"].Value = false;
// options
cachedDirectoryEntry.Properties["options"].Value = 0;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
de.Close();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing && cachedDirectoryEntry != null)
cachedDirectoryEntry.Dispose();
_disposed = true;
}
}
~ReplicationConnection()
{
Dispose(false); // finalizer is called => Dispose has not been called yet.
}
public string Name
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return _connectionName;
}
}
public string SourceServer
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the source server
if (_sourceServerName == null)
{
string sourceServerDN = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer);
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, sourceServerDN);
if (IsADAM)
{
int portnumber = (int)PropertyManager.GetPropertyValue(context, de, PropertyManager.MsDSPortLDAP);
string tmpServerName = (string)PropertyManager.GetPropertyValue(context, de.Parent, PropertyManager.DnsHostName);
if (portnumber != 389)
{
_sourceServerName = tmpServerName + ":" + portnumber;
}
}
else
{
_sourceServerName = (string)PropertyManager.GetPropertyValue(context, de.Parent, PropertyManager.DnsHostName);
}
}
return _sourceServerName;
}
}
public string DestinationServer
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (_destinationServerName == null)
{
DirectoryEntry NTDSObject = null;
DirectoryEntry serverObject = null;
try
{
NTDSObject = cachedDirectoryEntry.Parent;
serverObject = NTDSObject.Parent;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
string hostName = (string)PropertyManager.GetPropertyValue(context, serverObject, PropertyManager.DnsHostName);
if (IsADAM)
{
int portnumber = (int)PropertyManager.GetPropertyValue(context, NTDSObject, PropertyManager.MsDSPortLDAP);
if (portnumber != 389)
{
_destinationServerName = hostName + ":" + portnumber;
}
else
_destinationServerName = hostName;
}
else
_destinationServerName = hostName;
}
return _destinationServerName;
}
}
public bool Enabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// fetch the property value
try
{
if (cachedDirectoryEntry.Properties.Contains("enabledConnection"))
return (bool)cachedDirectoryEntry.Properties["enabledConnection"][0];
else
return false;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
cachedDirectoryEntry.Properties["enabledConnection"].Value = value;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public ActiveDirectoryTransportType TransportType
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// for exisint connection, we need to check its property, for newly created and not committed one, we just return
// the member variable value directly
if (existingConnection)
{
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["transportType"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
return ActiveDirectoryTransportType.Rpc;
}
else
{
return Utils.GetTransportTypeFromDN((string)propValue[0]);
}
}
else
return _transport;
}
}
public bool GeneratedByKcc
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) object generated by DS, not admin
if ((_options & 0x1) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) object generated by DS, not admin
if (value)
{
_options |= 0x1;
}
else
{
_options &= (~(0x1));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool ReciprocalReplicationEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync
if ((_options & 0x2) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_TWOWAY_SYNC ( 1 << 1 ) force sync in opposite direction at end of sync
if (value == true)
{
_options |= 0x2;
}
else
{
_options &= (~(0x2));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public NotificationStatus ChangeNotificationStatus
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
int overrideNotify = _options & 0x4;
int userNotify = _options & 0x8;
if (overrideNotify == 0x4 && userNotify == 0)
return NotificationStatus.NoNotification;
else if (overrideNotify == 0x4 && userNotify == 0x8)
return NotificationStatus.NotificationAlways;
else
return NotificationStatus.IntraSiteOnly;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (value < NotificationStatus.NoNotification || value > NotificationStatus.NotificationAlways)
throw new InvalidEnumArgumentException("value", (int)value, typeof(NotificationStatus));
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
if (value == NotificationStatus.IntraSiteOnly)
{
_options &= (~(0x4));
_options &= (~(0x8));
}
else if (value == NotificationStatus.NoNotification)
{
_options |= (0x4);
_options &= (~(0x8));
}
else
{
_options |= (0x4);
_options |= (0x8);
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool DataCompressionEnabled
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
//NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION (1 << 4)
// 0 - Compression of replication data enabled
// 1 - Compression of replication data disabled
if ((_options & 0x10) == 0)
return true;
else
return false;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
//NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION (1 << 4)
// 0 - Compression of replication data enabled
// 1 - Compression of replication data disabled
if (value == false)
{
_options |= 0x10;
}
else
{
_options &= (~(0x10));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public bool ReplicationScheduleOwnedByUser
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
PropertyValueCollection propValue = null;
try
{
propValue = cachedDirectoryEntry.Properties["options"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (propValue.Count == 0)
{
// if the property does not exist, then default is to RPC over IP
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_USER_OWNED_SCHEDULE (1 << 5)
if ((_options & 0x20) == 0)
return false;
else
return true;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
PropertyValueCollection propValue = cachedDirectoryEntry.Properties["options"];
if (propValue.Count == 0)
{
_options = 0;
}
else
{
_options = (int)propValue[0];
}
// NTDSCONN_OPT_USER_OWNED_SCHEDULE (1 << 5)
if (value == true)
{
_options |= 0x20;
}
else
{
_options &= (~(0x20));
}
// put the value into cache
cachedDirectoryEntry.Properties["options"].Value = _options;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public ReplicationSpan ReplicationSpan
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// find out whether the site and the destination is in the same site
string destinationPath = (string)PropertyManager.GetPropertyValue(context, cachedDirectoryEntry, PropertyManager.FromServer);
string destinationSite = Utils.GetDNComponents(destinationPath)[3].Value;
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string serverDN = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ServerName);
string serverSite = Utils.GetDNComponents(serverDN)[2].Value;
if (Utils.Compare(destinationSite, serverSite) == 0)
{
return ReplicationSpan.IntraSite;
}
else
{
return ReplicationSpan.InterSite;
}
}
}
public ActiveDirectorySchedule ReplicationSchedule
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
ActiveDirectorySchedule schedule = null;
bool scheduleExists = false;
try
{
scheduleExists = cachedDirectoryEntry.Properties.Contains("schedule");
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (scheduleExists)
{
byte[] tmpSchedule = (byte[])cachedDirectoryEntry.Properties["schedule"][0];
Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188);
schedule = new ActiveDirectorySchedule();
schedule.SetUnmanagedSchedule(tmpSchedule);
}
return schedule;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
if (value == null)
{
if (cachedDirectoryEntry.Properties.Contains("schedule"))
cachedDirectoryEntry.Properties["schedule"].Clear();
}
else
{
cachedDirectoryEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule();
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
private bool IsADAM
{
get
{
if (!_checkADAM)
{
DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
PropertyValueCollection values = null;
try
{
values = de.Properties["supportedCapabilities"];
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (values.Contains(ADAMGuid))
_isADAMServer = true;
}
return _isADAMServer;
}
}
public void Delete()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existingConnection)
{
throw new InvalidOperationException(SR.CannotDelete);
}
else
{
try
{
cachedDirectoryEntry.Parent.Children.Remove(cachedDirectoryEntry);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
public void Save()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
try
{
cachedDirectoryEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
if (!existingConnection)
{
existingConnection = true;
}
}
public override string ToString()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return Name;
}
public DirectoryEntry GetDirectoryEntry()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (!existingConnection)
{
throw new InvalidOperationException(SR.CannotGetObject);
}
else
{
return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedDirectoryEntry.Path);
}
}
private static void ValidateArgument(DirectoryContext context, string name)
{
if (context == null)
throw new ArgumentNullException("context");
// the target of the scope must be server
if (context.Name == null || !context.isServer())
throw new ArgumentException(SR.DirectoryContextNeedHost);
if (name == null)
throw new ArgumentNullException("name");
if (name.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, "name");
}
private void ValidateTargetAndSourceServer(DirectoryContext context, DirectoryServer sourceServer)
{
bool targetIsDC = false;
DirectoryEntry targetDE = null;
DirectoryEntry sourceDE = null;
// first find out target is a dc or ADAM instance
targetDE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
if (Utils.CheckCapability(targetDE, Capability.ActiveDirectory))
{
targetIsDC = true;
}
else if (!Utils.CheckCapability(targetDE, Capability.ActiveDirectoryApplicationMode))
{
// if it is also not an ADAM instance, it is invalid then
throw new ArgumentException(SR.DirectoryContextNeedHost, "context");
}
if (targetIsDC && !(sourceServer is DomainController))
{
// target and sourceServer are not of the same type
throw new ArgumentException(SR.ConnectionSourcServerShouldBeDC, "sourceServer");
}
else if (!targetIsDC && (sourceServer is DomainController))
{
// target and sourceServer are not of the same type
throw new ArgumentException(SR.ConnectionSourcServerShouldBeADAM, "sourceServer");
}
sourceDE = DirectoryEntryManager.GetDirectoryEntry(sourceServer.Context, WellKnownDN.RootDSE);
// now if they are both dc, we need to check whether they come from the same forest
if (targetIsDC)
{
string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.RootDomainNamingContext);
string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.RootDomainNamingContext);
if (Utils.Compare(targetRoot, sourceRoot) != 0)
{
throw new ArgumentException(SR.ConnectionSourcServerSameForest, "sourceServer");
}
}
else
{
string targetRoot = (string)PropertyManager.GetPropertyValue(context, targetDE, PropertyManager.ConfigurationNamingContext);
string sourceRoot = (string)PropertyManager.GetPropertyValue(sourceServer.Context, sourceDE, PropertyManager.ConfigurationNamingContext);
if (Utils.Compare(targetRoot, sourceRoot) != 0)
{
throw new ArgumentException(SR.ConnectionSourcServerSameConfigSet, "sourceServer");
}
}
}
catch (COMException e)
{
ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (targetDE != null)
targetDE.Close();
if (sourceDE != null)
sourceDE.Close();
}
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
public sealed partial class DBNull
{
internal DBNull() { }
public static readonly System.DBNull Value;
public override string ToString() { return default(string); }
public string ToString(System.IFormatProvider provider) { return default(string); }
}
}
namespace System.Data
{
[System.FlagsAttribute]
public enum CommandBehavior
{
CloseConnection = 32,
Default = 0,
KeyInfo = 4,
SchemaOnly = 2,
SequentialAccess = 16,
SingleResult = 1,
SingleRow = 8,
}
public enum CommandType
{
StoredProcedure = 4,
TableDirect = 512,
Text = 1,
}
[System.FlagsAttribute]
public enum ConnectionState
{
Broken = 16,
Closed = 0,
Connecting = 2,
Executing = 4,
Fetching = 8,
Open = 1,
}
public enum DataRowVersion
{
Default = 1536,
}
public partial class DataTable
{
internal DataTable() { }
}
public enum DbType
{
AnsiString = 0,
AnsiStringFixedLength = 22,
Binary = 1,
Boolean = 3,
Byte = 2,
Currency = 4,
Date = 5,
DateTime = 6,
DateTime2 = 26,
DateTimeOffset = 27,
Decimal = 7,
Double = 8,
Guid = 9,
Int16 = 10,
Int32 = 11,
Int64 = 12,
Object = 13,
SByte = 14,
Single = 15,
String = 16,
StringFixedLength = 23,
Time = 17,
UInt16 = 18,
UInt32 = 19,
UInt64 = 20,
VarNumeric = 21,
Xml = 25,
}
public partial interface IDataParameter
{
System.Data.DbType DbType { get; set; }
System.Data.ParameterDirection Direction { get; set; }
bool IsNullable { get; }
string ParameterName { get; set; }
string SourceColumn { get; set; }
System.Data.DataRowVersion SourceVersion { get; set; }
object Value { get; set; }
}
public partial interface IDataParameterCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
object this[string parameterName] { get; set; }
bool Contains(string parameterName);
int IndexOf(string parameterName);
void RemoveAt(string parameterName);
}
public partial interface IDataReader : System.Data.IDataRecord, System.IDisposable
{
int Depth { get; }
bool IsClosed { get; }
int RecordsAffected { get; }
void Close();
System.Data.DataTable GetSchemaTable();
bool NextResult();
bool Read();
}
public partial interface IDataRecord
{
int FieldCount { get; }
object this[int i] { get; }
object this[string name] { get; }
bool GetBoolean(int i);
byte GetByte(int i);
long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length);
char GetChar(int i);
long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length);
System.Data.IDataReader GetData(int i);
string GetDataTypeName(int i);
System.DateTime GetDateTime(int i);
decimal GetDecimal(int i);
double GetDouble(int i);
System.Type GetFieldType(int i);
float GetFloat(int i);
System.Guid GetGuid(int i);
short GetInt16(int i);
int GetInt32(int i);
long GetInt64(int i);
string GetName(int i);
int GetOrdinal(string name);
string GetString(int i);
object GetValue(int i);
int GetValues(object[] values);
bool IsDBNull(int i);
}
public partial interface IDbCommand : System.IDisposable
{
string CommandText { get; set; }
int CommandTimeout { get; set; }
System.Data.CommandType CommandType { get; set; }
System.Data.IDbConnection Connection { get; set; }
System.Data.IDataParameterCollection Parameters { get; }
System.Data.IDbTransaction Transaction { get; set; }
System.Data.UpdateRowSource UpdatedRowSource { get; set; }
void Cancel();
System.Data.IDbDataParameter CreateParameter();
int ExecuteNonQuery();
System.Data.IDataReader ExecuteReader();
System.Data.IDataReader ExecuteReader(System.Data.CommandBehavior behavior);
object ExecuteScalar();
void Prepare();
}
public partial interface IDbConnection : System.IDisposable
{
string ConnectionString { get; set; }
int ConnectionTimeout { get; }
string Database { get; }
System.Data.ConnectionState State { get; }
System.Data.IDbTransaction BeginTransaction();
System.Data.IDbTransaction BeginTransaction(System.Data.IsolationLevel il);
void ChangeDatabase(string databaseName);
void Close();
System.Data.IDbCommand CreateCommand();
void Open();
}
public partial interface IDbDataParameter : System.Data.IDataParameter
{
byte Precision { get; set; }
byte Scale { get; set; }
int Size { get; set; }
}
public partial interface IDbTransaction : System.IDisposable
{
System.Data.IDbConnection Connection { get; }
System.Data.IsolationLevel IsolationLevel { get; }
void Commit();
void Rollback();
}
public enum IsolationLevel
{
Chaos = 16,
ReadCommitted = 4096,
ReadUncommitted = 256,
RepeatableRead = 65536,
Serializable = 1048576,
Snapshot = 16777216,
Unspecified = -1,
}
public enum ParameterDirection
{
Input = 1,
InputOutput = 3,
Output = 2,
ReturnValue = 6,
}
public sealed partial class StateChangeEventArgs : System.EventArgs
{
public StateChangeEventArgs(System.Data.ConnectionState originalState, System.Data.ConnectionState currentState) { }
public System.Data.ConnectionState CurrentState { get { return default(System.Data.ConnectionState); } }
public System.Data.ConnectionState OriginalState { get { return default(System.Data.ConnectionState); } }
}
public delegate void StateChangeEventHandler(object sender, System.Data.StateChangeEventArgs e);
public enum UpdateRowSource
{
Both = 3,
FirstReturnedRecord = 2,
None = 0,
OutputParameters = 1,
}
}
namespace System.Data.Common
{
public abstract partial class DbCommand : System.IDisposable
{
protected DbCommand() { }
public abstract string CommandText { get; set; }
public abstract int CommandTimeout { get; set; }
public abstract System.Data.CommandType CommandType { get; set; }
public System.Data.Common.DbConnection Connection { get { return default(System.Data.Common.DbConnection); } set { } }
protected abstract System.Data.Common.DbConnection DbConnection { get; set; }
protected abstract System.Data.Common.DbParameterCollection DbParameterCollection { get; }
protected abstract System.Data.Common.DbTransaction DbTransaction { get; set; }
public abstract bool DesignTimeVisible { get; set; }
public System.Data.Common.DbParameterCollection Parameters { get { return default(System.Data.Common.DbParameterCollection); } }
public System.Data.Common.DbTransaction Transaction { get { return default(System.Data.Common.DbTransaction); } set { } }
public abstract System.Data.UpdateRowSource UpdatedRowSource { get; set; }
public abstract void Cancel();
protected abstract System.Data.Common.DbParameter CreateDbParameter();
public System.Data.Common.DbParameter CreateParameter() { return default(System.Data.Common.DbParameter); }
protected abstract System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior);
protected virtual System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteDbDataReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public abstract int ExecuteNonQuery();
public System.Threading.Tasks.Task<int> ExecuteNonQueryAsync() { return default(System.Threading.Tasks.Task<int>); }
public virtual System.Threading.Tasks.Task<int> ExecuteNonQueryAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public System.Data.Common.DbDataReader ExecuteReader() { return default(System.Data.Common.DbDataReader); }
public System.Data.Common.DbDataReader ExecuteReader(System.Data.CommandBehavior behavior) { return default(System.Data.Common.DbDataReader); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync() { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public abstract object ExecuteScalar();
public System.Threading.Tasks.Task<object> ExecuteScalarAsync() { return default(System.Threading.Tasks.Task<object>); }
public virtual System.Threading.Tasks.Task<object> ExecuteScalarAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<object>); }
public abstract void Prepare();
}
public abstract partial class DbConnection : System.IDisposable
{
protected DbConnection() { }
public abstract string ConnectionString { get; set; }
public virtual int ConnectionTimeout { get { return default(int); } }
public abstract string Database { get; }
public abstract string DataSource { get; }
public abstract string ServerVersion { get; }
public abstract System.Data.ConnectionState State { get; }
public virtual event System.Data.StateChangeEventHandler StateChange { add { } remove { } }
protected abstract System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel);
public System.Data.Common.DbTransaction BeginTransaction() { return default(System.Data.Common.DbTransaction); }
public System.Data.Common.DbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) { return default(System.Data.Common.DbTransaction); }
public abstract void ChangeDatabase(string databaseName);
public abstract void Close();
public System.Data.Common.DbCommand CreateCommand() { return default(System.Data.Common.DbCommand); }
protected abstract System.Data.Common.DbCommand CreateDbCommand();
protected virtual void OnStateChange(System.Data.StateChangeEventArgs stateChange) { }
public abstract void Open();
public System.Threading.Tasks.Task OpenAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task OpenAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
}
public partial class DbConnectionStringBuilder : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public DbConnectionStringBuilder() { }
public string ConnectionString { get { return default(string); } set { } }
public virtual int Count { get { return default(int); } }
public virtual object this[string keyword] { get { return default(object); } set { } }
public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } }
object System.Collections.IDictionary.this[object keyword] { get { return default(object); } set { } }
public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } }
public void Add(string keyword, object value) { }
public static void AppendKeyValuePair(System.Text.StringBuilder builder, string keyword, string value) { }
public virtual void Clear() { }
public virtual bool ContainsKey(string keyword) { return default(bool); }
public virtual bool EquivalentTo(System.Data.Common.DbConnectionStringBuilder connectionStringBuilder) { return default(bool); }
public virtual bool Remove(string keyword) { return default(bool); }
public virtual bool ShouldSerialize(string keyword) { return default(bool); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object keyword, object value) { }
bool System.Collections.IDictionary.Contains(object keyword) { return default(bool); }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
void System.Collections.IDictionary.Remove(object keyword) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public override string ToString() { return default(string); }
public virtual bool TryGetValue(string keyword, out object value) { value = default(object); return default(bool); }
}
public abstract partial class DbDataReader : System.Collections.IEnumerable, System.IDisposable
{
protected DbDataReader() { }
public abstract int Depth { get; }
public abstract int FieldCount { get; }
public abstract bool HasRows { get; }
public abstract bool IsClosed { get; }
public abstract object this[int ordinal] { get; }
public abstract object this[string name] { get; }
public abstract int RecordsAffected { get; }
public virtual int VisibleFieldCount { get { return default(int); } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract bool GetBoolean(int ordinal);
public abstract byte GetByte(int ordinal);
public abstract long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length);
public abstract char GetChar(int ordinal);
public abstract long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length);
public System.Data.Common.DbDataReader GetData(int ordinal) { return default(System.Data.Common.DbDataReader); }
public abstract string GetDataTypeName(int ordinal);
public abstract System.DateTime GetDateTime(int ordinal);
protected virtual System.Data.Common.DbDataReader GetDbDataReader(int ordinal) { return default(System.Data.Common.DbDataReader); }
public abstract decimal GetDecimal(int ordinal);
public abstract double GetDouble(int ordinal);
public abstract System.Collections.IEnumerator GetEnumerator();
public abstract System.Type GetFieldType(int ordinal);
public virtual T GetFieldValue<T>(int ordinal) { return default(T); }
public System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int ordinal) { return default(System.Threading.Tasks.Task<T>); }
public virtual System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int ordinal, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<T>); }
public abstract float GetFloat(int ordinal);
public abstract System.Guid GetGuid(int ordinal);
public abstract short GetInt16(int ordinal);
public abstract int GetInt32(int ordinal);
public abstract long GetInt64(int ordinal);
public abstract string GetName(int ordinal);
public abstract int GetOrdinal(string name);
public virtual System.Type GetProviderSpecificFieldType(int ordinal) { return default(System.Type); }
public virtual object GetProviderSpecificValue(int ordinal) { return default(object); }
public virtual int GetProviderSpecificValues(object[] values) { return default(int); }
public virtual System.IO.Stream GetStream(int ordinal) { return default(System.IO.Stream); }
public abstract string GetString(int ordinal);
public virtual System.IO.TextReader GetTextReader(int ordinal) { return default(System.IO.TextReader); }
public abstract object GetValue(int ordinal);
public abstract int GetValues(object[] values);
public abstract bool IsDBNull(int ordinal);
public System.Threading.Tasks.Task<bool> IsDBNullAsync(int ordinal) { return default(System.Threading.Tasks.Task<bool>); }
public virtual System.Threading.Tasks.Task<bool> IsDBNullAsync(int ordinal, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); }
public abstract bool NextResult();
public System.Threading.Tasks.Task<bool> NextResultAsync() { return default(System.Threading.Tasks.Task<bool>); }
public virtual System.Threading.Tasks.Task<bool> NextResultAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); }
public abstract bool Read();
public System.Threading.Tasks.Task<bool> ReadAsync() { return default(System.Threading.Tasks.Task<bool>); }
public virtual System.Threading.Tasks.Task<bool> ReadAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); }
}
public abstract partial class DbDataRecord : System.Data.IDataRecord
{
protected DbDataRecord() { }
public abstract int FieldCount { get; }
public abstract object this[int i] { get; }
public abstract object this[string name] { get; }
public abstract bool GetBoolean(int i);
public abstract byte GetByte(int i);
public abstract long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length);
public abstract char GetChar(int i);
public abstract long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length);
public System.Data.IDataReader GetData(int i) { return default(System.Data.IDataReader); }
public abstract string GetDataTypeName(int i);
public abstract System.DateTime GetDateTime(int i);
protected virtual System.Data.Common.DbDataReader GetDbDataReader(int i) { return default(System.Data.Common.DbDataReader); }
public abstract decimal GetDecimal(int i);
public abstract double GetDouble(int i);
public abstract System.Type GetFieldType(int i);
public abstract float GetFloat(int i);
public abstract System.Guid GetGuid(int i);
public abstract short GetInt16(int i);
public abstract int GetInt32(int i);
public abstract long GetInt64(int i);
public abstract string GetName(int i);
public abstract int GetOrdinal(string name);
public abstract string GetString(int i);
public abstract object GetValue(int i);
public abstract int GetValues(object[] values);
public abstract bool IsDBNull(int i);
}
public abstract partial class DbException : System.Exception
{
protected DbException() { }
protected DbException(string message) { }
protected DbException(string message, System.Exception innerException) { }
}
public abstract partial class DbParameter
{
protected DbParameter() { }
public abstract System.Data.DbType DbType { get; set; }
public abstract System.Data.ParameterDirection Direction { get; set; }
public abstract bool IsNullable { get; set; }
public abstract string ParameterName { get; set; }
public virtual byte Precision { get { return default(byte); } set { } }
public virtual byte Scale { get { return default(byte); } set { } }
public abstract int Size { get; set; }
public abstract string SourceColumn { get; set; }
public abstract bool SourceColumnNullMapping { get; set; }
public abstract object Value { get; set; }
public abstract void ResetDbType();
}
public abstract partial class DbParameterCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
protected DbParameterCollection() { }
public abstract int Count { get; }
public System.Data.Common.DbParameter this[int index] { get { return default(System.Data.Common.DbParameter); } set { } }
public System.Data.Common.DbParameter this[string parameterName] { get { return default(System.Data.Common.DbParameter); } set { } }
public abstract object SyncRoot { get; }
object System.Collections.IList.this[int index] { get { return default(object); } set { } }
public abstract int Add(object value);
public abstract void AddRange(System.Array values);
public abstract void Clear();
public abstract bool Contains(object value);
public abstract bool Contains(string value);
public abstract void CopyTo(System.Array array, int index);
public abstract System.Collections.IEnumerator GetEnumerator();
protected abstract System.Data.Common.DbParameter GetParameter(int index);
protected abstract System.Data.Common.DbParameter GetParameter(string parameterName);
public abstract int IndexOf(object value);
public abstract int IndexOf(string parameterName);
public abstract void Insert(int index, object value);
public abstract void Remove(object value);
public abstract void RemoveAt(int index);
public abstract void RemoveAt(string parameterName);
protected abstract void SetParameter(int index, System.Data.Common.DbParameter value);
protected abstract void SetParameter(string parameterName, System.Data.Common.DbParameter value);
}
public abstract partial class DbProviderFactory
{
protected DbProviderFactory() { }
public virtual System.Data.Common.DbCommand CreateCommand() { return default(System.Data.Common.DbCommand); }
public virtual System.Data.Common.DbConnection CreateConnection() { return default(System.Data.Common.DbConnection); }
public virtual System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { return default(System.Data.Common.DbConnectionStringBuilder); }
public virtual System.Data.Common.DbParameter CreateParameter() { return default(System.Data.Common.DbParameter); }
}
public abstract partial class DbTransaction : System.IDisposable
{
protected DbTransaction() { }
public System.Data.Common.DbConnection Connection { get { return default(System.Data.Common.DbConnection); } }
protected abstract System.Data.Common.DbConnection DbConnection { get; }
public abstract System.Data.IsolationLevel IsolationLevel { get; }
public abstract void Commit();
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void Rollback();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str_str : Directory_GetFileSystemEntries_str
{
#region Utilities
public override string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName, "*");
}
public virtual string[] GetEntries(string dirName, string searchPattern)
{
return Directory.GetFileSystemEntries(dirName, searchPattern);
}
#endregion
#region UniversalTests
[Fact]
public void SearchPatternNull()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(TestDirectory, null));
}
[Fact]
public void SearchPatternEmpty()
{
// To avoid OS differences we have decided not to throw an argument exception when empty
// string passed. But we should return 0 items.
Assert.Empty(GetEntries(TestDirectory, string.Empty));
}
[Fact]
public void SearchPatternValid()
{
Assert.Empty(GetEntries(TestDirectory, "a..b abc..d")); //Should not throw
}
[Fact]
public void SearchPatternDotIsStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
{
string[] strArr = GetEntries(testDir.FullName, ".");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
}
}
[Fact]
public void SearchPatternWithTrailingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "Test1*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternWithLeadingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "*2");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*Dir*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternExactMatch()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAA"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAAB"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "CAAA"));
using (File.Create(Path.Combine(testDir.FullName, "AAABB")))
using (File.Create(Path.Combine(testDir.FullName, "AAABBC")))
using (File.Create(Path.Combine(testDir.FullName, "CAAABB")))
{
if (TestFiles)
{
string[] results = GetEntries(testDir.FullName, "AAABB");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAABB"), results);
}
if (TestDirectories)
{
string[] results = GetEntries(testDir.FullName, "AAA");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAA"), results);
}
}
}
[Fact]
public void SearchPatternIgnoreSubDirectories()
{
//Shouldn't get files on full path by default
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, Path.Combine(testDir.Name, "*"));
if (TestDirectories && TestFiles)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSearchPatternLongSegment()
{
// Create a path segment longer than the normal max of 255
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 257);
Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
}
[Fact]
public void SearchPatternLongPath()
{
// Create a destination path longer than the traditional Windows limit of 256 characters
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 254);
string longFullname = Path.Combine(testDir.FullName, longName);
if (TestFiles)
{
using (File.Create(longFullname)) { }
}
else
{
Directory.CreateDirectory(longFullname);
}
string[] results = GetEntries(testDir.FullName, longName);
Assert.Contains(longFullname, results);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSearchPatternWithDoubleDots()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ">"));
Char[] invalidFileNames = Path.GetInvalidFileNameChars();
for (int i = 0; i < invalidFileNames.Length; i++)
{
switch (invalidFileNames[i])
{
case '\\':
case '/':
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())));
break;
//We dont throw in V1 too
case ':':
//History:
// 1) we assumed that this will work in all non-9x machine
// 2) Then only in XP
// 3) NTFS?
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
FileSystemDebugInfo.IsCurrentDriveNTFS()) // testing NTFS
{
Assert.Throws<IOException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())));
}
else
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()));
}
break;
case '*':
case '?':
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString()));
break;
default:
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidFileNames[i].ToString())));
break;
}
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, string.Format("te{0}st", "\0".ToString())));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSearchPatternQuestionMarks()
{
string testDir1Str = GetTestFileName();
DirectoryInfo testDir = new DirectoryInfo(TestDirectory);
DirectoryInfo testDir1 = testDir.CreateSubdirectory(testDir1Str);
using (File.Create(Path.Combine(TestDirectory, testDir1Str, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, string.Format("{0}.???", new string('?', GetTestFileName().Length)));
if (TestFiles && TestDirectories)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSearchPatternWhitespace()
{
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\n"));
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\t"));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void SearchPatternCaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void SearchPatternCaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixSearchPatternFileValidChar()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixSearchPatternDirectoryValidChar()
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
testDir.CreateSubdirectory(valid);
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixSearchPatternWithDoubleDots()
{
// search pattern is valid but directory doesn't exist
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
// invalid search pattern trying to go up a directory with ..
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc", "..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "..", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc") + Path.DirectorySeparatorChar));
}
#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.IO;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl.Xslt;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System.Xml.Xsl.Runtime
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class XsltFunctions
{
private static readonly CompareInfo s_compareInfo = CultureInfo.InvariantCulture.CompareInfo;
//------------------------------------------------
// Xslt/XPath functions
//------------------------------------------------
public static bool StartsWith(string s1, string s2)
{
//return collation.IsPrefix(s1, s2);
return s1.Length >= s2.Length && string.CompareOrdinal(s1, 0, s2, 0, s2.Length) == 0;
}
public static bool Contains(string s1, string s2)
{
//return collation.IndexOf(s1, s2) >= 0;
return s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal) >= 0;
}
public static string SubstringBefore(string s1, string s2)
{
if (s2.Length == 0) { return s2; }
//int idx = collation.IndexOf(s1, s2);
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 1) ? string.Empty : s1.Substring(0, idx);
}
public static string SubstringAfter(string s1, string s2)
{
if (s2.Length == 0) { return s1; }
//int idx = collation.IndexOf(s1, s2);
int idx = s_compareInfo.IndexOf(s1, s2, CompareOptions.Ordinal);
return (idx < 0) ? string.Empty : s1.Substring(idx + s2.Length);
}
public static string Substring(string value, double startIndex)
{
startIndex = Round(startIndex);
if (startIndex <= 0)
{
return value;
}
else if (startIndex <= value.Length)
{
return value.Substring((int)startIndex - 1);
}
else
{
Debug.Assert(value.Length < startIndex || double.IsNaN(startIndex));
return string.Empty;
}
}
public static string Substring(string value, double startIndex, double length)
{
startIndex = Round(startIndex) - 1; // start index
if (startIndex >= value.Length)
{
return string.Empty;
}
double endIndex = startIndex + Round(length); // end index
startIndex = (startIndex <= 0) ? 0 : startIndex;
if (startIndex < endIndex)
{
if (endIndex > value.Length)
{
endIndex = value.Length;
}
Debug.Assert(0 <= startIndex && startIndex <= endIndex && endIndex <= value.Length);
return value.Substring((int)startIndex, (int)(endIndex - startIndex));
}
else
{
Debug.Assert(endIndex <= startIndex || double.IsNaN(endIndex));
return string.Empty;
}
}
public static string NormalizeSpace(string value)
{
XmlCharType xmlCharType = XmlCharType.Instance;
StringBuilder sb = null;
int idx, idxStart = 0, idxSpace = 0;
for (idx = 0; idx < value.Length; idx++)
{
if (xmlCharType.IsWhiteSpace(value[idx]))
{
if (idx == idxStart)
{
// Previous character was a whitespace character, so discard this character
idxStart++;
}
else if (value[idx] != ' ' || idxSpace == idx)
{
// Space was previous character or this is a non-space character
if (sb == null)
sb = new StringBuilder(value.Length);
else
sb.Append(' ');
// Copy non-space characters into string builder
if (idxSpace == idx)
sb.Append(value, idxStart, idx - idxStart - 1);
else
sb.Append(value, idxStart, idx - idxStart);
idxStart = idx + 1;
}
else
{
// Single whitespace character doesn't cause normalization, but mark its position
idxSpace = idx + 1;
}
}
}
if (sb == null)
{
// Check for string that is entirely composed of whitespace
if (idxStart == idx) return string.Empty;
// If string does not end with a space, then it must already be normalized
if (idxStart == 0 && idxSpace != idx) return value;
sb = new StringBuilder(value.Length);
}
else if (idx != idxStart)
{
sb.Append(' ');
}
// Copy non-space characters into string builder
if (idxSpace == idx)
sb.Append(value, idxStart, idx - idxStart - 1);
else
sb.Append(value, idxStart, idx - idxStart);
return sb.ToString();
}
public static string Translate(string arg, string mapString, string transString)
{
if (mapString.Length == 0)
{
return arg;
}
StringBuilder sb = new StringBuilder(arg.Length);
for (int i = 0; i < arg.Length; i++)
{
int index = mapString.IndexOf(arg[i]);
if (index < 0)
{
// Keep the character
sb.Append(arg[i]);
}
else if (index < transString.Length)
{
// Replace the character
sb.Append(transString[index]);
}
else
{
// Remove the character
}
}
return sb.ToString();
}
public static bool Lang(string value, XPathNavigator context)
{
string lang = context.XmlLang;
if (!lang.StartsWith(value, StringComparison.OrdinalIgnoreCase))
{
return false;
}
return (lang.Length == value.Length || lang[value.Length] == '-');
}
// Round value using XPath rounding rules (round towards positive infinity).
// Values between -0.5 and -0.0 are rounded to -0.0 (negative zero).
public static double Round(double value)
{
double temp = Math.Round(value);
return (value - temp == 0.5) ? temp + 1 : temp;
}
// Spec: http://www.w3.org/TR/xslt.html#function-system-property
public static XPathItem SystemProperty(XmlQualifiedName name)
{
if (name.Namespace == XmlReservedNs.NsXslt)
{
// "xsl:version" must return 1.0 as a number, see http://www.w3.org/TR/xslt20/#incompatility-without-schema
switch (name.Name)
{
case "version": return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Double), 1.0);
case "vendor": return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), "Microsoft");
case "vendor-url": return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), "http://www.microsoft.com");
}
}
else if (name.Namespace == XmlReservedNs.NsMsxsl && name.Name == "version")
{
// msxsl:version
return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), typeof(XsltLibrary).Assembly.ImageRuntimeVersion);
}
// If the property name is not recognized, return the empty string
return new XmlAtomicValue(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), string.Empty);
}
//------------------------------------------------
// Navigator functions
//------------------------------------------------
public static string BaseUri(XPathNavigator navigator)
{
return navigator.BaseURI;
}
public static string OuterXml(XPathNavigator navigator)
{
RtfNavigator rtf = navigator as RtfNavigator;
if (rtf == null)
{
return navigator.OuterXml;
}
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.CheckCharacters = false;
XmlWriter xw = XmlWriter.Create(sb, settings);
rtf.CopyToWriter(xw);
xw.Close();
return sb.ToString();
}
//------------------------------------------------
// EXslt Functions
//------------------------------------------------
public static string EXslObjectType(IList<XPathItem> value)
{
if (value.Count != 1)
{
XsltLibrary.CheckXsltValue(value);
return "node-set";
}
XPathItem item = value[0];
if (item is RtfNavigator)
{
return "RTF";
}
else if (item.IsNode)
{
Debug.Assert(item is XPathNavigator);
return "node-set";
}
object o = item.TypedValue;
if (o is string)
{
return "string";
}
else if (o is double)
{
return "number";
}
else if (o is bool)
{
return "boolean";
}
else
{
Debug.Fail("Unexpected type: " + o.GetType().ToString());
return "external";
}
}
//------------------------------------------------
// Msxml Extension Functions
//------------------------------------------------
public static double MSNumber(IList<XPathItem> value)
{
XsltLibrary.CheckXsltValue(value);
if (value.Count == 0)
{
return double.NaN;
}
XPathItem item = value[0];
string stringValue;
if (item.IsNode)
{
stringValue = item.Value;
}
else
{
Type itemType = item.ValueType;
if (itemType == XsltConvert.StringType)
{
stringValue = item.Value;
}
else if (itemType == XsltConvert.DoubleType)
{
return item.ValueAsDouble;
}
else
{
Debug.Assert(itemType == XsltConvert.BooleanType, "Unexpected type of atomic value " + itemType.ToString());
return item.ValueAsBoolean ? 1d : 0d;
}
}
Debug.Assert(stringValue != null);
double d;
if (XmlConvert.TryToDouble(stringValue, out d) != null)
{
d = double.NaN;
}
return d;
}
// string ms:format-date(string datetime[, string format[, string language]])
// string ms:format-time(string datetime[, string format[, string language]])
//
// Format xsd:dateTime as a date/time string for a given language using a given format string.
// * Datetime contains a lexical representation of xsd:dateTime. If datetime is not valid, the
// empty string is returned.
// * Format specifies a format string in the same way as for GetDateFormat/GetTimeFormat system
// functions. If format is the empty string or not passed, the default date/time format for the
// given culture is used.
// * Language specifies a culture used for formatting. If language is the empty string or not
// passed, the current culture is used. If language is not recognized, a runtime error happens.
public static string MSFormatDateTime(string dateTime, string format, string lang, bool isDate)
{
try
{
string locale = GetCultureInfo(lang).Name;
XsdDateTime xdt;
if (!XsdDateTime.TryParse(dateTime, XsdDateTimeFlags.AllXsd | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrTimeNoTz, out xdt))
{
return string.Empty;
}
DateTime dt = xdt.ToZulu();
// If format is the empty string or not specified, use the default format for the given locale
if (format.Length == 0)
{
format = null;
}
return dt.ToString(format, new CultureInfo(locale));
}
catch (ArgumentException)
{ // Operations with DateTime can throw this exception eventualy
return string.Empty;
}
}
public static double MSStringCompare(string s1, string s2, string lang, string options)
{
CultureInfo cultinfo = GetCultureInfo(lang);
CompareOptions opts = CompareOptions.None;
bool upperFirst = false;
for (int idx = 0; idx < options.Length; idx++)
{
switch (options[idx])
{
case 'i':
opts = CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;
break;
case 'u':
upperFirst = true;
break;
default:
upperFirst = true;
opts = CompareOptions.IgnoreCase;
break;
}
}
if (upperFirst)
{
if (opts != CompareOptions.None)
{
throw new XslTransformException(SR.Xslt_InvalidCompareOption, options);
}
opts = CompareOptions.IgnoreCase;
}
int result = cultinfo.CompareInfo.Compare(s1, s2, opts);
if (upperFirst && result == 0)
{
result = -cultinfo.CompareInfo.Compare(s1, s2, CompareOptions.None);
}
return result;
}
public static string MSUtc(string dateTime)
{
XsdDateTime xdt;
DateTime dt;
try
{
if (!XsdDateTime.TryParse(dateTime, XsdDateTimeFlags.AllXsd | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrTimeNoTz, out xdt))
{
return string.Empty;
}
dt = xdt.ToZulu();
}
catch (ArgumentException)
{ // Operations with DateTime can throw this exception eventualy
return string.Empty;
}
char[] text = "----------T00:00:00.000".ToCharArray();
// "YYYY-MM-DDTHH:NN:SS.III"
// 0 1 2
// 01234567890123456789012
switch (xdt.TypeCode)
{
case XmlTypeCode.DateTime:
PrintDate(text, dt);
PrintTime(text, dt);
break;
case XmlTypeCode.Time:
PrintTime(text, dt);
break;
case XmlTypeCode.Date:
PrintDate(text, dt);
break;
case XmlTypeCode.GYearMonth:
PrintYear(text, dt.Year);
ShortToCharArray(text, 5, dt.Month);
break;
case XmlTypeCode.GYear:
PrintYear(text, dt.Year);
break;
case XmlTypeCode.GMonthDay:
ShortToCharArray(text, 5, dt.Month);
ShortToCharArray(text, 8, dt.Day);
break;
case XmlTypeCode.GDay:
ShortToCharArray(text, 8, dt.Day);
break;
case XmlTypeCode.GMonth:
ShortToCharArray(text, 5, dt.Month);
break;
}
return new string(text);
}
public static string MSLocalName(string name)
{
int colonOffset;
int len = ValidateNames.ParseQName(name, 0, out colonOffset);
if (len != name.Length)
{
return string.Empty;
}
if (colonOffset == 0)
{
return name;
}
else
{
return name.Substring(colonOffset + 1);
}
}
public static string MSNamespaceUri(string name, XPathNavigator currentNode)
{
int colonOffset;
int len = ValidateNames.ParseQName(name, 0, out colonOffset);
if (len != name.Length)
{
return string.Empty;
}
string prefix = name.Substring(0, colonOffset);
if (prefix == "xmlns")
{
return string.Empty;
}
string ns = currentNode.LookupNamespace(prefix);
if (ns != null)
{
return ns;
}
if (prefix == "xml")
{
return XmlReservedNs.NsXml;
}
return string.Empty;
}
//------------------------------------------------
// Helper Functions
//------------------------------------------------
private static CultureInfo GetCultureInfo(string lang)
{
Debug.Assert(lang != null);
if (lang.Length == 0)
{
return CultureInfo.CurrentCulture;
}
else
{
try
{
return new CultureInfo(lang);
}
catch (System.ArgumentException)
{
throw new XslTransformException(SR.Xslt_InvalidLanguage, lang);
}
}
}
private static void PrintDate(char[] text, DateTime dt)
{
PrintYear(text, dt.Year);
ShortToCharArray(text, 5, dt.Month);
ShortToCharArray(text, 8, dt.Day);
}
private static void PrintTime(char[] text, DateTime dt)
{
ShortToCharArray(text, 11, dt.Hour);
ShortToCharArray(text, 14, dt.Minute);
ShortToCharArray(text, 17, dt.Second);
PrintMsec(text, dt.Millisecond);
}
private static void PrintYear(char[] text, int value)
{
text[0] = (char)((value / 1000) % 10 + '0');
text[1] = (char)((value / 100) % 10 + '0');
text[2] = (char)((value / 10) % 10 + '0');
text[3] = (char)((value / 1) % 10 + '0');
}
private static void PrintMsec(char[] text, int value)
{
if (value == 0)
{
return;
}
text[20] = (char)((value / 100) % 10 + '0');
text[21] = (char)((value / 10) % 10 + '0');
text[22] = (char)((value / 1) % 10 + '0');
}
private static void ShortToCharArray(char[] text, int start, int value)
{
text[start] = (char)(value / 10 + '0');
text[start + 1] = (char)(value % 10 + '0');
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Numerics.Tests
{
public class ComparisonTest
{
private const int NumberOfRandomIterations = 1;
[Fact]
public static void ComparisonTests()
{
int seed = 100;
RunTests(seed);
}
public static void RunTests(int seed)
{
Random random = new Random(seed);
RunPositiveTests(random);
RunNegativeTests(random);
}
private static void RunPositiveTests(Random random)
{
BigInteger bigInteger1, bigInteger2;
int expectedResult;
byte[] byteArray;
bool isNegative;
//1 Inputs from BigInteger Properties
// BigInteger.MinusOne, BigInteger.MinusOne
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne, 0);
// BigInteger.MinusOne, BigInteger.Zero
VerifyComparison(BigInteger.MinusOne, BigInteger.Zero, -1);
// BigInteger.MinusOne, BigInteger.One
VerifyComparison(BigInteger.MinusOne, BigInteger.One, -1);
// BigInteger.MinusOne, Large Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)Int64.MaxValue), 1);
// BigInteger.MinusOne, Small Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)Int16.MaxValue), 1);
// BigInteger.MinusOne, Large Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.MinusOne, Small Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)Int32.MaxValue - 1, -1);
// BigInteger.MinusOne, One Less
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne - 1, 1);
// BigInteger.Zero, BigInteger.Zero
VerifyComparison(BigInteger.Zero, BigInteger.Zero, 0);
// BigInteger.Zero, Large Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)Int32.MaxValue + 1), 1);
// BigInteger.Zero, Small Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)Int32.MaxValue - 1), 1);
// BigInteger.Zero, Large Number
VerifyComparison(BigInteger.Zero, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.Zero, Small Number
VerifyComparison(BigInteger.Zero, (BigInteger)Int32.MaxValue - 1, -1);
// BigInteger.One, BigInteger.One
VerifyComparison(BigInteger.One, BigInteger.One, 0);
// BigInteger.One, BigInteger.MinusOne
VerifyComparison(BigInteger.One, BigInteger.MinusOne, 1);
// BigInteger.One, BigInteger.Zero
VerifyComparison(BigInteger.One, BigInteger.Zero, 1);
// BigInteger.One, Large Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)Int32.MaxValue + 1), 1);
// BigInteger.One, Small Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)Int32.MaxValue - 1), 1);
// BigInteger.One, Large Number
VerifyComparison(BigInteger.One, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.One, Small Number
VerifyComparison(BigInteger.One, (BigInteger)Int32.MaxValue - 1, -1);
//Basic Checks
// BigInteger.MinusOne, (Int32) -1
VerifyComparison(BigInteger.MinusOne, (Int32)(-1), 0);
// BigInteger.Zero, (Int32) 0
VerifyComparison(BigInteger.Zero, (Int32)(0), 0);
// BigInteger.One, 1
VerifyComparison(BigInteger.One, (Int32)(1), 0);
//1 Inputs Around the boundary of UInt32
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison(-1L * (BigInteger)UInt32.MaxValue - 1, -1L * (BigInteger)UInt32.MaxValue - 1, 0);
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue -1
VerifyComparison(-1L * (BigInteger)UInt32.MaxValue, (-1L * (BigInteger)UInt32.MaxValue) - 1L, 1);
// UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, -1L * (BigInteger)UInt32.MaxValue, 1);
// UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, (BigInteger)UInt32.MaxValue, 0);
// UInt32.MaxValue, UInt32.MaxValue + 1
VerifyComparison((BigInteger)UInt32.MaxValue, (BigInteger)UInt32.MaxValue + 1, -1);
// UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue, (BigInteger)UInt64.MaxValue, 0);
// UInt64.MaxValue + 1, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, UInt64.MaxValue, 1);
//Other cases
// -1 * Large Bigint, -1 * Large BigInt
VerifyComparison(-1L * ((BigInteger)Int32.MaxValue + 1), -1L * ((BigInteger)Int32.MaxValue + 1), 0);
// Large Bigint, Large Negative BigInt
VerifyComparison((BigInteger)Int32.MaxValue + 1, -1L * ((BigInteger)Int32.MaxValue + 1), 1);
// Large Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, (BigInteger)UInt32.MaxValue, 1);
// Large Bigint, One More
VerifyComparison((BigInteger)Int32.MaxValue + 1, ((BigInteger)Int32.MaxValue) + 2, -1);
// -1 * Small Bigint, -1 * Small BigInt
VerifyComparison(-1L * ((BigInteger)Int32.MaxValue - 1), -1L * ((BigInteger)Int32.MaxValue - 1), 0);
// Small Bigint, Small Negative BigInt
VerifyComparison((BigInteger)Int32.MaxValue - 1, -1L * ((BigInteger)Int32.MaxValue - 1), 1);
// Small Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue - 1, (BigInteger)UInt32.MaxValue - 1, -1);
// Small Bigint, One More
VerifyComparison((BigInteger)Int32.MaxValue - 2, ((BigInteger)Int32.MaxValue) - 1, -1);
//BigInteger vs. Int32
// One Larger (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue + 1, Int32.MaxValue, 1);
// Larger BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, Int32.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, Int32.MaxValue, -1);
// One Smaller (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue - 1, Int32.MaxValue, -1);
// (BigInteger) Int32.MaxValue, Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue, Int32.MaxValue, 0);
//BigInteger vs. UInt32
// One Larger (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue + 1, UInt32.MaxValue, 1);
// Larger BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, UInt32.MaxValue, 1);
// Smaller BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, UInt32.MaxValue, -1);
// One Smaller (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue - 1, UInt32.MaxValue, -1);
// (BigInteger UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, UInt32.MaxValue, 0);
//BigInteger vs. UInt64
// One Larger (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, UInt64.MaxValue, 1);
// Larger BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 100, UInt64.MaxValue, 1);
// Smaller BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, UInt64.MaxValue, -1);
VerifyComparison((BigInteger)Int16.MaxValue - 1, UInt64.MaxValue, -1);
VerifyComparison((BigInteger)Int32.MaxValue + 1, UInt64.MaxValue, -1);
// One Smaller (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue - 1, UInt64.MaxValue, -1);
// (BigInteger UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue, UInt64.MaxValue, 0);
//BigInteger vs. Int64
// One Smaller (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue - 1, Int64.MaxValue, -1);
// Larger BigInteger, Int64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 100, Int64.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, Int64.MaxValue, -1);
// (BigInteger Int64.MaxValue, Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue, Int64.MaxValue, 0);
// One Larger (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, Int64.MaxValue, 1);
//1 Random Inputs
// Random BigInteger only differs by sign
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b2 = new BigInteger(byteArray);
if (b2 > (BigInteger)0)
{
VerifyComparison(b2, -1L * b2, 1);
}
else
{
VerifyComparison(b2, -1L * b2, -1);
}
}
// Random BigInteger, Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
expectedResult = GetRandomInputForComparison(random, out bigInteger1, out bigInteger2);
VerifyComparison(bigInteger1, bigInteger2, expectedResult);
}
// Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(new BigInteger(byteArray), isNegative, new BigInteger(byteArray), isNegative, 0);
}
//1 Identical values constructed multiple ways
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=true
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), true, 0);
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=false
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.Zero, BigInteger constructed from an Int64
VerifyComparison(BigInteger.Zero, 0L, 0);
// BigInteger.Zero, BigInteger constructed from a Double
VerifyComparison(BigInteger.Zero, (BigInteger)0d, 0);
// BigInteger.Zero, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.Zero, (BigInteger)0, 0);
// BigInteger.Zero, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) + (-1 * new BigInteger(byteArray)), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) - new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 * new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 / new BigInteger(byteArray), isNegative, 0);
// BigInteger.One, BigInteger constructed with a byte[]
VerifyComparison(BigInteger.One, false, new BigInteger(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.One, BigInteger constructed from an Int64
VerifyComparison(BigInteger.One, 1L, 0);
// BigInteger.One, BigInteger constructed from a Double
VerifyComparison(BigInteger.One, (BigInteger)1d, 0);
// BigInteger.One, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.One, (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, false, (((BigInteger)(-1)) * new BigInteger(byteArray)) + (new BigInteger(byteArray)) + 1, false, 0);
// BigInteger.One, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
BigInteger b = new BigInteger(byteArray);
if (b > (BigInteger)0)
{
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
}
else
{
b = -1L * b;
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
b = -1L * b;
}
// BigInteger.One, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, (BigInteger)1 * (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b1 = new BigInteger(byteArray);
VerifyComparison(BigInteger.One, false, b1 / b1, false, 0);
}
private static void RunNegativeTests(Random random)
{
// BigInteger.Zero, 0
Assert.Equal(false, BigInteger.Zero.Equals((Object)0));
// BigInteger.Zero, null
Assert.Equal(false, BigInteger.Zero.Equals((Object)null));
// BigInteger.Zero, string
Assert.Equal(false, BigInteger.Zero.Equals((Object)"0"));
}
public static void IComparable_Invalid(string paramName)
{
IComparable comparable = new BigInteger();
Assert.Equal(1, comparable.CompareTo(null));
AssertExtensions.Throws<ArgumentException>(paramName, () => comparable.CompareTo(0)); // Obj is not a BigInteger
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] // Desktop misses Exception.ParamName fixed in .NETCore
public static void IComparable_Invalid_net46()
{
IComparable_Invalid(null);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void IComparable_Invalid_netcore()
{
IComparable_Invalid("obj");
}
private static void VerifyComparison(BigInteger x, BigInteger y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((Object)y));
Assert.Equal(expectedEquals, y.Equals((Object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
IComparable comparableX = x;
IComparable comparableY = y;
VerifyCompareResult(expectedResult, comparableX.CompareTo(y), "comparableX.CompareTo(y)");
VerifyCompareResult(-expectedResult, comparableY.CompareTo(x), "comparableY.CompareTo(x)");
VerifyCompareResult(expectedResult, BigInteger.Compare(x, y), "Compare(x,y)");
VerifyCompareResult(-expectedResult, BigInteger.Compare(y, x), "Compare(y,x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, Int32 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, UInt32 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, Int64 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, UInt64 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.NotEqual(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, bool IsXNegative, BigInteger y, bool IsYNegative, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
if (IsXNegative == true)
{
x = x * -1;
}
if (IsYNegative == true)
{
y = y * -1;
}
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((Object)y));
Assert.Equal(expectedEquals, y.Equals((Object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
Assert.NotEqual(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyCompareResult(int expected, int actual, string message)
{
if (0 == expected)
{
Assert.Equal(expected, actual);
}
else if (0 > expected)
{
Assert.InRange(actual, int.MinValue, -1);
}
else if (0 < expected)
{
Assert.InRange(actual, 1, int.MaxValue);
}
}
private static int GetRandomInputForComparison(Random random, out BigInteger bigInteger1, out BigInteger bigInteger2)
{
byte[] byteArray1, byteArray2;
bool sameSize = 0 == random.Next(0, 2);
if (sameSize)
{
int size = random.Next(0, 1024);
byteArray1 = GetRandomByteArray(random, size);
byteArray2 = GetRandomByteArray(random, size);
}
else
{
byteArray1 = GetRandomByteArray(random);
byteArray2 = GetRandomByteArray(random);
}
bigInteger1 = new BigInteger(byteArray1);
bigInteger2 = new BigInteger(byteArray2);
if (bigInteger1 > 0 && bigInteger2 > 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0 != byteArray2[i])
{
return -1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0 != byteArray1[i])
{
return 1;
}
}
}
}
else if ((bigInteger1 < 0 && bigInteger2 > 0) || (bigInteger1 == 0 && bigInteger2 > 0) || (bigInteger1 < 0 && bigInteger2 == 0))
{
return -1;
}
else if ((bigInteger1 > 0 && bigInteger2 < 0) || (bigInteger1 == 0 && bigInteger2 < 0) || (bigInteger1 > 0 && bigInteger2 == 0))
{
return 1;
}
else if (bigInteger1 != 0 && bigInteger2 != 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0xFF != byteArray2[i])
{
return 1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0xFF != byteArray1[i])
{
return -1;
}
}
}
}
for (int i = Math.Min(byteArray1.Length, byteArray2.Length) - 1; 0 <= i; --i)
{
if (byteArray1[i] > byteArray2[i])
{
return 1;
}
else if (byteArray1[i] < byteArray2[i])
{
return -1;
}
}
return 0;
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Security;
using System.Text;
namespace Alphaleonis.Win32.Filesystem
{
public static partial class Path
{
/// <summary>Returns the absolute path for the specified path string.</summary>
/// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns>
/// <remarks>
/// <para>GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file.</para>
/// <para>It also calculates the address of the file name portion of the full path and file name.</para>
/// <para> </para>
/// <para>This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.</para>
/// <para>The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0".</para>
/// <para> </para>
/// <para>MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and</para>
/// <para>should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,</para>
/// <para>therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.</para>
/// <para>This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread,</para>
/// <para>for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
/// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
/// </remarks>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="path">The file or directory for which to obtain absolute path information.</param>
[SecurityCritical]
public static string GetFullPath(string path)
{
return GetFullPathTackleCore(null, path);
}
/// <summary>[AlphaFS] Returns the absolute path for the specified path string.</summary>
/// <returns>The fully qualified location of path, such as "C:\MyFile.txt".</returns>
/// <remarks>
/// <para>GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file.</para>
/// <para>It also calculates the address of the file name portion of the full path and file name.</para>
/// <para> </para>
/// <para>This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.</para>
/// <para>The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0".</para>
/// <para> </para>
/// <para>MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and</para>
/// <para>should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,</para>
/// <para>therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.</para>
/// <para>This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread,</para>
/// <para>for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
/// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
/// </remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="NotSupportedException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The file or directory for which to obtain absolute path information.</param>
[SecurityCritical]
public static string GetFullPathTransacted(KernelTransaction transaction, string path)
{
return GetFullPathTackleCore(transaction, path);
}
#region Internal Methods
/// <summary>Retrieves the absolute path for the specified <paramref name="path"/> string.</summary>
/// <returns>The fully qualified location of <paramref name="path"/>, such as "C:\MyFile.txt".</returns>
/// <remarks>
/// <para>GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file.</para>
/// <para>It also calculates the address of the file name portion of the full path and file name.</para>
/// <para> </para>
/// <para>This method does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.</para>
/// <para>The .NET Framework does not support direct access to physical disks through paths that are device names, such as "\\.\PHYSICALDRIVE0".</para>
/// <para> </para>
/// <para>MSDN: Multithreaded applications and shared library code should not use the GetFullPathName function and</para>
/// <para>should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process,</para>
/// <para>therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value.</para>
/// <para>This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread,</para>
/// <para>for example parsing file names from the command line argument string in the main thread prior to creating any additional threads.</para>
/// <para>Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.</para>
/// </remarks>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The file or directory for which to obtain absolute path information.</param>
/// <param name="options">Options for controlling the operation.</param>
[SecurityCritical]
internal static string GetFullPathCore(KernelTransaction transaction, string path, GetFullPathOptions options)
{
if (path != null)
if (path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase))
return path;
if (options != GetFullPathOptions.None)
{
if ((options & GetFullPathOptions.CheckInvalidPathChars) != 0)
{
bool checkAdditional = (options & GetFullPathOptions.CheckAdditional) != 0;
CheckInvalidPathChars(path, checkAdditional);
// Prevent duplicate checks.
options &= ~GetFullPathOptions.CheckInvalidPathChars;
if (checkAdditional)
options &= ~GetFullPathOptions.CheckAdditional;
}
// Do not remove trailing directory separator when path points to a drive like: "C:\"
// Doing so makes path point to the current directory.
if (path == null || path.Length <= 3 || (!path.StartsWith(LongPathPrefix, StringComparison.OrdinalIgnoreCase) && path[1] != VolumeSeparatorChar))
options &= ~GetFullPathOptions.RemoveTrailingDirectorySeparator;
}
string pathLp = GetLongPathCore(path, options);
uint bufferSize = NativeMethods.MaxPathUnicode;
// ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
{
startGetFullPathName:
var buffer = new StringBuilder((int)bufferSize);
uint returnLength = (transaction == null || !NativeMethods.IsAtLeastWindowsVista
// GetFullPathName() / GetFullPathNameTransacted()
// In the ANSI version of this function, the name is limited to MAX_PATH characters.
// To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
// 2013-04-15: MSDN confirms LongPath usage.
? NativeMethods.GetFullPathName(pathLp, bufferSize, buffer, IntPtr.Zero)
: NativeMethods.GetFullPathNameTransacted(pathLp, bufferSize, buffer, IntPtr.Zero, transaction.SafeHandle));
if (returnLength != Win32Errors.NO_ERROR)
{
if (returnLength > bufferSize)
{
bufferSize = returnLength;
goto startGetFullPathName;
}
}
else
{
if ((options & GetFullPathOptions.ContinueOnNonExist) != 0)
return null;
NativeError.ThrowException(pathLp);
}
return (options & GetFullPathOptions.AsLongPath) != 0
? GetLongPathCore(buffer.ToString(), GetFullPathOptions.None)
: GetRegularPathCore(buffer.ToString(), GetFullPathOptions.None);
}
}
private static string GetFullPathTackleCore(KernelTransaction transaction, string path)
{
if (path != null)
{
if (path.StartsWith(GlobalRootPrefix, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(VolumePrefix, StringComparison.OrdinalIgnoreCase))
return path;
CheckInvalidUncPath(path);
}
CheckSupportedPathFormat(path, true, true);
return GetFullPathCore(transaction, path, GetFullPathOptions.None);
}
/// <summary>Applies the <seealso cref="GetFullPathOptions"/> to <paramref name="path"/></summary>
/// <returns><paramref name="path"/> with applied <paramref name="options"/>.</returns>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="ArgumentException"/>
/// <param name="path"></param>
/// <param name="options"></param>
private static string ApplyFullPathOptions(string path, GetFullPathOptions options)
{
if ((options & GetFullPathOptions.TrimEnd) != 0)
path = path.TrimEnd();
if ((options & GetFullPathOptions.AddTrailingDirectorySeparator) != 0)
path = AddTrailingDirectorySeparator(path, false);
if ((options & GetFullPathOptions.RemoveTrailingDirectorySeparator) != 0)
path = RemoveTrailingDirectorySeparator(path, false);
if ((options & GetFullPathOptions.CheckInvalidPathChars) != 0)
CheckInvalidPathChars(path, (options & GetFullPathOptions.CheckAdditional) != 0);
// Trim leading whitespace.
return path.TrimStart();
}
#endregion // Internal Methods
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// Represents a host crash dump
/// First published in XenServer 4.0.
/// </summary>
public partial class Host_crashdump : XenObject<Host_crashdump>
{
public Host_crashdump()
{
}
public Host_crashdump(string uuid,
XenRef<Host> host,
DateTime timestamp,
long size,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.host = host;
this.timestamp = timestamp;
this.size = size;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Host_crashdump from a Proxy_Host_crashdump.
/// </summary>
/// <param name="proxy"></param>
public Host_crashdump(Proxy_Host_crashdump proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Host_crashdump update)
{
uuid = update.uuid;
host = update.host;
timestamp = update.timestamp;
size = update.size;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Host_crashdump proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host);
timestamp = proxy.timestamp;
size = proxy.size == null ? 0 : long.Parse((string)proxy.size);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Host_crashdump ToProxy()
{
Proxy_Host_crashdump result_ = new Proxy_Host_crashdump();
result_.uuid = uuid ?? "";
result_.host = host ?? "";
result_.timestamp = timestamp;
result_.size = size.ToString();
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Host_crashdump from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Host_crashdump(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
host = Marshalling.ParseRef<Host>(table, "host");
timestamp = Marshalling.ParseDateTime(table, "timestamp");
size = Marshalling.ParseLong(table, "size");
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Host_crashdump other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._host, other._host) &&
Helper.AreEqual2(this._timestamp, other._timestamp) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Host_crashdump server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Host_crashdump.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static Host_crashdump get_record(Session session, string _host_crashdump)
{
return new Host_crashdump((Proxy_Host_crashdump)session.proxy.host_crashdump_get_record(session.uuid, _host_crashdump ?? "").parse());
}
/// <summary>
/// Get a reference to the host_crashdump instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Host_crashdump> get_by_uuid(Session session, string _uuid)
{
return XenRef<Host_crashdump>.Create(session.proxy.host_crashdump_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static string get_uuid(Session session, string _host_crashdump)
{
return (string)session.proxy.host_crashdump_get_uuid(session.uuid, _host_crashdump ?? "").parse();
}
/// <summary>
/// Get the host field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static XenRef<Host> get_host(Session session, string _host_crashdump)
{
return XenRef<Host>.Create(session.proxy.host_crashdump_get_host(session.uuid, _host_crashdump ?? "").parse());
}
/// <summary>
/// Get the timestamp field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static DateTime get_timestamp(Session session, string _host_crashdump)
{
return session.proxy.host_crashdump_get_timestamp(session.uuid, _host_crashdump ?? "").parse();
}
/// <summary>
/// Get the size field of the given host_crashdump.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static long get_size(Session session, string _host_crashdump)
{
return long.Parse((string)session.proxy.host_crashdump_get_size(session.uuid, _host_crashdump ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given host_crashdump.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static Dictionary<string, string> get_other_config(Session session, string _host_crashdump)
{
return Maps.convert_from_proxy_string_string(session.proxy.host_crashdump_get_other_config(session.uuid, _host_crashdump ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given host_crashdump.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _host_crashdump, Dictionary<string, string> _other_config)
{
session.proxy.host_crashdump_set_other_config(session.uuid, _host_crashdump ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given host_crashdump.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _host_crashdump, string _key, string _value)
{
session.proxy.host_crashdump_add_to_other_config(session.uuid, _host_crashdump ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given host_crashdump. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _host_crashdump, string _key)
{
session.proxy.host_crashdump_remove_from_other_config(session.uuid, _host_crashdump ?? "", _key ?? "").parse();
}
/// <summary>
/// Destroy specified host crash dump, removing it from the disk.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static void destroy(Session session, string _host_crashdump)
{
session.proxy.host_crashdump_destroy(session.uuid, _host_crashdump ?? "").parse();
}
/// <summary>
/// Destroy specified host crash dump, removing it from the disk.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
public static XenRef<Task> async_destroy(Session session, string _host_crashdump)
{
return XenRef<Task>.Create(session.proxy.async_host_crashdump_destroy(session.uuid, _host_crashdump ?? "").parse());
}
/// <summary>
/// Upload the specified host crash dump to a specified URL
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_url">The URL to upload to</param>
/// <param name="_options">Extra configuration operations</param>
public static void upload(Session session, string _host_crashdump, string _url, Dictionary<string, string> _options)
{
session.proxy.host_crashdump_upload(session.uuid, _host_crashdump ?? "", _url ?? "", Maps.convert_to_proxy_string_string(_options)).parse();
}
/// <summary>
/// Upload the specified host crash dump to a specified URL
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host_crashdump">The opaque_ref of the given host_crashdump</param>
/// <param name="_url">The URL to upload to</param>
/// <param name="_options">Extra configuration operations</param>
public static XenRef<Task> async_upload(Session session, string _host_crashdump, string _url, Dictionary<string, string> _options)
{
return XenRef<Task>.Create(session.proxy.async_host_crashdump_upload(session.uuid, _host_crashdump ?? "", _url ?? "", Maps.convert_to_proxy_string_string(_options)).parse());
}
/// <summary>
/// Return a list of all the host_crashdumps known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Host_crashdump>> get_all(Session session)
{
return XenRef<Host_crashdump>.Create(session.proxy.host_crashdump_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the host_crashdump Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Host_crashdump>, Host_crashdump> get_all_records(Session session)
{
return XenRef<Host_crashdump>.Create<Proxy_Host_crashdump>(session.proxy.host_crashdump_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Host the crashdump relates to
/// </summary>
public virtual XenRef<Host> host
{
get { return _host; }
set
{
if (!Helper.AreEqual(value, _host))
{
_host = value;
Changed = true;
NotifyPropertyChanged("host");
}
}
}
private XenRef<Host> _host;
/// <summary>
/// Time the crash happened
/// </summary>
public virtual DateTime timestamp
{
get { return _timestamp; }
set
{
if (!Helper.AreEqual(value, _timestamp))
{
_timestamp = value;
Changed = true;
NotifyPropertyChanged("timestamp");
}
}
}
private DateTime _timestamp;
/// <summary>
/// Size of the crashdump
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
Changed = true;
NotifyPropertyChanged("size");
}
}
}
private long _size;
/// <summary>
/// additional configuration
/// First published in XenServer 4.1.
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER
// REMAINS UNCHANGED.
//
// Email: [email protected]
//
// Copyright (C) 2002-2003 Idael Cardoso.
//
// LAME ( LAME Ain't an Mp3 Encoder )
// You must call the fucntion "beVersion" to obtain information like version
// numbers (both of the DLL and encoding engine), release date and URL for
// lame_enc's homepage. All this information should be made available to the
// user of your product through a dialog box or something similar.
// You must see all information about LAME project and legal license infos at
// http://www.mp3dev.org/ The official LAME site
//
// About Thomson and/or Fraunhofer patents:
// Any use of this product does not convey a license under the relevant
// intellectual property of Thomson and/or Fraunhofer Gesellschaft nor imply
// any right to use this product in any finished end user or ready-to-use final
// product. An independent license for such use is required.
// For details, please visit http://www.mp3licensing.com.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using Yeti.MMedia;
using Yeti.MMedia.Mp3;
using WaveLib;
namespace Yeti.MMedia.Mp3
{
/// <summary>
/// Summary description for EditMp3Writer.
/// </summary>
public class EditMp3Writer : System.Windows.Forms.UserControl, IEditAudioWriterConfig
{
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private Yeti.MMedia.EditFormat editFormat1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBoxMpegVersion;
private System.Windows.Forms.ComboBox comboBoxBitRate;
private System.Windows.Forms.CheckBox checkBoxVBR;
private System.Windows.Forms.ComboBox comboBoxMaxBitRate;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox comboBoxVBRMethod;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox comboBoxAvgBitrate;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.CheckBox checkBoxCopyRight;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.CheckBox checkBoxCRC;
private System.Windows.Forms.CheckBox checkBoxOriginal;
private System.Windows.Forms.CheckBox checkBoxPrivate;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TrackBar trackBarVBRQuality;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.GroupBox groupBoxVBR;
private System.ComponentModel.IContainer components;
private Lame.BE_CONFIG m_Config = null;
private const string Mpeg1BitRates = "32,40,48,56,64,80,96,112,128,160,192,224,256,320";
private const string Mpeg2BitRates = "8,16,24,32,40,48,56,64,80,96,112,128,144,160";
public EditMp3Writer()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
m_Config = new Yeti.Lame.BE_CONFIG(editFormat1.Format);
DoSetInitialValues();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private bool m_FireConfigChangeEvent = true;
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.editFormat1 = new Yeti.MMedia.EditFormat();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.checkBoxPrivate = new System.Windows.Forms.CheckBox();
this.checkBoxOriginal = new System.Windows.Forms.CheckBox();
this.checkBoxCRC = new System.Windows.Forms.CheckBox();
this.checkBoxCopyRight = new System.Windows.Forms.CheckBox();
this.checkBoxVBR = new System.Windows.Forms.CheckBox();
this.groupBoxVBR = new System.Windows.Forms.GroupBox();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.comboBoxVBRMethod = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.trackBarVBRQuality = new System.Windows.Forms.TrackBar();
this.label6 = new System.Windows.Forms.Label();
this.comboBoxAvgBitrate = new System.Windows.Forms.ComboBox();
this.label5 = new System.Windows.Forms.Label();
this.comboBoxMaxBitRate = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.comboBoxBitRate = new System.Windows.Forms.ComboBox();
this.textBoxMpegVersion = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.groupBoxVBR.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.trackBarVBRQuality)).BeginInit();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 0);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(336, 280);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.editFormat1);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(328, 254);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Input format";
//
// editFormat1
//
this.editFormat1.Dock = System.Windows.Forms.DockStyle.Fill;
this.editFormat1.Location = new System.Drawing.Point(0, 0);
this.editFormat1.Name = "editFormat1";
this.editFormat1.ReadOnly = true;
this.editFormat1.Size = new System.Drawing.Size(328, 254);
this.editFormat1.TabIndex = 0;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.checkBoxPrivate);
this.tabPage2.Controls.Add(this.checkBoxOriginal);
this.tabPage2.Controls.Add(this.checkBoxCRC);
this.tabPage2.Controls.Add(this.checkBoxCopyRight);
this.tabPage2.Controls.Add(this.checkBoxVBR);
this.tabPage2.Controls.Add(this.groupBoxVBR);
this.tabPage2.Controls.Add(this.comboBoxBitRate);
this.tabPage2.Controls.Add(this.textBoxMpegVersion);
this.tabPage2.Controls.Add(this.label2);
this.tabPage2.Controls.Add(this.label1);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(328, 254);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "MP3 config";
//
// checkBoxPrivate
//
this.checkBoxPrivate.Location = new System.Drawing.Point(248, 48);
this.checkBoxPrivate.Name = "checkBoxPrivate";
this.checkBoxPrivate.Size = new System.Drawing.Size(72, 24);
this.checkBoxPrivate.TabIndex = 9;
this.checkBoxPrivate.Text = "Private";
this.toolTip1.SetToolTip(this.checkBoxPrivate, "Controls the private bit of MP3 stream");
this.checkBoxPrivate.CheckedChanged += new System.EventHandler(this.Control_Changed);
//
// checkBoxOriginal
//
this.checkBoxOriginal.Location = new System.Drawing.Point(168, 48);
this.checkBoxOriginal.Name = "checkBoxOriginal";
this.checkBoxOriginal.Size = new System.Drawing.Size(72, 24);
this.checkBoxOriginal.TabIndex = 8;
this.checkBoxOriginal.Text = "Original";
this.toolTip1.SetToolTip(this.checkBoxOriginal, "Controls the original bit of MP3 stream");
this.checkBoxOriginal.CheckedChanged += new System.EventHandler(this.Control_Changed);
//
// checkBoxCRC
//
this.checkBoxCRC.Location = new System.Drawing.Point(88, 48);
this.checkBoxCRC.Name = "checkBoxCRC";
this.checkBoxCRC.Size = new System.Drawing.Size(72, 24);
this.checkBoxCRC.TabIndex = 7;
this.checkBoxCRC.Text = "CRC";
this.toolTip1.SetToolTip(this.checkBoxCRC, "If set enables CRC-checksum in the bitstream");
this.checkBoxCRC.CheckedChanged += new System.EventHandler(this.Control_Changed);
//
// checkBoxCopyRight
//
this.checkBoxCopyRight.Location = new System.Drawing.Point(8, 48);
this.checkBoxCopyRight.Name = "checkBoxCopyRight";
this.checkBoxCopyRight.Size = new System.Drawing.Size(72, 24);
this.checkBoxCopyRight.TabIndex = 6;
this.checkBoxCopyRight.Text = "Copyright";
this.toolTip1.SetToolTip(this.checkBoxCopyRight, "Controls the copyrightb bit of MP3 stream");
this.checkBoxCopyRight.CheckedChanged += new System.EventHandler(this.Control_Changed);
//
// checkBoxVBR
//
this.checkBoxVBR.Location = new System.Drawing.Point(8, 72);
this.checkBoxVBR.Name = "checkBoxVBR";
this.checkBoxVBR.Size = new System.Drawing.Size(192, 24);
this.checkBoxVBR.TabIndex = 5;
this.checkBoxVBR.Text = "Enable Variable Bit Rate (VBR)";
this.checkBoxVBR.CheckedChanged += new System.EventHandler(this.checkBoxVBR_CheckedChanged);
//
// groupBoxVBR
//
this.groupBoxVBR.Controls.Add(this.label8);
this.groupBoxVBR.Controls.Add(this.label7);
this.groupBoxVBR.Controls.Add(this.comboBoxVBRMethod);
this.groupBoxVBR.Controls.Add(this.label4);
this.groupBoxVBR.Controls.Add(this.trackBarVBRQuality);
this.groupBoxVBR.Controls.Add(this.label6);
this.groupBoxVBR.Controls.Add(this.comboBoxAvgBitrate);
this.groupBoxVBR.Controls.Add(this.label5);
this.groupBoxVBR.Controls.Add(this.comboBoxMaxBitRate);
this.groupBoxVBR.Controls.Add(this.label3);
this.groupBoxVBR.Location = new System.Drawing.Point(8, 96);
this.groupBoxVBR.Name = "groupBoxVBR";
this.groupBoxVBR.Size = new System.Drawing.Size(304, 144);
this.groupBoxVBR.TabIndex = 4;
this.groupBoxVBR.TabStop = false;
this.groupBoxVBR.Text = "VBR options";
//
// label8
//
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label8.Location = new System.Drawing.Point(256, 64);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(32, 16);
this.label8.TabIndex = 13;
this.label8.Text = "Min";
//
// label7
//
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label7.Location = new System.Drawing.Point(152, 64);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(56, 16);
this.label7.TabIndex = 12;
this.label7.Text = "Max.";
//
// comboBoxVBRMethod
//
this.comboBoxVBRMethod.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxVBRMethod.Items.AddRange(new object[] {
"NONE",
"DEFAULT",
"OLD",
"NEW",
"MTRH",
"ABR"});
this.comboBoxVBRMethod.Location = new System.Drawing.Point(8, 32);
this.comboBoxVBRMethod.Name = "comboBoxVBRMethod";
this.comboBoxVBRMethod.Size = new System.Drawing.Size(121, 21);
this.comboBoxVBRMethod.TabIndex = 7;
this.comboBoxVBRMethod.SelectedIndexChanged += new System.EventHandler(this.comboBoxVBRMethod_SelectedIndexChanged);
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 16);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(96, 24);
this.label4.TabIndex = 6;
this.label4.Text = "VBR method:";
//
// trackBarVBRQuality
//
this.trackBarVBRQuality.LargeChange = 0;
this.trackBarVBRQuality.Location = new System.Drawing.Point(144, 32);
this.trackBarVBRQuality.Maximum = 9;
this.trackBarVBRQuality.Name = "trackBarVBRQuality";
this.trackBarVBRQuality.Size = new System.Drawing.Size(144, 42);
this.trackBarVBRQuality.TabIndex = 11;
this.trackBarVBRQuality.Scroll += new System.EventHandler(this.Control_Changed);
//
// label6
//
this.label6.Location = new System.Drawing.Point(152, 16);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(100, 16);
this.label6.TabIndex = 10;
this.label6.Text = "VBR quality:";
//
// comboBoxAvgBitrate
//
this.comboBoxAvgBitrate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxAvgBitrate.Location = new System.Drawing.Point(8, 112);
this.comboBoxAvgBitrate.Name = "comboBoxAvgBitrate";
this.comboBoxAvgBitrate.Size = new System.Drawing.Size(121, 21);
this.comboBoxAvgBitrate.TabIndex = 9;
this.comboBoxAvgBitrate.SelectedIndexChanged += new System.EventHandler(this.Control_Changed);
//
// label5
//
this.label5.Location = new System.Drawing.Point(8, 96);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(88, 16);
this.label5.TabIndex = 8;
this.label5.Text = "Average bit rate:";
//
// comboBoxMaxBitRate
//
this.comboBoxMaxBitRate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxMaxBitRate.Location = new System.Drawing.Point(8, 72);
this.comboBoxMaxBitRate.Name = "comboBoxMaxBitRate";
this.comboBoxMaxBitRate.Size = new System.Drawing.Size(121, 21);
this.comboBoxMaxBitRate.TabIndex = 5;
this.comboBoxMaxBitRate.SelectedIndexChanged += new System.EventHandler(this.BitRateChange);
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 56);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(104, 16);
this.label3.TabIndex = 4;
this.label3.Text = "Max bit rate:";
//
// comboBoxBitRate
//
this.comboBoxBitRate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxBitRate.Location = new System.Drawing.Point(168, 24);
this.comboBoxBitRate.Name = "comboBoxBitRate";
this.comboBoxBitRate.Size = new System.Drawing.Size(121, 21);
this.comboBoxBitRate.TabIndex = 3;
this.toolTip1.SetToolTip(this.comboBoxBitRate, "Minimum bit rate if VBR is specified ");
this.comboBoxBitRate.SelectedIndexChanged += new System.EventHandler(this.BitRateChange);
//
// textBoxMpegVersion
//
this.textBoxMpegVersion.Location = new System.Drawing.Point(8, 24);
this.textBoxMpegVersion.Name = "textBoxMpegVersion";
this.textBoxMpegVersion.ReadOnly = true;
this.textBoxMpegVersion.Size = new System.Drawing.Size(120, 20);
this.textBoxMpegVersion.TabIndex = 2;
this.textBoxMpegVersion.Text = "";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(96, 16);
this.label2.TabIndex = 1;
this.label2.Text = "MPEG Version:";
//
// label1
//
this.label1.Location = new System.Drawing.Point(168, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 16);
this.label1.TabIndex = 0;
this.label1.Text = "Bit rate:";
//
// EditMp3Writer
//
this.Controls.Add(this.tabControl1);
this.Name = "EditMp3Writer";
this.Size = new System.Drawing.Size(336, 280);
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.groupBoxVBR.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.trackBarVBRQuality)).EndInit();
this.ResumeLayout(false);
}
#endregion
#region IEditAudioWriterConfig Members
public AudioWriterConfig Config
{
get
{
Lame.BE_CONFIG cfg = new Yeti.Lame.BE_CONFIG(editFormat1.Format, uint.Parse(comboBoxBitRate.SelectedItem.ToString()));
cfg.format.lhv1.bCopyright = checkBoxCopyRight.Checked? 1 : 0;
cfg.format.lhv1.bCRC = checkBoxCRC.Checked? 1 : 0;
cfg.format.lhv1.bOriginal = checkBoxOriginal.Checked? 1 : 0;
cfg.format.lhv1.bPrivate = checkBoxPrivate.Checked? 1 : 0;
if ( checkBoxVBR.Checked )
{
cfg.format.lhv1.bEnableVBR = 1;
if ( comboBoxVBRMethod.SelectedIndex > 0 )
{
cfg.format.lhv1.nVbrMethod = (Lame.VBRMETHOD)(comboBoxVBRMethod.SelectedIndex+1);
}
else
{
cfg.format.lhv1.nVbrMethod = Lame.VBRMETHOD.VBR_METHOD_DEFAULT;
}
cfg.format.lhv1.dwMaxBitrate = uint.Parse(comboBoxMaxBitRate.SelectedItem.ToString());
if (cfg.format.lhv1.dwMaxBitrate < cfg.format.lhv1.dwBitrate)
{
cfg.format.lhv1.dwMaxBitrate = cfg.format.lhv1.dwBitrate;
}
cfg.format.lhv1.dwVbrAbr_bps = uint.Parse(comboBoxAvgBitrate.SelectedItem.ToString());
if (cfg.format.lhv1.dwVbrAbr_bps < cfg.format.lhv1.dwBitrate)
{
cfg.format.lhv1.dwVbrAbr_bps = cfg.format.lhv1.dwBitrate;
}
cfg.format.lhv1.nVBRQuality = trackBarVBRQuality.Value;
}
else
{
cfg.format.lhv1.bEnableVBR = 0;
}
return new Mp3WriterConfig(editFormat1.Format, cfg);
}
set
{
editFormat1.Format = value.Format;
m_Config = ((Mp3WriterConfig)value).Mp3Config;
DoSetInitialValues();
}
}
#endregion
#region IConfigControl Members
public void DoApply()
{
// TODO: Add EditMp3Writer.DoApply implementation
}
public string ControlName
{
get
{
return "MP3 Writer config";
}
}
public event System.EventHandler ConfigChange;
public Control ConfigControl
{
get
{
return this;
}
}
public void DoSetInitialValues()
{
m_FireConfigChangeEvent = false;
try
{
int i;
string[] rates;
Lame.LHV1 hv = m_Config.format.lhv1;
editFormat1.DoSetInitialValues();
if (hv.dwMpegVersion == Lame.LHV1.MPEG2)
{
textBoxMpegVersion.Text = "MPEG2";
rates = Mpeg2BitRates.Split(',');
}
else
{
textBoxMpegVersion.Text = "MPEG1";
rates = Mpeg1BitRates.Split(',');
}
comboBoxBitRate.Items.Clear();
comboBoxBitRate.Items.AddRange(rates);
comboBoxMaxBitRate.Items.Clear();
comboBoxMaxBitRate.Items.AddRange(rates);
comboBoxAvgBitrate.Items.Clear();
comboBoxAvgBitrate.Items.AddRange(rates);
i = comboBoxBitRate.Items.IndexOf(hv.dwBitrate.ToString());
comboBoxBitRate.SelectedIndex = i;
comboBoxAvgBitrate.SelectedIndex = i;
comboBoxMaxBitRate.SelectedIndex = i;
checkBoxCopyRight.Checked = hv.bCopyright != 0;
checkBoxCRC.Checked = hv.bCRC != 0;
checkBoxOriginal.Checked = hv.bOriginal != 0;
checkBoxPrivate.Checked = hv.bPrivate != 0;
comboBoxVBRMethod.SelectedIndex = (int)hv.nVbrMethod + 1;
if ( (hv.nVBRQuality >=0) && (hv.nVBRQuality <= 9) )
{
trackBarVBRQuality.Value = hv.nVBRQuality;
}
else
{
trackBarVBRQuality.Value = 0;
}
checkBoxVBR.Checked = groupBoxVBR.Enabled = hv.bEnableVBR != 0;
}
finally
{
m_FireConfigChangeEvent = true;
}
}
#endregion
protected virtual void DoConfigChange(System.EventArgs e)
{
if ( m_FireConfigChangeEvent && (ConfigChange != null) )
{
ConfigChange(this, e);
}
}
private void checkBoxVBR_CheckedChanged(object sender, System.EventArgs e)
{
if (checkBoxVBR.Checked)
{
groupBoxVBR.Enabled = true;
if (comboBoxVBRMethod.SelectedIndex < 1)
{
comboBoxVBRMethod.SelectedIndex = 1;
}
}
else
{
groupBoxVBR.Enabled = false;
}
DoConfigChange(e);
}
private void Control_Changed(object sender, System.EventArgs e)
{
DoConfigChange(e);
}
private void BitRateChange(object sender, System.EventArgs e)
{
if (comboBoxMaxBitRate.SelectedIndex < comboBoxBitRate.SelectedIndex )
{
comboBoxMaxBitRate.SelectedIndex = comboBoxBitRate.SelectedIndex;
}
DoConfigChange(e);
}
private void comboBoxVBRMethod_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (checkBoxVBR.Checked && (comboBoxVBRMethod.SelectedIndex == 0))
{
comboBoxVBRMethod.SelectedIndex = 1;
}
DoConfigChange(e);
}
}
}
| |
#region Header
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Copyright (c) 2007-2008 James Nies and NArrange contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available under
* the terms of the Common Public License v1.0 which accompanies this
* distribution.
*
* 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.
*
* 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.
*
*<author>James Nies</author>
*<contributor>Justin Dearing</contributor>
*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
#endregion Header
namespace NArrange.Core
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text.RegularExpressions;
using NArrange.Core.CodeElements;
using NArrange.Core.Configuration;
/// <summary>
/// Base code parser implementation.
/// </summary>
public abstract class CodeParser : ICodeElementParser
{
#region Fields
/// <summary>
/// Default block length (for instantiating string builders)
/// </summary>
protected const int DefaultBlockLength = 256;
/// <summary>
/// Default word length (for instantiating string builders)
/// </summary>
protected const int DefaultWordLength = 16;
/// <summary>
/// Empty character.
/// </summary>
protected const char EmptyChar = '\0';
/// <summary>
/// Whitepace characters.
/// </summary>
protected static readonly char[] WhiteSpaceCharacters = { ' ', '\t', '\r', '\n' };
/// <summary>
/// Buffer for reading a character.
/// </summary>
private readonly char[] _charBuffer = new char[1];
/// <summary>
/// Code configuration.
/// </summary>
private CodeConfiguration _configuration;
/// <summary>
/// Current character.
/// </summary>
private char _currCh;
/// <summary>
/// Current line number.
/// </summary>
private int _lineNumber = 1;
/// <summary>
/// Current line character position.
/// </summary>
private int _position = 1;
/// <summary>
/// Previous character.
/// </summary>
private char _prevCh;
/// <summary>
/// Input text reader.
/// </summary>
private TextReader _reader;
/// <summary>
/// Regular expression cache.
/// </summary>
private Dictionary<string, Regex> _regexCache = new Dictionary<string, Regex>();
#endregion Fields
#region Properties
/// <summary>
/// Gets or sets the code configuration.
/// </summary>
public CodeConfiguration Configuration
{
get
{
if (_configuration == null)
{
_configuration = CodeConfiguration.Default;
}
return _configuration;
}
set
{
_configuration = value;
}
}
/// <summary>
/// Gets the most recently read character.
/// </summary>
protected char CurrentChar
{
get
{
return _currCh;
}
}
/// <summary>
/// Gets the next character in the stream, if any.
/// </summary>
/// <returns>Next character, if none then EmptyChar.</returns>
protected char NextChar
{
get
{
int data = _reader.Peek();
if (data > 0)
{
char ch = (char)data;
return ch;
}
else
{
return EmptyChar;
}
}
}
/// <summary>
/// Gets the previously read character (i.e. before CurrentChar)
/// </summary>
protected char PreviousChar
{
get
{
return _prevCh;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Determines whether or not the specified character is whitespace.
/// </summary>
/// <param name="character">Character to test.</param>
/// <returns>True if the character is whitespace, otherwise false.</returns>
public static bool IsWhiteSpace(char character)
{
return character == ' ' || character == '\t' ||
character == '\n' || character == '\r';
}
/// <summary>
/// Parses a collection of code elements from a stream reader.
/// </summary>
/// <param name="reader">Code stream reader</param>
/// <returns>A collection of parsed code elements.</returns>
public ReadOnlyCollection<ICodeElement> Parse(TextReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
List<ICodeElement> codeElements = new List<ICodeElement>();
Reset();
_reader = reader;
codeElements = DoParseElements();
return codeElements.AsReadOnly();
}
/// <summary>
/// Applies attributes and comments to a code element.
/// </summary>
/// <param name="codeElement">Code element to apply to.</param>
/// <param name="comments">Comments to apply.</param>
/// <param name="attributes">Attributes to apply.</param>
protected static void ApplyCommentsAndAttributes(
CodeElement codeElement,
ReadOnlyCollection<ICommentElement> comments,
ReadOnlyCollection<AttributeElement> attributes)
{
CommentedElement commentedElement = codeElement as CommentedElement;
if (commentedElement != null)
{
//
// Add any header comments
//
foreach (ICommentElement comment in comments)
{
commentedElement.AddHeaderComment(comment);
}
}
AttributedElement attributedElement = codeElement as AttributedElement;
if (attributedElement != null)
{
foreach (AttributeElement attribute in attributes)
{
attributedElement.AddAttribute(attribute);
//
// Treat attribute comments as header comments
//
if (attribute.HeaderComments.Count > 0)
{
foreach (ICommentElement comment in attribute.HeaderComments)
{
attributedElement.AddHeaderComment(comment);
}
attribute.ClearHeaderCommentLines();
}
}
}
}
/// <summary>
/// Parses elements from the current point in the stream.
/// </summary>
/// <returns>List of parsed code elements.</returns>
protected abstract List<ICodeElement> DoParseElements();
/// <summary>
/// Eats the specified character.
/// </summary>
/// <param name="character">Character to eat.</param>
protected void EatChar(char character)
{
EatWhiteSpace();
TryReadChar();
if (CurrentChar != character)
{
OnParseError("Expected " + character);
}
}
/// <summary>
/// Reads until the next non-whitespace character is reached.
/// </summary>
protected void EatWhiteSpace()
{
EatWhiteSpace(WhiteSpaceTypes.All);
}
/// <summary>
/// Reads until the next non-whitespace character is reached.
/// </summary>
/// <param name="whiteSpaceType">Whitespace type flags.</param>
protected void EatWhiteSpace(WhiteSpaceTypes whiteSpaceType)
{
int data = _reader.Peek();
while (data > 0)
{
char ch = (char)data;
if ((((whiteSpaceType & WhiteSpaceTypes.Space) == WhiteSpaceTypes.Space) && ch == ' ') ||
(((whiteSpaceType & WhiteSpaceTypes.Tab) == WhiteSpaceTypes.Tab) && ch == '\t') ||
(((whiteSpaceType & WhiteSpaceTypes.CarriageReturn) == WhiteSpaceTypes.CarriageReturn) && ch == '\r') ||
(((whiteSpaceType & WhiteSpaceTypes.Linefeed) == WhiteSpaceTypes.Linefeed) && ch == '\n'))
{
TryReadChar();
}
else
{
return;
}
data = _reader.Peek();
}
}
/// <summary>
/// Gets text from a comment directive, if present.
/// </summary>
/// <param name="comment">Comment element containing the directive.</param>
/// <param name="pattern">Regular expression pattern.</param>
/// <param name="group">Group key for the text to retrieve.</param>
/// <returns>Text for the comment directive.</returns>
protected string GetCommentDirectiveText(CommentElement comment, string pattern, string group)
{
string text = null;
if (comment != null && comment.Type == CommentType.Line && !string.IsNullOrEmpty(pattern))
{
Regex regex = null;
if (!_regexCache.TryGetValue(pattern, out regex))
{
regex = new Regex(pattern, RegexOptions.IgnoreCase);
_regexCache.Add(pattern, regex);
}
string commentText = comment.Text.Trim();
Match match = regex.Match(commentText);
if (match != null && match.Length > 0)
{
Group textGroup = match.Groups[group];
if (textGroup != null)
{
text = textGroup.Value.Trim();
}
}
}
return text;
}
/// <summary>
/// Throws a parse error
/// </summary>
/// <param name="message">Parse error message.</param>
protected void OnParseError(string message)
{
throw new ParseException(message, _lineNumber, _position);
}
/// <summary>
/// Reads the current line. Does not update PreviousChar.
/// </summary>
/// <returns>The line read.</returns>
protected string ReadLine()
{
string line = _reader.ReadLine();
_lineNumber++;
_position = 1;
return line;
}
/// <summary>
/// Tries to read the specified character from the stream and update
/// the CurrentChar property.
/// </summary>
/// <param name="character">Character to read.</param>
/// <returns>True if the character was read, otherwise false.</returns>
protected bool TryReadChar(char character)
{
int data = _reader.Peek();
char nextCh = (char)data;
if (nextCh == character)
{
TryReadChar();
return true;
}
return false;
}
/// <summary>
/// Tries to read any character from the stream and places it in the
/// CurrentChar property.
/// </summary>
/// <returns>True if a character was read, otherwise false.</returns>
protected bool TryReadChar()
{
if (_reader.Read(_charBuffer, 0, 1) > 0)
{
_prevCh = _currCh;
_currCh = _charBuffer[0];
if (_currCh == '\n')
{
_lineNumber++;
_position = 1;
}
else
{
_position++;
}
return true;
}
return false;
}
/// <summary>
/// Reset the parser to a state to handle parsing another input.
/// </summary>
private void Reset()
{
_currCh = '\0';
_prevCh = '\0';
_lineNumber = 1;
_position = 1;
}
#endregion Methods
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Parsing;
using Microsoft.PythonTools.Repl;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.PythonTools.Intellisense {
/// <summary>
/// Provides an asynchronous queue for parsing source code. Multiple items
/// may be parsed simultaneously. Text buffers are monitored for changes and
/// the parser is called when the buffer should be re-parsed.
/// </summary>
internal class ParseQueue {
internal readonly VsProjectAnalyzer _parser;
internal int _analysisPending;
/// <summary>
/// Creates a new parse queue which will parse using the provided parser.
/// </summary>
/// <param name="parser"></param>
public ParseQueue(VsProjectAnalyzer parser) {
_parser = parser;
}
/// <summary>
/// Parses the specified text buffer. Continues to monitor the parsed buffer and updates
/// the parse tree asynchronously as the buffer changes.
/// </summary>
/// <param name="buffer"></param>
public BufferParser EnqueueBuffer(IProjectEntry projEntry, ITextView textView, ITextBuffer buffer) {
// only attach one parser to each buffer, we can get multiple enqueue's
// for example if a document is already open when loading a project.
BufferParser bufferParser;
if (!buffer.Properties.TryGetProperty<BufferParser>(typeof(BufferParser), out bufferParser)) {
Dispatcher dispatcher = null;
var uiElement = textView as UIElement;
if (uiElement != null) {
dispatcher = uiElement.Dispatcher;
}
bufferParser = new BufferParser(this, dispatcher, projEntry, _parser, buffer);
var curSnapshot = buffer.CurrentSnapshot;
var severity = _parser.PyService.GeneralOptions.IndentationInconsistencySeverity;
bufferParser.EnqueingEntry();
EnqueWorker(() => {
_parser.ParseBuffers(bufferParser, severity, curSnapshot);
});
} else {
bufferParser.AttachedViews++;
}
return bufferParser;
}
/// <summary>
/// Parses the specified file on disk.
/// </summary>
/// <param name="filename"></param>
public void EnqueueFile(IProjectEntry projEntry, string filename) {
var severity = _parser.PyService.GeneralOptions.IndentationInconsistencySeverity;
EnqueWorker(() => {
for (int i = 0; i < 10; i++) {
try {
if (!File.Exists(filename)) {
break;
}
using (var reader = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) {
_parser.ParseFile(projEntry, filename, reader, severity);
return;
}
} catch (IOException) {
// file being copied, try again...
Thread.Sleep(100);
} catch (UnauthorizedAccessException) {
// file is inaccessible, try again...
Thread.Sleep(100);
}
}
IPythonProjectEntry pyEntry = projEntry as IPythonProjectEntry;
if (pyEntry != null) {
// failed to parse, keep the UpdateTree calls balanced
pyEntry.UpdateTree(null, null);
}
});
}
public void EnqueueZipArchiveEntry(IProjectEntry projEntry, string zipFileName, ZipArchiveEntry entry, Action onComplete) {
var pathInArchive = entry.FullName.Replace('/', '\\');
var fileName = Path.Combine(zipFileName, pathInArchive);
var severity = _parser.PyService.GeneralOptions.IndentationInconsistencySeverity;
EnqueWorker(() => {
try {
using (var stream = entry.Open()) {
_parser.ParseFile(projEntry, fileName, stream, severity);
return;
}
} catch (IOException ex) {
Debug.Fail(ex.Message);
} catch (InvalidDataException ex) {
Debug.Fail(ex.Message);
} finally {
onComplete();
}
IPythonProjectEntry pyEntry = projEntry as IPythonProjectEntry;
if (pyEntry != null) {
// failed to parse, keep the UpdateTree calls balanced
pyEntry.UpdateTree(null, null);
}
});
}
private void EnqueWorker(Action parser) {
Interlocked.Increment(ref _analysisPending);
ThreadPool.QueueUserWorkItem(
dummy => {
try {
parser();
} finally {
Interlocked.Decrement(ref _analysisPending);
}
}
);
}
public bool IsParsing {
get {
return _analysisPending > 0;
}
}
public int ParsePending {
get {
return _analysisPending;
}
}
}
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "ownership is unclear")]
class BufferParser {
internal VsProjectAnalyzer _parser;
private readonly ParseQueue _queue;
private readonly Timer _timer;
private readonly Dispatcher _dispatcher;
private IList<ITextBuffer> _buffers;
private bool _parsing, _requeue, _textChange;
internal IProjectEntry _currentProjEntry;
private ITextDocument _document;
public int AttachedViews;
private const int ReparseDelay = 1000; // delay in MS before we re-parse a buffer w/ non-line changes.
public BufferParser(ParseQueue queue, Dispatcher dispatcher, IProjectEntry initialProjectEntry, VsProjectAnalyzer parser, ITextBuffer buffer) {
_queue = queue;
_parser = parser;
_timer = new Timer(ReparseTimer, null, Timeout.Infinite, Timeout.Infinite);
_buffers = new[] { buffer };
_currentProjEntry = initialProjectEntry;
_dispatcher = dispatcher;
AttachedViews = 1;
InitBuffer(buffer);
}
private Severity IndentationInconsistencySeverity {
get {
return _parser.PyService.GeneralOptions.IndentationInconsistencySeverity;
}
}
public void StopMonitoring() {
foreach (var buffer in _buffers) {
buffer.ChangedLowPriority -= BufferChangedLowPriority;
buffer.Properties.RemoveProperty(typeof(BufferParser));
if (_document != null) {
_document.EncodingChanged -= EncodingChanged;
_document = null;
}
}
_timer.Dispose();
}
public Dispatcher Dispatcher {
get {
return _dispatcher;
}
}
public ITextBuffer[] Buffers {
get {
return _buffers.Where(
x => !x.Properties.ContainsProperty(PythonReplEvaluator.InputBeforeReset)
).ToArray();
}
}
internal void AddBuffer(ITextBuffer textBuffer) {
lock (this) {
EnsureMutableBuffers();
_buffers.Add(textBuffer);
InitBuffer(textBuffer);
_parser.ConnectErrorList(_currentProjEntry, textBuffer);
}
}
internal void RemoveBuffer(ITextBuffer subjectBuffer) {
lock (this) {
EnsureMutableBuffers();
UninitBuffer(subjectBuffer);
_buffers.Remove(subjectBuffer);
_parser.DisconnectErrorList(_currentProjEntry, subjectBuffer);
}
}
private void UninitBuffer(ITextBuffer subjectBuffer) {
if (_document != null) {
_document.EncodingChanged -= EncodingChanged;
_document = null;
}
subjectBuffer.Properties.RemoveProperty(typeof(IProjectEntry));
subjectBuffer.Properties.RemoveProperty(typeof(BufferParser));
subjectBuffer.ChangedLowPriority -= BufferChangedLowPriority;
}
private void InitBuffer(ITextBuffer buffer) {
buffer.Properties.AddProperty(typeof(BufferParser), this);
buffer.ChangedLowPriority += BufferChangedLowPriority;
buffer.Properties.AddProperty(typeof(IProjectEntry), _currentProjEntry);
if (_document != null) {
_document.EncodingChanged -= EncodingChanged;
_document = null;
}
if (buffer.Properties.TryGetProperty<ITextDocument>(typeof(ITextDocument), out _document) && _document != null) {
_document.EncodingChanged += EncodingChanged;
}
}
private void EnsureMutableBuffers() {
if (_buffers.IsReadOnly) {
_buffers = new List<ITextBuffer>(_buffers);
}
}
internal void ReparseTimer(object unused) {
RequeueWorker();
}
internal void ReparseWorker(object unused) {
ITextSnapshot[] snapshots;
lock (this) {
if (_parsing) {
NotReparsing();
Interlocked.Decrement(ref _queue._analysisPending);
return;
}
_parsing = true;
var buffers = Buffers;
snapshots = new ITextSnapshot[buffers.Length];
for (int i = 0; i < buffers.Length; i++) {
snapshots[i] = buffers[i].CurrentSnapshot;
}
}
_parser.ParseBuffers(this, IndentationInconsistencySeverity, snapshots);
Interlocked.Decrement(ref _queue._analysisPending);
lock (this) {
_parsing = false;
if (_requeue) {
RequeueWorker();
}
_requeue = false;
}
}
/// <summary>
/// Called when we decide we need to re-parse a buffer but before we start the buffer.
/// </summary>
internal void EnqueingEntry() {
lock (this) {
IPythonProjectEntry pyEntry = _currentProjEntry as IPythonProjectEntry;
if (pyEntry != null) {
pyEntry.BeginParsingTree();
}
}
}
/// <summary>
/// Called when we race and are not actually re-parsing a buffer, balances the calls
/// of BeginParsingTree when we aren't parsing.
/// </summary>
private void NotReparsing() {
lock (this) {
IPythonProjectEntry pyEntry = _currentProjEntry as IPythonProjectEntry;
if (pyEntry != null) {
pyEntry.UpdateTree(null, null);
}
}
}
internal void EncodingChanged(object sender, EncodingChangedEventArgs e) {
lock (this) {
if (_parsing) {
// we are currently parsing, just reque when we complete
_requeue = true;
_timer.Change(Timeout.Infinite, Timeout.Infinite);
} else {
Requeue();
}
}
}
internal void BufferChangedLowPriority(object sender, TextContentChangedEventArgs e) {
lock (this) {
// only immediately re-parse on line changes after we've seen a text change.
if (_parsing) {
// we are currently parsing, just reque when we complete
_requeue = true;
_timer.Change(Timeout.Infinite, Timeout.Infinite);
} else if (LineAndTextChanges(e)) {
// user pressed enter, we should reque immediately
Requeue();
} else {
// parse if the user doesn't do anything for a while.
_textChange = IncludesTextChanges(e);
_timer.Change(ReparseDelay, Timeout.Infinite);
}
}
}
internal void Requeue() {
RequeueWorker();
_timer.Change(Timeout.Infinite, Timeout.Infinite);
}
private void RequeueWorker() {
Interlocked.Increment(ref _queue._analysisPending);
EnqueingEntry();
ThreadPool.QueueUserWorkItem(ReparseWorker);
}
/// <summary>
/// Used to track if we have line + text changes, just text changes, or just line changes.
///
/// If we have text changes followed by a line change we want to immediately reparse.
/// If we have just text changes we want to reparse in ReparseDelay ms from the last change.
/// If we have just repeated line changes (e.g. someone's holding down enter) we don't want to
/// repeatedly reparse, instead we want to wait ReparseDelay ms.
/// </summary>
private bool LineAndTextChanges(TextContentChangedEventArgs e) {
if (_textChange) {
_textChange = false;
return e.Changes.IncludesLineChanges;
}
bool mixedChanges = false;
if (e.Changes.IncludesLineChanges) {
mixedChanges = IncludesTextChanges(e);
}
return mixedChanges;
}
/// <summary>
/// Returns true if the change incldues text changes (not just line changes).
/// </summary>
private static bool IncludesTextChanges(TextContentChangedEventArgs e) {
bool mixedChanges = false;
foreach (var change in e.Changes) {
if (!string.IsNullOrEmpty(change.OldText) || change.NewText != Environment.NewLine) {
mixedChanges = true;
break;
}
}
return mixedChanges;
}
internal ITextDocument Document {
get {
return _document;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using Aurora.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Services.Interfaces
{
public interface IGridService
{
IGridService InnerService { get; }
/// <summary>
/// The max size a region can be (meters)
/// </summary>
int GetMaxRegionSize();
/// <summary>
/// The size (in meters) of how far neighbors will be found
/// </summary>
int GetRegionViewSize();
/// <summary>
/// Register a region with the grid service.
/// </summary>
/// <param name="regionInfos"> </param>
/// <param name="oldSessionID"></param>
/// <param name="password"> </param>
/// <returns></returns>
/// <exception cref="System.Exception">Thrown if region registration failed</exception>
RegisterRegion RegisterRegion(GridRegion regionInfos, UUID oldSessionID, string password);
/// <summary>
/// Deregister a region with the grid service.
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
/// <exception cref="System.Exception">Thrown if region deregistration failed</exception>
bool DeregisterRegion(GridRegion region);
/// <summary>
/// Get a specific region by UUID in the given scope
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionID"></param>
/// <returns></returns>
GridRegion GetRegionByUUID(List<UUID> scopeIDs, UUID regionID);
/// <summary>
/// Get the region at the given position (in meters)
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
GridRegion GetRegionByPosition(List<UUID> scopeIDs, int x, int y);
/// <summary>
/// Get the first returning region by name in the given scope
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionName"></param>
/// <returns></returns>
GridRegion GetRegionByName(List<UUID> scopeIDs, string regionName);
/// <summary>
/// Get information about regions starting with the provided name.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="name">
/// The name to match against.
/// </param>
/// <returns>
/// A list of <see cref="RegionInfo"/>s of regions with matching name. If the
/// grid-server couldn't be contacted or returned an error, return null.
/// </returns>
List<GridRegion> GetRegionsByName(List<UUID> scopeIDs, string name, uint? start, uint? count);
/// <summary>
/// Get number of regions starting with the provided name.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="name">
/// The name to match against.
/// </param>
/// <returns>
/// A the count of <see cref="RegionInfo"/>s of regions with matching name. If the
/// grid-server couldn't be contacted or returned an error, returns 0.
/// </returns>
uint GetRegionsByNameCount(List<UUID> scopeIDs, string name);
/// <summary>
/// Get all regions within the range of (xmin - xmax, ymin - ymax) (in meters)
/// </summary>
/// <param name="scopeID"></param>
/// <param name="xmin"></param>
/// <param name="xmax"></param>
/// <param name="ymin"></param>
/// <param name="ymax"></param>
/// <returns></returns>
List<GridRegion> GetRegionRange(List<UUID> scopeIDs, int xmin, int xmax, int ymin, int ymax);
/// <summary>
/// Get all regions within the range of specified center.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="centerX"></param>
/// <param name="centerY"></param>
/// <param name="squareRangeFromCenterInMeters"></param>
/// <returns></returns>
List<GridRegion> GetRegionRange(List<UUID> scopeIDs, float centerX, float centerY, uint squareRangeFromCenterInMeters);
/// <summary>
/// Get the neighbors of the given region
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
List<GridRegion> GetNeighbors(List<UUID> scopeIDs, GridRegion region);
/// <summary>
/// Get any default regions that have been set for users that are logging in that don't have a region to log into
/// </summary>
/// <param name="scopeID"></param>
/// <returns></returns>
List<GridRegion> GetDefaultRegions(List<UUID> scopeIDs);
/// <summary>
/// If all the default regions are down, find any fallback regions that have been set near x,y
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
List<GridRegion> GetFallbackRegions(List<UUID> scopeIDs, int x, int y);
/// <summary>
/// If there still are no regions after fallbacks have been checked, find any region near x,y
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
List<GridRegion> GetSafeRegions(List<UUID> scopeIDs, int x, int y);
/// <summary>
/// Get the current flags of the given region
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionID"></param>
/// <returns></returns>
int GetRegionFlags(List<UUID> scopeIDs, UUID regionID);
/// <summary>
/// Update the map of the given region if the sessionID is correct
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
string UpdateMap(GridRegion region);
/// <summary>
/// Get all map items of the given type for the given region
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="gridItemType"></param>
/// <returns></returns>
multipleMapItemReply GetMapItems (List<UUID> scopeIDs, ulong regionHandle, GridItemType gridItemType);
/// <summary>
/// The region (RegionID) has been determined to be unsafe, don't let agents log into it if no other region is found
/// </summary>
/// <param name="id"></param>
void SetRegionUnsafe (UUID id);
/// <summary>
/// The region (RegionID) has been determined to be safe, allow agents to log into it again
/// </summary>
/// <param name="id"></param>
void SetRegionSafe (UUID id);
/// <summary>
/// Verify the given SessionID for the given region
/// </summary>
/// <param name="r"></param>
/// <param name="SessionID"></param>
/// <returns></returns>
bool VerifyRegionSessionID(GridRegion r, UUID SessionID);
void Configure (Nini.Config.IConfigSource config, IRegistryCore registry);
void Start (Nini.Config.IConfigSource config, IRegistryCore registry);
void FinishedStartup ();
}
public class RegisterRegion : IDataTransferable
{
public string Error;
public List<GridRegion> Neighbors = new List<GridRegion>();
public UUID SessionID;
public int RegionFlags = 0;
public OSDMap Urls = new OSDMap();
public OSDMap RegionRemote;
public GridRegion Region;
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["Error"] = Error;
map["Neighbors"] = new OSDArray(Neighbors.ConvertAll<OSD>((region) => region.ToOSD()));
map["SessionID"] = SessionID;
map["RegionFlags"] = RegionFlags;
if (Urls != null)
map["Urls"] = Urls;
if (RegionRemote != null)
map["RegionRemote"] = RegionRemote;
if (Region != null)
map["Region"] = Region.ToOSD();
return map;
}
public override void FromOSD(OSDMap map)
{
Error = map["Error"];
OSDArray n = (OSDArray)map["Neighbors"];
Neighbors = n.ConvertAll<GridRegion>((osd) => { GridRegion r = new GridRegion(); r.FromOSD((OSDMap)osd); return r; });
SessionID = map["SessionID"];
RegionFlags = map["RegionFlags"];
if (map.ContainsKey("Urls"))
Urls = (OSDMap)map["Urls"];
if (map.ContainsKey("RegionRemote"))
RegionRemote = (OSDMap)map["RegionRemote"];
if (map.ContainsKey("Region"))
{
Region = new GridRegion();
Region.FromOSD((OSDMap)map["Region"]);
}
}
}
public class GridRegion : AllScopeIDImpl
{
#region GridRegion
/// <summary>
/// The port by which http communication occurs with the region
/// </summary>
public uint HttpPort
{
get { return m_httpPort; }
set { m_httpPort = value; }
}
protected uint m_httpPort;
/// <summary>
/// A well-formed URI for the host region server (namely "http://" + ExternalHostName + : + HttpPort)
/// </summary>
public string ServerURI
{
get
{
if(string.IsNullOrEmpty(m_serverURI))
return "http://" + ExternalHostName + ":" + HttpPort;
return m_serverURI;
}
set { m_serverURI = value; }
}
protected string m_serverURI;
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
protected string m_regionName = String.Empty;
public string RegionType
{
get { return m_regionType; }
set { m_regionType = value; }
}
protected string m_regionType = String.Empty;
public int RegionLocX
{
get { return m_regionLocX; }
set { m_regionLocX = value; }
}
protected int m_regionLocX;
public int RegionLocY
{
get { return m_regionLocY; }
set { m_regionLocY = value; }
}
protected int m_regionLocY;
public int RegionLocZ
{
get { return m_regionLocZ; }
set { m_regionLocZ = value; }
}
protected int m_regionLocZ;
protected UUID m_estateOwner;
public UUID EstateOwner
{
get { return m_estateOwner; }
set { m_estateOwner = value; }
}
public int RegionSizeX
{
get { return m_RegionSizeX; }
set { m_RegionSizeX = value; }
}
public int RegionSizeY
{
get { return m_RegionSizeY; }
set { m_RegionSizeY = value; }
}
public int RegionSizeZ
{
get { return m_RegionSizeZ; }
}
public int Flags { get; set; }
public UUID SessionID
{
get { return m_SessionID; }
set { m_SessionID = value; }
}
private int m_RegionSizeX = 256;
private int m_RegionSizeY = 256;
private int m_RegionSizeZ = 256;
public UUID RegionID = UUID.Zero;
private UUID m_SessionID = UUID.Zero;
public UUID TerrainImage = UUID.Zero;
public UUID TerrainMapImage = UUID.Zero;
public UUID ParcelMapImage = UUID.Zero;
public byte Access;
public string AuthToken = string.Empty;
private IPEndPoint m_remoteEndPoint = null;
protected string m_externalHostName;
protected IPEndPoint m_internalEndPoint;
public int LastSeen = 0;
protected OSDMap m_genericMap = new OSDMap();
public OSDMap GenericMap
{
get { return m_genericMap; }
set { m_genericMap = value; }
}
public bool IsOnline
{
get { return (Flags & (int)Aurora.Framework.RegionFlags.RegionOnline) == 1; }
set
{
if (value)
Flags |= (int)Aurora.Framework.RegionFlags.RegionOnline;
else
Flags &= (int)Aurora.Framework.RegionFlags.RegionOnline;
}
}
public GridRegion()
{
Flags = 0;
}
public GridRegion(RegionInfo ConvertFrom)
{
Flags = 0;
m_regionName = ConvertFrom.RegionName;
m_regionType = ConvertFrom.RegionType;
m_regionLocX = ConvertFrom.RegionLocX;
m_regionLocY = ConvertFrom.RegionLocY;
m_regionLocZ = ConvertFrom.RegionLocZ;
m_internalEndPoint = ConvertFrom.InternalEndPoint;
m_externalHostName = MainServer.Instance.HostName;
m_externalHostName = m_externalHostName.Replace("https://", "");
m_externalHostName = m_externalHostName.Replace("http://", "");
m_httpPort = MainServer.Instance.Port;
RegionID = ConvertFrom.RegionID;
ServerURI = MainServer.Instance.ServerURI;
TerrainImage = ConvertFrom.RegionSettings.TerrainImageID;
TerrainMapImage = ConvertFrom.RegionSettings.TerrainMapImageID;
ParcelMapImage = ConvertFrom.RegionSettings.ParcelMapImageID;
Access = ConvertFrom.AccessLevel;
if(ConvertFrom.EstateSettings != null)
EstateOwner = ConvertFrom.EstateSettings.EstateOwner;
m_RegionSizeX = ConvertFrom.RegionSizeX;
m_RegionSizeY = ConvertFrom.RegionSizeY;
m_RegionSizeZ = ConvertFrom.RegionSizeZ;
ScopeID = ConvertFrom.ScopeID;
AllScopeIDs = ConvertFrom.AllScopeIDs;
SessionID = ConvertFrom.GridSecureSessionID;
Flags |= (int)Aurora.Framework.RegionFlags.RegionOnline;
}
#region Definition of equality
/// <summary>
/// Define equality as two regions having the same, non-zero UUID.
/// </summary>
public bool Equals(GridRegion region)
{
if (region == null)
return false;
// Return true if the non-zero UUIDs are equal:
return (RegionID != UUID.Zero) && RegionID.Equals(region.RegionID);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
return Equals(obj as GridRegion);
}
public override int GetHashCode()
{
return RegionID.GetHashCode() ^ TerrainImage.GetHashCode();
}
#endregion
/// <value>
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
/// XXX Isn't this really doing too much to be a simple getter, rather than an explict method?
/// </value>
public IPEndPoint ExternalEndPoint
{
get
{
if (m_remoteEndPoint == null && m_externalHostName != null && m_internalEndPoint != null)
m_remoteEndPoint = NetworkUtils.ResolveEndPoint(m_externalHostName, m_internalEndPoint.Port);
return m_remoteEndPoint;
}
}
public string ExternalHostName
{
get { return m_externalHostName; }
set { m_externalHostName = value; }
}
public IPEndPoint InternalEndPoint
{
get { return m_internalEndPoint; }
set { m_internalEndPoint = value; }
}
public ulong RegionHandle
{
get { return Util.IntsToUlong(RegionLocX, RegionLocY); }
set
{
Util.UlongToInts(value, out m_regionLocX, out m_regionLocY);
}
}
/// <summary>
/// Returns whether the grid coordinate is inside of this region
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public bool PointIsInRegion(int x, int y)
{
if (x > RegionLocX && y > RegionLocY &&
x < RegionLocX + RegionSizeX &&
y < RegionLocY + RegionSizeY)
return true;
return false;
}
#endregion
#region IDataTransferable
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["uuid"] = RegionID;
map["locX"] = RegionLocX;
map["locY"] = RegionLocY;
map["locZ"] = RegionLocZ;
map["regionName"] = RegionName;
map["regionType"] = RegionType;
map["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString();
map["serverHttpPort"] = HttpPort;
map["serverURI"] = ServerURI;
if(InternalEndPoint != null)
map["serverPort"] = InternalEndPoint.Port;
map["regionMapTexture"] = TerrainImage;
map["regionTerrainTexture"] = TerrainMapImage;
map["ParcelMapImage"] = ParcelMapImage;
map["access"] = (int)Access;
map["owner_uuid"] = EstateOwner;
map["AuthToken"] = AuthToken;
map["sizeX"] = RegionSizeX;
map["sizeY"] = RegionSizeY;
map["sizeZ"] = RegionSizeZ;
map["LastSeen"] = LastSeen;
map["SessionID"] = SessionID;
map["ScopeID"] = ScopeID;
map["AllScopeIDs"] = AllScopeIDs.ToOSDArray();
map["Flags"] = Flags;
map["GenericMap"] = GenericMap;
map["EstateOwner"] = EstateOwner;
// We send it along too so that it doesn't need resolved on the other end
if (ExternalEndPoint != null)
{
map["remoteEndPointIP"] = ExternalEndPoint.Address.GetAddressBytes ();
map["remoteEndPointPort"] = ExternalEndPoint.Port;
}
return map;
}
public override void FromOSD(OSDMap map)
{
if (map.ContainsKey("uuid"))
RegionID = map["uuid"].AsUUID();
if (map.ContainsKey("locX"))
RegionLocX = map["locX"].AsInteger();
if (map.ContainsKey("locY"))
RegionLocY = map["locY"].AsInteger();
if (map.ContainsKey("locZ"))
RegionLocZ = map["locZ"].AsInteger();
if (map.ContainsKey("regionName"))
RegionName = map["regionName"].AsString();
if (map.ContainsKey("regionType"))
RegionType = map["regionType"].AsString();
ExternalHostName = map.ContainsKey("serverIP") ? map["serverIP"].AsString() : "127.0.0.1";
if (map.ContainsKey("serverPort"))
{
Int32 port = map["serverPort"].AsInteger();
InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port);
}
if (map.ContainsKey("serverHttpPort"))
{
UInt32 port = map["serverHttpPort"].AsUInteger();
HttpPort = port;
}
if (map.ContainsKey("serverURI"))
ServerURI = map["serverURI"];
if (map.ContainsKey("regionMapTexture"))
TerrainImage = map["regionMapTexture"].AsUUID();
if (map.ContainsKey("regionTerrainTexture"))
TerrainMapImage = map["regionTerrainTexture"].AsUUID();
if (map.ContainsKey("ParcelMapImage"))
ParcelMapImage = map["ParcelMapImage"].AsUUID();
if (map.ContainsKey("access"))
Access = (byte)map["access"].AsInteger();
if (map.ContainsKey("owner_uuid"))
EstateOwner = map["owner_uuid"].AsUUID();
if (map.ContainsKey("EstateOwner"))
EstateOwner = map["EstateOwner"].AsUUID();
if (map.ContainsKey("AuthToken"))
AuthToken = map["AuthToken"].AsString();
if (map.ContainsKey("sizeX"))
m_RegionSizeX = map["sizeX"].AsInteger();
if (map.ContainsKey("sizeY"))
m_RegionSizeY = map["sizeY"].AsInteger();
if (map.ContainsKey("sizeZ"))
m_RegionSizeZ = map["sizeZ"].AsInteger();
if (map.ContainsKey("LastSeen"))
LastSeen = map["LastSeen"].AsInteger();
if (map.ContainsKey("SessionID"))
SessionID = map["SessionID"].AsUUID();
if (map.ContainsKey("Flags"))
Flags = map["Flags"].AsInteger();
if (map.ContainsKey("ScopeID"))
ScopeID = map["ScopeID"].AsUUID();
if (map.ContainsKey("AllScopeIDs"))
AllScopeIDs = ((OSDArray)map["AllScopeIDs"]).ConvertAll<UUID>(o => o);
if (map.ContainsKey("GenericMap"))
GenericMap = (OSDMap)map["GenericMap"];
if (map.ContainsKey("remoteEndPointIP"))
{
IPAddress add = new IPAddress(map["remoteEndPointIP"].AsBinary());
int port = map["remoteEndPointPort"].AsInteger();
m_remoteEndPoint = new IPEndPoint(add, port);
}
}
public override Dictionary<string, object> ToKVP()
{
return Util.OSDToDictionary(ToOSD());
}
public override void FromKVP(Dictionary<string, object> KVP)
{
FromOSD(Util.DictionaryToOSD(KVP));
}
#endregion
}
/// <summary>
/// This is the main service that collects URLs for registering clients.
/// Call this if you want to get secure URLs for the given SessionID
/// </summary>
public interface IGridRegistrationService
{
/// <summary>
/// Time before handlers will need to reregister (in hours)
/// </summary>
float ExpiresTime { get; }
/// <summary>
/// Gets a list of secure URLs for the given RegionHandle and SessionID
/// </summary>
/// <param name="SessionID"></param>
/// <returns></returns>
OSDMap GetUrlForRegisteringClient(string SessionID);
/// <summary>
/// Registers a module that will be requested when GetUrlForRegisteringClient is called
/// </summary>
/// <param name="module"></param>
void RegisterModule(IGridRegistrationUrlModule module);
/// <summary>
/// Remove the URLs for the given region
/// </summary>
/// <param name="SessionID"></param>
void RemoveUrlsForClient(string SessionID);
/// <summary>
/// Checks that the given client can access the function that it is calling
/// </summary>
/// <param name="SessionID"></param>
/// <param name="function"></param>
/// <param name="defaultThreatLevel"></param>
/// <returns></returns>
bool CheckThreatLevel(string SessionID, string function, ThreatLevel defaultThreatLevel);
/// <summary>
/// Updates the time so that the region does not timeout
/// </summary>
/// <param name="p"></param>
void UpdateUrlsForClient(string SessionID);
OSDMap RegionRemoteHandlerURL(GridRegion regionInfo, UUID sessionID, UUID oldSessionID);
}
/// <summary>
/// The threat level enum
/// Tells how much we trust another host
/// </summary>
public enum ThreatLevel
{
None = 1,
Low = 2,
Medium = 4,
High = 8,
Full = 16
}
/// <summary>
/// This is the sub service of the IGridRegistrationService that is implemented by other modules
/// so that they can be queried for URLs to return.
/// </summary>
public interface IGridRegistrationUrlModule
{
/// <summary>
/// Name of the Url
/// </summary>
string UrlName { get; }
/// <summary>
/// Give the region all of the ports assigned for this module
/// </summary>
bool DoMultiplePorts { get; }
/// <summary>
/// Get the Url for the given sessionID
/// </summary>
/// <param name="SessionID"></param>
/// <param name="port"></param>
/// <returns></returns>
string GetUrlForRegisteringClient (string SessionID, uint port);
/// <summary>
/// Adds an existing URL to the module for the given SessionID and RegionHandle
/// </summary>
/// <param name="SessionID"></param>
/// <param name="url"></param>
/// <param name="port"></param>
void AddExistingUrlForClient (string SessionID, string url, uint port);
/// <summary>
/// Removes the given region from the http server so that the URLs cannot be used anymore
/// </summary>
/// <param name="sessionID"></param>
/// <param name="url"></param>
/// <param name="port"></param>
void RemoveUrlForClient (string sessionID, string url, uint port);
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
// onLine is invoked whenever the TCP object receives a line from the server. Treat the first
// word as a "command" and dispatch to an appropriate handler.
//---------------------------------------------------------------------------------------------
function TCPDebugger::onLine(%this, %line)
{
echo("Got line=>" @ %line);
%cmd = firstWord(%line);
%rest = restWords(%line);
if (%cmd $= "PASS") {
%this.handlePass(%rest);
}
else if(%cmd $= "COUT") {
%this.handleLineOut(%rest);
}
else if(%cmd $= "FILELISTOUT") {
%this.handleFileList(%rest);
}
else if(%cmd $= "BREAKLISTOUT") {
%this.handleBreakList(%rest);
}
else if(%cmd $= "BREAK") {
%this.handleBreak(%rest);
}
else if(%cmd $= "RUNNING") {
%this.handleRunning();
}
else if(%cmd $= "EVALOUT") {
%this.handleEvalOut(%rest);
}
else {
%this.handleError(%line);
}
}
// Handler for PASS response.
function TCPDebugger::handlePass(%this, %message)
{
if (%message $= "WrongPass") {
DebuggerConsoleView.print("Disconnected - wrong password.");
%this.disconnect();
}
else if(%message $= "Connected.") {
DebuggerConsoleView.print("Connected.");
DebuggerStatus.setValue("CONNECTED");
%this.send("FILELIST\r\n");
}
}
// Handler for COUT response.
function TCPDebugger::handleLineOut(%this, %line)
{
DebuggerConsoleView.print(%line);
}
// Handler for FILELISTOUT response.
function TCPDebugger::handleFileList(%this, %line)
{
DebuggerFilePopup.clear();
%word = 0;
while ((%file = getWord(%line, %word)) !$= "") {
%word++;
DebuggerFilePopup.add(%file, %word);
}
}
// Handler for BREAKLISTOUT response.
function TCPDebugger::handleBreakList(%this, %line)
{
%file = getWord(%line, 0);
if (%file != $DebuggerFile) {
return;
}
%pairs = getWord(%line, 1);
%curLine = 1;
DebuggerFileView.clearBreakPositions();
// Set the possible break positions.
for (%i = 0; %i < %pairs; %i++) {
%skip = getWord(%line, %i * 2 + 2);
%breaks = getWord(%line, %i * 2 + 3);
%curLine += %skip;
for (%j = 0; %j < %breaks; %j++) {
DebuggerFileView.setBreakPosition(%curLine);
%curLine++;
}
}
// Now set the actual break points.
for (%i = 0; %i < DebuggerBreakPoints.rowCount(); %i++) {
%breakText = DebuggerBreakPoints.getRowText(%i);
%breakLine = getField(%breakText, 0);
%breakFile = getField(%breakText, 1);
if (%breakFile == $DebuggerFile) {
DebuggerFileView.setBreak(%breakLine);
}
}
}
// Handler for BREAK response.
function TCPDebugger::handleBreak(%this, %line)
{
DebuggerStatus.setValue("BREAK");
// Query all the watches.
for (%i = 0; %i < DebuggerWatchView.rowCount(); %i++) {
%id = DebuggerWatchView.getRowId(%i);
%row = DebuggerWatchView.getRowTextById(%id);
%expr = getField(%row, 0);
%this.send("EVAL " @ %id @ " 0 " @ %expr @ "\r\n");
}
// Update the call stack window.
DebuggerCallStack.clear();
%file = getWord(%line, 0);
%lineNumber = getWord(%line, 1);
%funcName = getWord(%line, 2);
DbgOpenFile(%file, %lineNumber, true);
%nextWord = 3;
%rowId = 0;
%id = 0;
while(1) {
DebuggerCallStack.setRowById(%id, %file @ "\t" @ %lineNumber @ "\t" @ %funcName);
%id++;
%file = getWord(%line, %nextWord);
%lineNumber = getWord(%line, %nextWord + 1);
%funcName = getWord(%line, %nextWord + 2);
%nextWord += 3;
if (%file $= "") {
break;
}
}
}
// Handler for RUNNING response.
function TCPDebugger::handleRunning(%this)
{
DebuggerFileView.setCurrentLine(-1, true);
DebuggerCallStack.clear();
DebuggerStatus.setValue("RUNNING...");
}
// Handler for EVALOUT response.
function TCPDebugger::handleEvalOut(%this, %line)
{
%id = firstWord(%line);
%value = restWords(%line);
// See if it's the cursor watch, or from the watch window.
if (%id < 0) {
DebuggerCursorWatch.setText(DebuggerCursorWatch.expr SPC "=" SPC %value);
}
else {
%row = DebuggerWatchView.getRowTextById(%id);
if (%row $= "") {
return;
}
%expr = getField(%row, 0);
DebuggerWatchView.setRowById(%id, %expr @ "\t" @ %value);
}
}
// Handler for unrecognized response.
function TCPDebugger::handleError(%this, %line)
{
DebuggerConsoleView.print("ERROR - bogus message: " @ %line);
}
// Print a line of response from the server.
function DebuggerConsoleView::print(%this, %line)
{
%row = %this.addRow(0, %line);
%this.scrollVisible(%row);
}
// When entry in file list selected, open the file.
function DebuggerFilePopup::onSelect(%this, %id, %text)
{
DbgOpenFile(%text, 0, false);
}
// When entry on call stack selected, open the file and go to the line.
function DebuggerCallStack::onAction(%this)
{
%id = %this.getSelectedId();
if (%id == -1) {
return;
}
%text = %this.getRowTextById(%id);
%file = getField(%text, 0);
%line = getField(%text, 1);
DbgOpenFile(%file, %line, %id == 0);
}
// Add a breakpoint at the selected spot, if it doesn't already exist.
function DebuggerBreakPoints::addBreak(%this, %file, %line, %clear, %passct, %expr)
{
// columns 0 = line, 1 = file, 2 = expr
%textLine = %line @ "\t" @ %file @ "\t" @ %expr @ "\t" @ %passct @ "\t" @ %clear;
%selId = %this.getSelectedId();
%selText = %this.getRowTextById(%selId);
if ((getField(%selText, 0) $= %line) && (getField(%selText, 1) $= %file)) {
%this.setRowById(%selId, %textLine);
}
else {
%this.addRow($DbgBreakId, %textLine);
$DbgBreakId++;
}
}
// Remove the selected breakpoint.
function DebuggerBreakPoints::removeBreak(%this, %file, %line)
{
for (%i = 0; %i < %this.rowCount(); %i++) {
%id = %this.getRowId(%i);
%text = %this.getRowTextById(%id);
if ((getField(%text, 0) $= %line) && (getField(%text, 1) $= %file)) {
%this.removeRowById(%id);
return;
}
}
}
// Remove all breakpoints.
function DebuggerBreakPoints::clearBreaks(%this)
{
while (%this.rowCount()) {
%id = %this.getRowId(0);
%text = %this.getRowTextById(%id);
%file = getField(%text, 1);
%line = getField(%text, 0);
DbgRemoveBreakPoint(%file, %line);
}
}
// Go to file & line for the selected breakpoint.
function DebuggerBreakPoints::onAction(%this)
{
%id = %this.getSelectedId();
if (%id == -1) {
return;
}
%text = %this.getRowTextById(%id);
%line = getField(%text, 0);
%file = getField(%text, 1);
DbgOpenFile(%file, %line, false);
}
// Handle breakpoint removal executed from the file-view GUI.
function DebuggerFileView::onRemoveBreakPoint(%this, %line)
{
%file = $DebuggerFile;
DbgRemoveBreakPoint(%file, %line);
}
// Handle breakpoint addition executed from the file-view GUI.
function DebuggerFileView::onSetBreakPoint(%this, %line)
{
%file = $DebuggerFile;
DbgSetBreakPoint(%file, %line, 0, 0, true);
}
//---------------------------------------------------------------------------------------------
// Various support functions.
//---------------------------------------------------------------------------------------------
// Add a watch expression.
function DbgWatchDialogAdd()
{
%expr = WatchDialogExpression.getValue();
if (%expr !$= "") {
DebuggerWatchView.setRowById($DbgWatchSeq, %expr @"\t(unknown)");
TCPDebugger.send("EVAL " @ $DbgWatchSeq @ " 0 " @ %expr @ "\r\n");
$DbgWatchSeq++;
}
Canvas.popDialog(DebuggerWatchDlg);
}
// Edit a watch expression.
function DbgWatchDialogEdit()
{
%newValue = EditWatchDialogValue.getValue();
%id = DebuggerWatchView.getSelectedId();
if (%id >= 0) {
%row = DebuggerWatchView.getRowTextById(%id);
%expr = getField(%row, 0);
if (%newValue $= "") {
%assignment = %expr @ " = \"\"";
}
else {
%assignment = %expr @ " = " @ %newValue;
}
TCPDebugger.send("EVAL " @ %id @ " 0 " @ %assignment @ "\r\n");
}
Canvas.popDialog(DebuggerEditWatchDlg);
}
// Set/change the singular "cursor watch" expression.
function DbgSetCursorWatch(%expr)
{
DebuggerCursorWatch.expr = %expr;
if (DebuggerCursorWatch.expr $= "") {
DebuggerCursorWatch.setText("");
}
else {
TCPDebugger.send("EVAL -1 0 " @ DebuggerCursorWatch.expr @ "\r\n");
}
}
// Connect to the server with the given addr/port/password.
function DbgConnect()
{
%address = DebuggerConnectAddress.getValue();
%port = DebuggerConnectPort.getValue();
%password = DebuggerConnectPassword.getValue();
if ((%address !$= "" ) && (%port !$= "" ) && (%password !$= "" )) {
TCPDebugger.connect(%address @ ":" @ %port);
TCPDebugger.schedule(5000, send, %password @ "\r\n");
TCPDebugger.password = %password;
}
Canvas.popDialog(DebuggerConnectDlg);
}
// Put a condition on a breakpoint.
function DbgBreakConditionSet()
{
// Read the condition.
%condition = BreakCondition.getValue();
%passct = BreakPassCount.getValue();
%clear = BreakClear.getValue();
if (%condition $= "") {
%condition = "true";
}
if (%passct $= "") {
%passct = "0";
}
if (%clear $= "") {
%clear = "false";
}
// Set the condition.
%id = DebuggerBreakPoints.getSelectedId();
if (%id != -1) {
%bkp = DebuggerBreakPoints.getRowTextById(%id);
DbgSetBreakPoint(getField(%bkp, 1), getField(%bkp, 0), %clear, %passct, %condition);
}
Canvas.popDialog(DebuggerBreakConditionDlg);
}
// Open a file, go to the indicated line, and optionally select the line.
function DbgOpenFile(%file, %line, %selectLine)
{
if (%file !$= "") {
// Open the file in the file view.
if (DebuggerFileView.open(%file)) {
// Go to the line.
DebuggerFileView.setCurrentLine(%line, %selectLine);
// Get the breakpoints for this file.
if (%file !$= $DebuggerFile) {
TCPDebugger.send("BREAKLIST " @ %file @ "\r\n");
$DebuggerFile = %file;
}
}
}
}
// Search in the fileview GUI.
function DbgFileViewFind()
{
%searchString = DebuggerFindStringText.getValue();
DebuggerFileView.findString(%searchString);
Canvas.popDialog(DebuggerFindDlg);
}
// Set a breakpoint, optionally with condition.
function DbgSetBreakPoint(%file, %line, %clear, %passct, %expr)
{
if (!%clear) {
if (%file == $DebuggerFile) {
DebuggerFileView.setBreak(%line);
}
}
DebuggerBreakPoints.addBreak(%file, %line, %clear, %passct, %expr);
TCPDebugger.send("BRKSET " @ %file @ " " @ %line @ " " @ %clear @ " " @ %passct @ " " @ %expr @ "\r\n");
}
// Remove a breakpoint.
function DbgRemoveBreakPoint(%file, %line)
{
if (%file == $DebuggerFile) {
DebuggerFileView.removeBreak(%line);
}
TCPDebugger.send("BRKCLR " @ %file @ " " @ %line @ "\r\n");
DebuggerBreakPoints.removeBreak(%file, %line);
}
// Remove whatever breakpoint is selected in the breakpoints GUI.
function DbgDeleteSelectedBreak()
{
%selectedBreak = DebuggerBreakPoints.getSelectedId();
%rowNum = DebuggerBreakPoints.getRowNumById(%selectedWatch);
if (%rowNum >= 0) {
%breakText = DebuggerBreakPoints.getRowText(%rowNum);
%breakLine = getField(%breakText, 0);
%breakFile = getField(%breakText, 1);
DbgRemoveBreakPoint(%breakFile, %breakLine);
}
}
// Send an expression to the server for evaluation.
function DbgConsoleEntryReturn()
{
%msg = DbgConsoleEntry.getValue();
if (%msg !$= "") {
DebuggerConsoleView.print("%" @ %msg);
if (DebuggerStatus.getValue() $= "NOT CONNECTED") {
DebuggerConsoleView.print("*** Not connected.");
}
else if (DebuggerStatus.getValue() $= "BREAK") {
DebuggerConsoleView.print("*** Target is in BREAK mode.");
}
else {
TCPDebugger.send("CEVAL " @ %msg @ "\r\n");
}
}
DbgConsoleEntry.setValue("");
}
// Print a line from the server.
function DbgConsolePrint(%status)
{
DebuggerConsoleView.print(%status);
}
// Delete the currently selected watch expression.
function DbgDeleteSelectedWatch()
{
%selectedWatch = DebuggerWatchView.getSelectedId();
%rowNum = DebuggerWatchView.getRowNumById(%selectedWatch);
DebuggerWatchView.removeRow(%rowNum);
}
// Evaluate all the watch expressions.
function DbgRefreshWatches()
{
for (%i = 0; %i < DebuggerWatchView.rowCount(); %i++) {
%id = DebuggerWatchView.getRowId(%i);
%row = DebuggerWatchView.getRowTextById(%id);
%expr = getField(%row, 0);
TCPDebugger.send("EVAL " @ %id @ " 0 " @ %expr @ "\r\n");
}
}
//---------------------------------------------------------------------------------------------
// Incremental execution functions
// These just send commands to the server.
//---------------------------------------------------------------------------------------------
function dbgStepIn()
{
TCPDebugger.send("STEPIN\r\n");
}
function dbgStepOut()
{
TCPDebugger.send("STEPOUT\r\n");
}
function dbgStepOver()
{
TCPDebugger.send("STEPOVER\r\n");
}
function dbgContinue()
{
TCPDebugger.send("CONTINUE\r\n");
}
| |
using System.Collections;
using GuruComponents.Netrix.WebEditing.HighLighting;
using GuruComponents.Netrix.SpellChecker.NetSpell.Dictionary;
using GuruComponents.Netrix.SpellChecker.NetSpell;
using System.Collections.Generic;
namespace GuruComponents.Netrix.SpellChecker
{
/// <summary>
/// This realizes the basic spell checker API using callback methods.
/// </summary>
/// <remarks>
/// See <see cref="SpellChecker"/> class for more information.
/// </remarks>
/// <seealso cref="SpellChecker"/>
public interface IDocumentSpellChecker
{
/// <summary>
/// Gets or sets the <see cref="GuruComponents.Netrix.WebEditing.HighLighting.HighLightStyle"/> for the
/// spell checker.
/// </summary>
/// <remarks>
/// The style is used to highlight words marked as wrong.
/// </remarks>
IHighLightStyle HighLightStyle { get; set; }
/// <summary>
/// Activates or deactivates the background service.
/// </summary>
/// <remarks>
/// This service runs through the document and restarts
/// at the end automatically. Setting this property to <c>false</c> will stop the service.
/// </remarks>
bool BackgroundService { get; set; }
/// <summary>
/// Returns the word the caret is on on nearby.
/// </summary>
/// <returns>The recognized word, or <c>null</c>, if nothing was recognized.</returns>
string WordUnderPointer();
/// <summary>
/// Replaces the word the caret is currently in with other text.
/// </summary>
/// <param name="replaceWith">Text for replacement.</param>
void ReplaceWordUnderPointer(string replaceWith);
/// <summary>
/// Replaces the word the caret is currently in with other text.
/// </summary>
/// <param name="withHtml">If set to <c>true</c> it's allowed to add HTML.</param>
/// <param name="replaceWith">Text or HTML for replacement.</param>
void ReplaceWordUnderPointer(bool withHtml, string replaceWith);
/// <summary>
/// Returns the word with or without inline HTML the caret is on on nearby.
/// </summary>
/// <param name="withHtml">If true the method returns any embedded HTML too, otherwise HTML is stripped out.</param>
/// <returns>The recognized HTML, or <c>null</c>, if nothing was recognized.</returns>
string WordUnderPointer(bool withHtml);
/// <summary>
/// Checks to see if the word is in the dictionary.
/// </summary>
/// <param name="word" type="string">
/// <para>
/// The word to check.
/// </para>
/// </param>
/// <returns>
/// Returns true if word is found in dictionary.
/// </returns>
bool TestWord(string word);
/// <summary>
/// Populates the <see cref="Suggestions"/> property with word suggestions.
/// for the word
/// </summary>
/// <param name="word" type="string">
/// <para>
/// The word to generate suggestions on.
/// </para>
/// </param>
/// <remarks>
/// This method sets the <see cref="Text"/> property to the word.
/// Then calls <see cref="TestWord"/> on the word to generate the need
/// information for suggestions. Note that the Text, CurrentWord and WordIndex
/// properties are set when calling this method.
/// </remarks>
/// <seealso cref="Suggestions"/>
/// <seealso cref="TestWord"/>
void Suggest(string word);
/// <summary>
/// Populates the <see cref="Suggestions"/> property with word suggestions.
/// </summary>
/// <remarks>
/// <see cref="TestWord"/> must have been called before calling this method.
/// </remarks>
/// <seealso cref="Suggestions()"/>
/// <seealso cref="TestWord"/>
void Suggest();
/// <summary>
/// Deletes the CurrentWord from the Text Property
/// </summary>
/// <remarks>
/// Note, calling ReplaceWord with the ReplacementWord property set to
/// an empty string has the same behavior as DeleteWord.
/// </remarks>
void DeleteWord();
/// <summary>
/// Calculates the minimum number of change, inserts or deletes
/// required to change firstWord into secondWord
/// </summary>
/// <param name="source" type="string">
/// <para>
/// The first word to calculate
/// </para>
/// </param>
/// <param name="target" type="string">
/// <para>
/// The second word to calculate
/// </para>
/// </param>
/// <param name="positionPriority" type="bool">
/// <para>
/// set to true if the first and last char should have priority
/// </para>
/// </param>
/// <returns>
/// The number of edits to make firstWord equal secondWord
/// </returns>
int EditDistance(string source, string target, bool positionPriority);
/// <summary>
/// Calculates the minimum number of change, inserts or deletes
/// required to change firstWord into secondWord
/// </summary>
/// <param name="source" type="string">
/// <para>
/// The first word to calculate
/// </para>
/// </param>
/// <param name="target" type="string">
/// <para>
/// The second word to calculate
/// </para>
/// </param>
/// <returns>
/// The number of edits to make firstWord equal secondWord
/// </returns>
/// <remarks>
/// This method automatically gives priority to matching the first and last char
/// </remarks>
int EditDistance(string source, string target);
/// <summary>
/// Gets the word index from the text index. Use this method to
/// find a word based on the text position.
/// </summary>
/// <param name="textIndex">
/// <para>
/// The index to search for
/// </para>
/// </param>
/// <returns>
/// The word index that the text index falls on
/// </returns>
int GetWordIndexFromTextIndex(int textIndex);
/// <summary>
/// Ignores all instances of the CurrentWord in the Text Property
/// </summary>
void IgnoreAllWord();
/// <summary>
/// Ignores the instances of the CurrentWord in the Text Property.
/// </summary>
/// <remarks>
/// Must call SpellCheck after call this method to resume spell checking.
/// Forces the IgnoredWord event on Speller plug-in. Host application must handle.
/// </remarks>
void IgnoreWord();
/// <summary>
/// Replaces all instances of the CurrentWord in the Text Property
/// </summary>
void ReplaceAllWord();
/// <summary>
/// Replaces all instances of the CurrentWord in the Text Property
/// </summary>
/// <param name="replacementWord" type="string">
/// <para>
/// The word to replace the CurrentWord with
/// </para>
/// </param>
void ReplaceAllWord(string replacementWord);
/// <summary>
/// Replaces the instances of the CurrentWord in the Text Property
/// </summary>
void ReplaceWord();
/// <summary>
/// Replaces the instances of the CurrentWord in the Text Property
/// </summary>
/// <param name="replacementWord" type="string">
/// <para>
/// The word to replace the CurrentWord with
/// </para>
/// </param>
void ReplaceWord(string replacementWord);
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position.
/// </summary>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="WordIndex"/>
bool SpellCheck();
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position. This overload takes in the
/// WordIndex to start checking from.
/// </summary>
/// <param name="startWordIndex" type="int">
/// <para>
/// The index of the word to start checking from.
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="WordIndex"/>
bool SpellCheck(int startWordIndex);
/// <summary>
/// Spell checks a range of words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position and ending at endWordIndex.
/// </summary>
/// <param name="startWordIndex" type="int">
/// <para>
/// The index of the word to start checking from.
/// </para>
/// </param>
/// <param name="endWordIndex" type="int">
/// <para>
/// The index of the word to end checking with.
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="WordIndex"/>
bool SpellCheck(int startWordIndex, int endWordIndex);
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position. This overload takes in the
/// text to spell check
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The text to spell check
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="WordIndex"/>
bool SpellCheck(string text);
/// <summary>
/// Spell checks the words in the <see cref="Text"/> property starting
/// at the <see cref="WordIndex"/> position. This overload takes in
/// the text to check and the WordIndex to start checking from.
/// </summary>
/// <param name="text" type="string">
/// <para>
/// The text to spell check
/// </para>
/// </param>
/// <param name="startWordIndex" type="int">
/// <para>
/// The index of the word to start checking from
/// </para>
/// </param>
/// <returns>
/// Returns true if there is a word found in the text
/// that is not in the dictionaries
/// </returns>
/// <seealso cref="WordIndex"/>
bool SpellCheck(string text, int startWordIndex);
/// <summary>
/// Event fired for each word found.
/// </summary>
event WordCheckerHandler WordChecker;
/// <summary>
/// Event fired for each word found. The return value of the callback function is used to stop the checking
/// process immediately.
/// </summary>
event WordCheckerStopHandler WordCheckerStop;
/// <summary>
/// Event fired once the word checking is done.
/// </summary>
event WordCheckerFinishedHandler WordCheckerFinished;
/// <summary>
/// Event fired if the suer has right clicked the word and the caret has moved.
/// </summary>
/// <remarks>
/// This event is later than
/// ContextMenu because it is necessary to being delayed to set the caret to the final position before
/// an attached context menu opens.
/// </remarks>
event WordOnContextHandler WordOnContext;
/// <summary>
/// Remove the highlighted sections from the whole document.
/// </summary>
void RemoveWordCheckingHighlights();
/// <summary>
/// Checks the complete document and highlight any wrong word using default highlight style.
/// </summary>
void DoWordCheckingHighlights();
/// <summary>
/// Checks the complete document and highlight any wrong word. Search and spell call back on word base.</summary>
/// <remarks>
/// The method calls a callback method the host application
/// must provide and which returns a boolean value to control the behavior of the highlighter.
/// </remarks>
/// <param name="highLightStyle">The style used to mark wrong words</param>
void DoWordCheckingHighlights(IHighLightStyle highLightStyle);
/// <summary>
/// Checks the complete document and highlight any wrong word. Search and spell call back on word base.
/// </summary>
/// <remarks>
/// The method calls a callback method the host application
/// must provide and which returns a boolean value to control the behavior of the highlighter.
/// </remarks>
/// <param name="highLightStyle">The style used to mark wrong word</param>
/// <param name="backgroundService">If true the service runs as a endless background process until the WordStop callback handler returns true.</param>
void DoWordCheckingHighlights(IHighLightStyle highLightStyle, bool backgroundService);
/// <summary>
/// Checks the complete document and highlight any wrong word. Search and spell call back on sentence base.
/// </summary>
/// <param name="highLightStyle"></param>
void DoBlockCheckingHighlights(IHighLightStyle highLightStyle);
/// <summary>
/// Checks the complete document interactively and tags the current word in default selection style.
/// </summary>
void DoBlockCheckingSelected();
/// <summary>
/// Checks the complete document and select any wrong word with the standard selection.
/// </summary>
void DoWordCheckingSelected();
/// <summary>
/// Returns the collection of misspelled words.
/// </summary>
IList MisSpelledWords { get; }
# region NetSpell Properties
/// <summary>
/// Gets or sets a value that activates the internal NetSpell spell checker.
/// </summary>
bool CheckInternal
{
get;
set;
}
/// <summary>
/// The suggestion strategy to use when generating suggestions
/// </summary>
SuggestionEnum SuggestionMode
{
set;
get;
}
/// <summary>
/// An array of word suggestions for the correct spelling of the misspelled word
/// </summary>
/// <seealso cref="Suggest()"/>
/// <seealso cref="SpellCheck()"/>
List<string> Suggestions
{
get;
}
/// <summary>
/// The text to spell check
/// </summary>
string Text
{
get;
}
/// <summary>
/// TextIndex is the index of the current text being spell checked
/// </summary>
int TextIndex
{
get;
}
/// <summary>
/// The number of words being spell checked
/// </summary>
int WordCount
{
get;
}
/// <summary>
/// WordIndex is the index of the current word being spell checked
/// </summary>
int WordIndex
{
get;
}
/// <summary>
/// The WordDictionary object to use when spell checking.
/// </summary>
WordDictionary Dictionary
{
get;
}
# endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Monitoring.Autoscale;
using Microsoft.WindowsAzure.Management.Monitoring.Autoscale.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Microsoft.WindowsAzure.Management.Monitoring.Autoscale
{
/// <summary>
/// Operations for managing the autoscale settings.
/// </summary>
internal partial class SettingOperations : IServiceOperations<AutoscaleClient>, ISettingOperations
{
/// <summary>
/// Initializes a new instance of the SettingOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal SettingOperations(AutoscaleClient client)
{
this._client = client;
}
private AutoscaleClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.Monitoring.Autoscale.AutoscaleClient.
/// </summary>
public AutoscaleClient Client
{
get { return this._client; }
}
/// <param name='resourceId'>
/// The resource ID.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> CreateOrUpdateAsync(string resourceId, AutoscaleSettingCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
tracingParameters.Add("parameters", parameters);
Tracing.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/monitoring/autoscalesettings?resourceId=" + resourceId;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
if (parameters.Setting != null)
{
JObject settingValue = new JObject();
requestDoc = settingValue;
if (parameters.Setting.Profiles != null)
{
JArray profilesArray = new JArray();
foreach (AutoscaleProfile profilesItem in parameters.Setting.Profiles)
{
JObject autoscaleProfileValue = new JObject();
profilesArray.Add(autoscaleProfileValue);
if (profilesItem.Name != null)
{
autoscaleProfileValue["Name"] = profilesItem.Name;
}
if (profilesItem.Capacity != null)
{
JObject capacityValue = new JObject();
autoscaleProfileValue["Capacity"] = capacityValue;
if (profilesItem.Capacity.Minimum != null)
{
capacityValue["Minimum"] = profilesItem.Capacity.Minimum;
}
if (profilesItem.Capacity.Maximum != null)
{
capacityValue["Maximum"] = profilesItem.Capacity.Maximum;
}
if (profilesItem.Capacity.Default != null)
{
capacityValue["Default"] = profilesItem.Capacity.Default;
}
}
if (profilesItem.Rules != null)
{
JArray rulesArray = new JArray();
foreach (ScaleRule rulesItem in profilesItem.Rules)
{
JObject scaleRuleValue = new JObject();
rulesArray.Add(scaleRuleValue);
if (rulesItem.MetricTrigger != null)
{
JObject metricTriggerValue = new JObject();
scaleRuleValue["MetricTrigger"] = metricTriggerValue;
if (rulesItem.MetricTrigger.MetricName != null)
{
metricTriggerValue["MetricName"] = rulesItem.MetricTrigger.MetricName;
}
if (rulesItem.MetricTrigger.MetricNamespace != null)
{
metricTriggerValue["MetricNamespace"] = rulesItem.MetricTrigger.MetricNamespace;
}
if (rulesItem.MetricTrigger.MetricSource != null)
{
metricTriggerValue["MetricSource"] = rulesItem.MetricTrigger.MetricSource;
}
metricTriggerValue["TimeGrain"] = TypeConversion.To8601String(rulesItem.MetricTrigger.TimeGrain);
metricTriggerValue["Statistic"] = rulesItem.MetricTrigger.Statistic.ToString();
metricTriggerValue["TimeWindow"] = TypeConversion.To8601String(rulesItem.MetricTrigger.TimeWindow);
metricTriggerValue["TimeAggregation"] = rulesItem.MetricTrigger.TimeAggregation.ToString();
metricTriggerValue["Operator"] = rulesItem.MetricTrigger.Operator.ToString();
metricTriggerValue["Threshold"] = rulesItem.MetricTrigger.Threshold;
}
if (rulesItem.ScaleAction != null)
{
JObject scaleActionValue = new JObject();
scaleRuleValue["ScaleAction"] = scaleActionValue;
scaleActionValue["Direction"] = rulesItem.ScaleAction.Direction.ToString();
scaleActionValue["Type"] = rulesItem.ScaleAction.Type.ToString();
if (rulesItem.ScaleAction.Value != null)
{
scaleActionValue["Value"] = rulesItem.ScaleAction.Value;
}
scaleActionValue["Cooldown"] = TypeConversion.To8601String(rulesItem.ScaleAction.Cooldown);
}
}
autoscaleProfileValue["Rules"] = rulesArray;
}
if (profilesItem.FixedDate != null)
{
JObject fixedDateValue = new JObject();
autoscaleProfileValue["FixedDate"] = fixedDateValue;
if (profilesItem.FixedDate.TimeZone != null)
{
fixedDateValue["TimeZone"] = profilesItem.FixedDate.TimeZone;
}
fixedDateValue["Start"] = profilesItem.FixedDate.Start;
fixedDateValue["End"] = profilesItem.FixedDate.End;
}
if (profilesItem.Recurrence != null)
{
JObject recurrenceValue = new JObject();
autoscaleProfileValue["Recurrence"] = recurrenceValue;
recurrenceValue["Frequency"] = profilesItem.Recurrence.Frequency.ToString();
if (profilesItem.Recurrence.Schedule != null)
{
JObject scheduleValue = new JObject();
recurrenceValue["Schedule"] = scheduleValue;
if (profilesItem.Recurrence.Schedule.TimeZone != null)
{
scheduleValue["TimeZone"] = profilesItem.Recurrence.Schedule.TimeZone;
}
if (profilesItem.Recurrence.Schedule.Days != null)
{
JArray daysArray = new JArray();
foreach (string daysItem in profilesItem.Recurrence.Schedule.Days)
{
daysArray.Add(daysItem);
}
scheduleValue["Days"] = daysArray;
}
if (profilesItem.Recurrence.Schedule.Hours != null)
{
JArray hoursArray = new JArray();
foreach (int hoursItem in profilesItem.Recurrence.Schedule.Hours)
{
hoursArray.Add(hoursItem);
}
scheduleValue["Hours"] = hoursArray;
}
if (profilesItem.Recurrence.Schedule.Minutes != null)
{
JArray minutesArray = new JArray();
foreach (int minutesItem in profilesItem.Recurrence.Schedule.Minutes)
{
minutesArray.Add(minutesItem);
}
scheduleValue["Minutes"] = minutesArray;
}
}
}
}
settingValue["Profiles"] = profilesArray;
}
settingValue["Enabled"] = parameters.Setting.Enabled;
}
requestContent = requestDoc.ToString(Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='resourceId'>
/// The resource ID.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<OperationResponse> DeleteAsync(string resourceId, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/monitoring/autoscalesettings?resourceId=" + resourceId;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <param name='resourceId'>
/// The resource ID.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AutoscaleSettingGetResponse> GetAsync(string resourceId, CancellationToken cancellationToken)
{
// Validate
if (resourceId == null)
{
throw new ArgumentNullException("resourceId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceId", resourceId);
Tracing.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri + "/" + this.Client.Credentials.SubscriptionId + "/services/monitoring/autoscalesettings?resourceId=" + resourceId;
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2013-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Json);
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AutoscaleSettingGetResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new AutoscaleSettingGetResponse();
JToken responseDoc = JToken.Parse(responseContent);
if (responseDoc != null)
{
AutoscaleSetting settingInstance = new AutoscaleSetting();
result.Setting = settingInstance;
JArray profilesArray = (JArray)responseDoc["Profiles"];
if (profilesArray != null)
{
foreach (JToken profilesValue in profilesArray)
{
AutoscaleProfile autoscaleProfileInstance = new AutoscaleProfile();
settingInstance.Profiles.Add(autoscaleProfileInstance);
JToken nameValue = profilesValue["Name"];
if (nameValue != null)
{
string nameInstance = (string)nameValue;
autoscaleProfileInstance.Name = nameInstance;
}
JToken capacityValue = profilesValue["Capacity"];
if (capacityValue != null)
{
ScaleCapacity capacityInstance = new ScaleCapacity();
autoscaleProfileInstance.Capacity = capacityInstance;
JToken minimumValue = capacityValue["Minimum"];
if (minimumValue != null)
{
string minimumInstance = (string)minimumValue;
capacityInstance.Minimum = minimumInstance;
}
JToken maximumValue = capacityValue["Maximum"];
if (maximumValue != null)
{
string maximumInstance = (string)maximumValue;
capacityInstance.Maximum = maximumInstance;
}
JToken defaultValue = capacityValue["Default"];
if (defaultValue != null)
{
string defaultInstance = (string)defaultValue;
capacityInstance.Default = defaultInstance;
}
}
JArray rulesArray = (JArray)profilesValue["Rules"];
if (rulesArray != null)
{
foreach (JToken rulesValue in rulesArray)
{
ScaleRule scaleRuleInstance = new ScaleRule();
autoscaleProfileInstance.Rules.Add(scaleRuleInstance);
JToken metricTriggerValue = rulesValue["MetricTrigger"];
if (metricTriggerValue != null)
{
MetricTrigger metricTriggerInstance = new MetricTrigger();
scaleRuleInstance.MetricTrigger = metricTriggerInstance;
JToken metricNameValue = metricTriggerValue["MetricName"];
if (metricNameValue != null)
{
string metricNameInstance = (string)metricNameValue;
metricTriggerInstance.MetricName = metricNameInstance;
}
JToken metricNamespaceValue = metricTriggerValue["MetricNamespace"];
if (metricNamespaceValue != null)
{
string metricNamespaceInstance = (string)metricNamespaceValue;
metricTriggerInstance.MetricNamespace = metricNamespaceInstance;
}
JToken metricSourceValue = metricTriggerValue["MetricSource"];
if (metricSourceValue != null)
{
string metricSourceInstance = (string)metricSourceValue;
metricTriggerInstance.MetricSource = metricSourceInstance;
}
JToken timeGrainValue = metricTriggerValue["TimeGrain"];
if (timeGrainValue != null)
{
TimeSpan timeGrainInstance = TypeConversion.From8601TimeSpan((string)timeGrainValue);
metricTriggerInstance.TimeGrain = timeGrainInstance;
}
JToken statisticValue = metricTriggerValue["Statistic"];
if (statisticValue != null)
{
// how
MetricStatisticType statisticInstance = (MetricStatisticType)Enum.Parse(typeof(MetricStatisticType), (string)statisticValue, false);
metricTriggerInstance.Statistic = statisticInstance;
}
JToken timeWindowValue = metricTriggerValue["TimeWindow"];
if (timeWindowValue != null)
{
TimeSpan timeWindowInstance = TypeConversion.From8601TimeSpan((string)timeWindowValue);
metricTriggerInstance.TimeWindow = timeWindowInstance;
}
JToken timeAggregationValue = metricTriggerValue["TimeAggregation"];
if (timeAggregationValue != null)
{
// how
TimeAggregationType timeAggregationInstance = (TimeAggregationType)Enum.Parse(typeof(TimeAggregationType), (string)timeAggregationValue, false);
metricTriggerInstance.TimeAggregation = timeAggregationInstance;
}
JToken operatorValue = metricTriggerValue["Operator"];
if (operatorValue != null)
{
// how
ComparisonOperationType operatorInstance = (ComparisonOperationType)Enum.Parse(typeof(ComparisonOperationType), (string)operatorValue, false);
metricTriggerInstance.Operator = operatorInstance;
}
JToken thresholdValue = metricTriggerValue["Threshold"];
if (thresholdValue != null)
{
double thresholdInstance = (double)thresholdValue;
metricTriggerInstance.Threshold = thresholdInstance;
}
}
JToken scaleActionValue = rulesValue["ScaleAction"];
if (scaleActionValue != null)
{
ScaleAction scaleActionInstance = new ScaleAction();
scaleRuleInstance.ScaleAction = scaleActionInstance;
JToken directionValue = scaleActionValue["Direction"];
if (directionValue != null)
{
// how
ScaleDirection directionInstance = (ScaleDirection)Enum.Parse(typeof(ScaleDirection), (string)directionValue, false);
scaleActionInstance.Direction = directionInstance;
}
JToken typeValue = scaleActionValue["Type"];
if (typeValue != null)
{
// how
ScaleType typeInstance = (ScaleType)Enum.Parse(typeof(ScaleType), (string)typeValue, false);
scaleActionInstance.Type = typeInstance;
}
JToken valueValue = scaleActionValue["Value"];
if (valueValue != null)
{
string valueInstance = (string)valueValue;
scaleActionInstance.Value = valueInstance;
}
JToken cooldownValue = scaleActionValue["Cooldown"];
if (cooldownValue != null)
{
TimeSpan cooldownInstance = TypeConversion.From8601TimeSpan((string)cooldownValue);
scaleActionInstance.Cooldown = cooldownInstance;
}
}
}
}
JToken fixedDateValue = profilesValue["FixedDate"];
if (fixedDateValue != null)
{
TimeWindow fixedDateInstance = new TimeWindow();
autoscaleProfileInstance.FixedDate = fixedDateInstance;
JToken timeZoneValue = fixedDateValue["TimeZone"];
if (timeZoneValue != null)
{
string timeZoneInstance = (string)timeZoneValue;
fixedDateInstance.TimeZone = timeZoneInstance;
}
JToken startValue = fixedDateValue["Start"];
if (startValue != null)
{
DateTime startInstance = (DateTime)startValue;
fixedDateInstance.Start = startInstance;
}
JToken endValue = fixedDateValue["End"];
if (endValue != null)
{
DateTime endInstance = (DateTime)endValue;
fixedDateInstance.End = endInstance;
}
}
JToken recurrenceValue = profilesValue["Recurrence"];
if (recurrenceValue != null)
{
Recurrence recurrenceInstance = new Recurrence();
autoscaleProfileInstance.Recurrence = recurrenceInstance;
JToken frequencyValue = recurrenceValue["Frequency"];
if (frequencyValue != null)
{
// how
RecurrenceFrequency frequencyInstance = (RecurrenceFrequency)Enum.Parse(typeof(RecurrenceFrequency), (string)frequencyValue, false);
recurrenceInstance.Frequency = frequencyInstance;
}
JToken scheduleValue = recurrenceValue["Schedule"];
if (scheduleValue != null)
{
RecurrentSchedule scheduleInstance = new RecurrentSchedule();
recurrenceInstance.Schedule = scheduleInstance;
JToken timeZoneValue2 = scheduleValue["TimeZone"];
if (timeZoneValue2 != null)
{
string timeZoneInstance2 = (string)timeZoneValue2;
scheduleInstance.TimeZone = timeZoneInstance2;
}
JArray daysArray = (JArray)scheduleValue["Days"];
if (daysArray != null)
{
foreach (JToken daysValue in daysArray)
{
scheduleInstance.Days.Add((string)daysValue);
}
}
JArray hoursArray = (JArray)scheduleValue["Hours"];
if (hoursArray != null)
{
foreach (JToken hoursValue in hoursArray)
{
scheduleInstance.Hours.Add((int)hoursValue);
}
}
JArray minutesArray = (JArray)scheduleValue["Minutes"];
if (minutesArray != null)
{
foreach (JToken minutesValue in minutesArray)
{
scheduleInstance.Minutes.Add((int)minutesValue);
}
}
}
}
}
}
JToken enabledValue = responseDoc["Enabled"];
if (enabledValue != null)
{
bool enabledInstance = (bool)enabledValue;
settingInstance.Enabled = enabledInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* Copyright 2013 Stanislav Muhametsin. All rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using CILAssemblyManipulator.Logical.Implementation;
using System.Text;
using System.Collections.Generic;
using CILAssemblyManipulator.Physical;
using CollectionsWithRoles.API;
using System.Runtime.InteropServices;
using CommonUtils;
namespace CILAssemblyManipulator.Logical
{
/// <summary>
/// This class contains miscellaneous utility methods related to CIL assembly emitting.
/// </summary>
public static class LogicalUtils
{
internal static readonly System.Reflection.Assembly NATIVE_MSCORLIB = typeof( Object )
#if WINDOWS_PHONE_APP
.GetTypeInfo()
#endif
.Assembly;
/// <summary>
/// Returns <see cref="ElementKind"/> of the given native type.
/// </summary>
/// <param name="type">The native type.</param>
/// <returns><c>null</c> if <paramref name="type"/> is not element type, otherwise <see cref="ElementKind"/> of the <paramref name="type"/>.</returns>
public static ElementKind? GetElementKind( this Type type )
{
if ( type.IsArray )
{
return ElementKind.Array;
}
else if ( type.IsPointer )
{
return ElementKind.Pointer;
}
else if ( type.IsByRef )
{
return ElementKind.Reference;
}
else
{
return null;
}
}
/// <summary>
/// Checks whether <paramref name="type"/> is not <c>null</c> and is vector array type.
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns><c>true</c> if <paramref name="type"/> is not <c>null</c> and is vector array type; <c>false</c> otherwise.</returns>
public static Boolean IsVectorArray( this Type type )
{
return type != null && type.IsArray && type.Name.EndsWith( "[]" );
}
/// <summary>
/// Checks whether <paramref name="type"/> is not <c>null</c> and is multi-dimensional array type.
/// </summary>
/// <param name="type">The type to check.</param>
/// <returns><c>true</c> if <paramref name="type"/> is not <c>null</c> and is multi-dimensional array type; <c>false</c> otherwise.</returns>
public static Boolean IsMultiDimensionalArray( this Type type )
{
return type != null && type.IsArray && type.Name.EndsWith( "]" ) && type.Name[type.Name.Length - 2] != '[';
}
// /// <summary>
// /// Helper method to extact full public key from a private key CAPI BLOB.
// /// </summary>
// /// <param name="privateOrPublicKeyBLOB">The private or public key BLOB in CAPI format (basically a .snk file).</param>
// /// <param name="signingAlgorithm">The signing algorithm to use.</param>
// /// <returns>The full public key of the assembly that is signed with <paramref name="privateOrPublicKeyBLOB"/> using <paramref name="signingAlgorithm"/> as signing algorithm.</returns>
// public static Byte[] ExtractPublicKey( Byte[] privateOrPublicKeyBLOB, AssemblyHashAlgorithm signingAlgorithm )
// {
// Byte[] pk;
// AssemblyHashAlgorithm dummy;
// CILAssemblyManipulator.Logical.Implementation.Physical.CryptoUtils.CreateSigningInformationFromKeyBLOB( privateOrPublicKeyBLOB, signingAlgorithm, out pk, out dummy );
// return pk;
// }
// internal struct TypeParseResult
// {
// internal readonly CILAssemblyName assemblyName;
// internal readonly String nameSpace;
// internal readonly String typeName;
// internal readonly IList<String> genericArguments;
// internal readonly IList<Tuple<ElementKind, GeneralArrayInfo>> elementInfo;
// internal readonly IList<String> nestedTypes;
// internal TypeParseResult( CILAssemblyName an, String ns, String tn, IList<String> gArgs, IList<Tuple<ElementKind, GeneralArrayInfo>> elInfo, IList<String> nt )
// {
// this.assemblyName = an;
// this.nameSpace = ns;
// this.typeName = tn;
// this.genericArguments = gArgs;
// this.elementInfo = elInfo;
// this.nestedTypes = nt;
// }
// }
// internal static TypeParseResult ParseTypeString( String typeStr )
// {
// // If there is an assembly name, there will be ", " but not "\, " in type string.
// var an = ParseAssemblyNameFromTypeString( ref typeStr );
// if ( String.IsNullOrEmpty( typeStr ) )
// {
// // Assembly name but no type name?
// throw new ArgumentException( "The string \"" + typeStr + "\" does not contain a type name." );
// }
// // Find next escapable but not escaped character: '&' (by-ref), '*' (pointer), '[' (array or generic type)
// List<Tuple<ElementKind, GeneralArrayInfo>> elInfo = null;
// List<String> gArgs = null;
// var curIdx = IndexOfNonEscaped( typeStr, 0, CHARS_ENDING_SIMPLE_TYPENAME );
// if ( curIdx >= 0 )
// {
// // Element kind or generic parameters present
// var tmp = curIdx;
// while ( tmp >= 0 )
// {
// switch ( typeStr[tmp] )
// {
// case '&':
// if ( elInfo == null )
// {
// elInfo = new List<Tuple<ElementKind, GeneralArrayInfo>>();
// }
// elInfo.Add( Tuple.Create<ElementKind, GeneralArrayInfo>( ElementKind.Reference, null ) );
// break;
// case '*':
// if ( elInfo == null )
// {
// elInfo = new List<Tuple<ElementKind, GeneralArrayInfo>>();
// }
// elInfo.Add( Tuple.Create<ElementKind, GeneralArrayInfo>( ElementKind.Pointer, null ) );
// break;
// case '[':
// // Either array or generic type.
// Int32 arrayRank;
// var tmp2 = tmp;
// var isArray = IsArray( typeStr, ref tmp2, out arrayRank );
// if ( isArray )
// {
// if ( elInfo == null )
// {
// elInfo = new List<Tuple<ElementKind, GeneralArrayInfo>>();
// }
// // TODO ArrayInfo
// elInfo.Add( Tuple.Create( ElementKind.Array, ReadArrayInfo( typeStr, tmp, tmp2, arrayRank ) ) );
// tmp = tmp2;
// }
// else
// {
// tmp2 = tmp + 1;
// // Generic type. Iterate through, remember [] -depth, and read generic argument strings
// if ( gArgs != null )
// {
// // Specifying generic types x2
// throw new ArgumentException( "Invalid type string \"" + typeStr + "\". Generic arguments were specified more than once." );
// }
// gArgs = new List<String>();
// var curBracketDepth = 0;
// while ( ++tmp < typeStr.Length && curBracketDepth >= 0 )
// {
// // Skip escaped characters
// if ( typeStr[tmp - 1] != '\\' )
// {
// var ch = typeStr[tmp];
// if ( ch == '[' )
// {
// ++curBracketDepth;
// }
// else if ( ch == ']' )
// {
// --curBracketDepth;
// if ( curBracketDepth < 0 )
// {
// // Add last argument
// gArgs.Add( UnescapeSomeString( typeStr.Substring( tmp2, tmp - tmp2 ) ) );
// }
// }
// else if ( ch == ',' && curBracketDepth == 0 )
// {
// // "Top-level" comma, meaning generic argument separator.
// gArgs.Add( UnescapeSomeString( typeStr.Substring( tmp2, tmp - tmp2 ) ) );
// tmp2 = tmp + 1;
// }
// }
// }
// if ( curBracketDepth >= 0 )
// {
// throw new ArgumentException( "Invalid type string \"" + typeStr + "\". String ended before all generic arguments were specified." );
// }
// if ( gArgs.Count == 0 )
// {
// throw new Exception( "Internal error in type parsing, no generic arguments added when should have to." );
// }
// }
// break;
// }
// tmp = IndexOfNonEscaped( typeStr, tmp + 1, CHARS_ENDING_SIMPLE_TYPENAME );
// }
// typeStr = typeStr.Substring( 0, curIdx );
// }
// // Construct nested type information
// String ns, tn;
// List<String> nt = null;
// var nSep = IndexOfNonEscaped( typeStr, 0, '+' );
// if ( nSep >= 0 && nSep < typeStr.Length - 1 )
// {
// // Nested type
// nt = new List<String>();
// var min = nSep + 1;
// Int32 max;
// do
// {
// max = IndexOfNonEscaped( typeStr, min, '+' );
// if ( max < 0 )
// {
// max = typeStr.Length;
// }
// nt.Add( UnescapeSomeString( typeStr.Substring( min, max - min ) ) );
// min = max + 1;
// } while ( min < typeStr.Length );
// typeStr = typeStr.Substring( 0, nSep );
// }
// // Parse namespace information
// nSep = typeStr.LastIndexOf( '.' );
// ns = nSep == -1 ? null : typeStr.Substring( 0, nSep );
// tn = nSep == -1 ? typeStr : typeStr.Substring( nSep + 1 );
// return new TypeParseResult( an, UnescapeSomeString( ns ), UnescapeSomeString( tn ), gArgs, elInfo, nt );
// }
// internal static String NamespaceAndTypeName( String ns, String tn )
// {
// return String.IsNullOrEmpty( ns ) ? tn : ( ns + '.' + tn );
// }
// private static Boolean IsArray( String typeStr, ref Int32 idx, out Int32 rank )
// {
// // Array type will either have ']' as next character, or numbers, commas, and dots before ']', nothing else.
// var max = IndexOfNonEscaped( typeStr, idx, ']' );
// var isArray = true;
// rank = 1;
// for ( var i = idx; i < max; ++i )
// {
// var ch = typeStr[i];
// if ( !Char.IsDigit( ch ) || ch != '.' || ch != ',' || ch != '*' )
// {
// isArray = false;
// break;
// }
// else if ( ch == ',' )
// {
// ++rank;
// }
// }
// idx = max;
// return isArray;
// }
// // Start idx = index of '[', End idx = index of ']'
// private static GeneralArrayInfo ReadArrayInfo( String typeStr, Int32 startIdx, Int32 endIdx, Int32 rank )
// {
// GeneralArrayInfo result;
// if ( startIdx == endIdx - 1 )
// {
// // Vector array
// result = null;
// }
// else
// {
// // General array
// ++startIdx;
// var sizes = new Int32[rank];
// var sizeIdx = 0;
// var loBounds = new Int32[rank];
// var loBoundIdx = 0;
// // Check for special case - rank 1, no sizes, no lower bounds (is '[*]').
// if ( startIdx != endIdx - 1 || typeStr[startIdx] != '*' )
// {
// var curIdx = startIdx;
// while ( curIdx <= endIdx )
// {
// switch ( typeStr[curIdx] )
// {
// case ',':
// case ']':
// // End of dimension
// if ( startIdx != curIdx )
// {
// // Size specified
// // Implicitly add zero lower bound if needed
// if ( sizeIdx == loBoundIdx )
// {
// loBounds[loBoundIdx++] = 0;
// }
// // Then save size
// sizes[sizeIdx++] = Int32.Parse( typeStr.Substring( startIdx, curIdx - startIdx ) );
// }
// startIdx = curIdx + 1;
// break;
// case '.':
// if ( startIdx != curIdx )
// {
// // End of lower bound
// loBounds[loBoundIdx++] = Int32.Parse( typeStr.Substring( startIdx, curIdx - startIdx ) );
// }
// startIdx = curIdx + 1;
// break;
// }
// ++curIdx;
// }
// }
// // Create actual size and lower bounds arrays
// var actualSizes = new Int32[sizeIdx];
// Array.Copy( sizes, actualSizes, sizeIdx );
// var actualLoBounds = new Int32[loBoundIdx];
// Array.Copy( loBounds, actualLoBounds, loBoundIdx );
// result = new GeneralArrayInfo( rank, actualSizes, actualLoBounds );
// }
// return result;
// }
// private static CILAssemblyName ParseAssemblyNameFromTypeString( ref String str )
// {
// var typeStrMax = 0;
// var curIdx = -1;
// while ( typeStrMax < str.Length
// && ( curIdx = str.IndexOf( TYPE_ASSEMBLY_SEPARATOR, typeStrMax ) ) > 0
// && str[curIdx - 1] == ESCAPE_CHAR )
// {
// typeStrMax = curIdx + TYPE_ASSEMBLY_SEPARATOR.Length;
// }
// CILAssemblyName an;
// if ( curIdx < 0 || typeStrMax >= str.Length )
// {
// // No assembly name present
// an = null;
// }
// else
// {
// // Parse assembly name and set type string to hold actual type string
// an = CILAssemblyName.Parse( str.Substring( curIdx + TYPE_ASSEMBLY_SEPARATOR.Length ) );
// str = str.Substring( 0, curIdx );
// }
// return an;
// }
// private static Int32 IndexOfNonEscaped( String str, Int32 startIdx, Char[] chars )
// {
// var chIdx = -1;
// while ( startIdx < str.Length
// && ( chIdx = str.IndexOfAny( chars, startIdx ) ) > 0
// && str[chIdx - 1] == ESCAPE_CHAR )
// {
// startIdx = chIdx + 1;
// }
// return chIdx < 0 || startIdx >= str.Length ? -1 : chIdx;
// }
// private static Int32 IndexOfNonEscaped( String str, Int32 startIdx, Char ch )
// {
// var chIdx = -1;
// while ( startIdx < str.Length
// && ( chIdx = str.IndexOf( ch, startIdx ) ) > 0
// && str[chIdx - 1] == ESCAPE_CHAR )
// {
// startIdx = chIdx + 1;
// }
// return chIdx < 0 || startIdx >= str.Length ? -1 : chIdx;
// }
internal static String CreateTypeString( CILType type, Boolean appendGArgs )
{
String typeString;
if ( type == null )
{
typeString = null;
}
else
{
var builder = new StringBuilder();
CreateTypeStringCore( type, type.Module, builder, appendGArgs );
typeString = builder.ToString();
}
return typeString;
}
//private static void CreateTypeString( CILTypeBase type, CILModule moduleBeingEmitted, StringBuilder builder, Boolean appendGArgs, Boolean isGParam )
//{
// var needsAssembly = moduleBeingEmitted != null && !moduleBeingEmitted.Assembly.Equals( type.Module.Assembly );
// if ( isGParam && needsAssembly )
// {
// builder.Append( '[' );
// }
// CreateTypeStringCore( type, moduleBeingEmitted, builder, appendGArgs );
// if ( needsAssembly )
// {
// builder
// .Append( TYPE_ASSEMBLY_SEPARATOR )
// .Append( type.Module.Assembly.Name.ToString() ); // Assembly name will be escaped.
// if ( isGParam )
// {
// builder.Append( ']' );
// }
// }
//}
private static void CreateTypeStringCore( CILTypeBase type, CILModule moduleBeingEmitted, StringBuilder builder, Boolean appendGArgs )
{
var eKind = type.GetElementKind();
if ( eKind.HasValue )
{
CreateTypeStringCore( type.GetElementType(), moduleBeingEmitted, builder, appendGArgs );
CreateElementKindString( eKind.Value, ( (CILType) type ).ArrayInformation, builder );
}
else if ( appendGArgs && type.IsGenericType() && !type.ContainsGenericParameters() )
{
var typee = (CILType) type;
CreateTypeStringCore( typee.GenericDefinition, moduleBeingEmitted, builder, false );
builder.Append( '[' );
var gArgs = typee.GenericArguments;
for ( var i = 0; i < gArgs.Count; ++i )
{
var gArg = gArgs[i];
var needsAssembly = moduleBeingEmitted != null
&& gArg.TypeKind != TypeKind.MethodSignature
&& !moduleBeingEmitted.Assembly.Equals( gArg.Module.Assembly );
if ( needsAssembly )
{
builder.Append( '[' );
}
CreateTypeStringCore( gArg, moduleBeingEmitted, builder, true );
if ( needsAssembly )
{
builder
.AppendAssemblyNameToTypeString( gArg.Module.Assembly.Name.ToString() ) // Assembly name will be escaped.
.Append( ']' );
}
if ( i < gArgs.Count - 1 )
{
builder.Append( ',' );
}
}
builder.Append( ']' );
}
else
{
switch ( type.TypeKind )
{
case TypeKind.Type:
var typee = (CILType) type;
var dt = typee.DeclaringType;
if ( dt == null )
{
var ns = typee.Namespace;
if ( !String.IsNullOrEmpty( ns ) )
{
builder.Append( ns.EscapeCILTypeString() ).Append( Miscellaneous.NAMESPACE_SEPARATOR );
}
}
else
{
CreateTypeStringCore( dt, moduleBeingEmitted, builder, false );
builder.Append( Miscellaneous.NESTED_TYPE_SEPARATOR );
}
builder.Append( typee.Name.EscapeCILTypeString() );
break;
case TypeKind.MethodSignature:
builder.Append( type.ToString() );
break;
case TypeKind.TypeParameter:
builder.Append( ( (CILTypeParameter) type ).Name );
break;
}
}
}
internal static String CreateElementKindString( ElementKind elementKind, GeneralArrayInfo arrayInfo )
{
var builder = new StringBuilder();
CreateElementKindString( elementKind, arrayInfo, builder );
return builder.ToString();
}
private static void CreateElementKindString( ElementKind elementKind, GeneralArrayInfo arrayInfo, StringBuilder builder )
{
switch ( elementKind )
{
case ElementKind.Array:
builder.Append( '[' );
if ( arrayInfo != null )
{
if ( arrayInfo.Rank == 1 && arrayInfo.Sizes.Count == 0 && arrayInfo.LowerBounds.Count == 0 )
{
// Special case
builder.Append( '*' );
}
else
{
for ( var i = 0; i < arrayInfo.Rank; ++i )
{
var appendLoBound = i < arrayInfo.LowerBounds.Count;
if ( appendLoBound )
{
var loBound = arrayInfo.LowerBounds[i];
appendLoBound = loBound != 0;
if ( appendLoBound )
{
builder.Append( loBound ).Append( ".." );
}
}
if ( i < arrayInfo.Sizes.Count )
{
builder.Append( arrayInfo.Sizes[i] );
}
else if ( appendLoBound )
{
builder.Append( '.' );
}
if ( i < arrayInfo.Rank - 1 )
{
builder.Append( ',' );
}
}
}
}
builder.Append( ']' );
break;
case ElementKind.Pointer:
builder.Append( '*' );
break;
case ElementKind.Reference:
builder.Append( '&' );
break;
}
}
internal static void ThrowIfDeclaringTypeGenericButNotGDef( CILElementOwnedByType element )
{
var gDef = element.DeclaringType.GenericDefinition;
if ( gDef != null && !Object.ReferenceEquals( gDef, element.DeclaringType ) )
{
throw new InvalidOperationException( "This method can not be used on generic types, which are not generic type definitions." );
}
}
internal static void ThrowIfDeclaringTypeNotGeneric( CILElementOwnedByType element, CILTypeBase[] gArgs )
{
var gDef = element.DeclaringType.GenericDefinition;
if ( gDef == null && gArgs != null && gArgs.Length != 0 )
{
throw new InvalidOperationException( "This method can only be used on elements declared in generic types." );
}
}
//internal static void CheckCyclity( this IEnumerable<CILTypeBase> graph, Object thisType )
//{
// if ( graph.Any( i => Object.ReferenceEquals( thisType, i ) ) )
// {
// throw new ArgumentException( "Cyclity detected between " + thisType + " and " + graph.First( i => Object.ReferenceEquals( thisType, i ) ) + "." );
// }
//}
internal static void CheckWhenDefiningGArgs( ListProxy<CILTypeBase> currentGArgs, String[] names )
{
if ( currentGArgs.MQ.Count > 0 )
{
throw new InvalidOperationException( "Generic arguments have already been defined." );
}
}
internal static T AddToResettableLazyList<T>( this IResettableLazy<ListProxy<T>> lazy, T value )
{
lazy.Value.Add( value );
return value;
}
//internal static void CheckMethodAttributesForOverriddenMethods( SettableValueForEnums<MethodAttributes> attrs, ListProxy<CILMethod> overriddenMethods )
//{
// if ( overriddenMethods.CQ.Any() )
// {
// attrs.Value = ( attrs.Value & ( ~MethodAttributes.MemberAccessMask ) ) | MethodAttributes.Private;
// }
//}
internal static void ThrowIfNotTrueDefinition( this CILCustomAttributeContainer element )
{
if ( element != null && !( (CILElementInstantiable) element ).IsTrueDefinition )
{
throw new ArgumentException( "Given argument is not true definition." );
}
}
internal static Boolean IsGenericDefinition<T>( this CILElementWithGenericArguments<T> element )
where T : class
{
return Object.ReferenceEquals( element, element.GenericDefinition );
}
internal static SignatureStarters GetSignatureStarter( this CallingConventions convs, Boolean isStatic, Boolean isGeneric )
{
var starter = SignatureStarters.Default;
if ( !isStatic )
{
starter |= SignatureStarters.HasThis;
}
if ( convs.IsExplicitThis() )
{
starter |= SignatureStarters.ExplicitThis;
}
if ( isGeneric )
{
starter |= SignatureStarters.Generic;
}
else if ( convs.IsVarArgs() )
{
starter |= SignatureStarters.VarArgs;
}
return starter;
}
internal static CallingConventions GetCallingConventionFromSignature( this SignatureStarters starter )
{
// TODO is this method correct?
CallingConventions result = 0;
if ( starter.IsHasThis() )
{
result = CallingConventions.HasThis;
}
if ( starter.IsExplicitThis() )
{
result |= CallingConventions.ExplicitThis;
}
if ( starter.IsVarArg() )
{
result |= CallingConventions.VarArgs;
}
else if ( starter.IsGeneric() )
{
result |= CallingConventions.Standard;
}
return result;
}
internal static void CheckTypeForMethodSig( CILModule thisModule, ref CILTypeBase type )
{
if ( TypeKind.MethodSignature == type.TypeKind && !Object.Equals( thisModule, type.Module ) )
{
type = ( (CILMethodSignature) type ).CopyToOtherModule( thisModule );
}
}
// Mofidied from http://stackoverflow.com/questions/1068541/how-to-convert-a-value-type-to-byte-in-c
internal static Byte[] ObjectToByteArray( Object value )
{
// TODO SL (get thru context?)
#if CAM_LOGICAL_IS_SL
return null;
#else
var rawsize = Marshal.SizeOf( value );
var rawdata = new Byte[rawsize];
var handle =
GCHandle.Alloc( rawdata,
GCHandleType.Pinned );
try
{
Marshal.StructureToPtr( value,
handle.AddrOfPinnedObject(),
false );
}
finally
{
handle.Free();
}
return rawdata;
#endif
}
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using NUnit.Framework;
using System;
using Assert = Lucene.Net.TestFramework.Assert;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Search
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IndexReader = Lucene.Net.Index.IndexReader;
using Int32Field = Int32Field;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MultiFields = Lucene.Net.Index.MultiFields;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SingleField = SingleField;
using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestNumericUtils = Lucene.Net.Util.TestNumericUtils; // NaN arrays
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestNumericRangeQuery32 : LuceneTestCase
{
// distance of entries
private static int distance;
// shift the starting of the values to the left, to also have negative values:
private static readonly int startOffset = -1 << 15;
// number of docs to generate for testing
private static int noDocs;
private static Directory directory = null;
private static IndexReader reader = null;
private static IndexSearcher searcher = null;
/// <summary>
/// LUCENENET specific
/// Is non-static because NewIndexWriterConfig is no longer static.
/// </summary>
[OneTimeSetUp]
public override void BeforeClass()
{
base.BeforeClass();
noDocs = AtLeast(4096);
distance = (1 << 30) / noDocs;
directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMaxBufferedDocs(TestUtil.NextInt32(Random, 100, 1000)).SetMergePolicy(NewLogMergePolicy()));
FieldType storedInt = new FieldType(Int32Field.TYPE_NOT_STORED);
storedInt.IsStored = true;
storedInt.Freeze();
FieldType storedInt8 = new FieldType(storedInt);
storedInt8.NumericPrecisionStep = 8;
FieldType storedInt4 = new FieldType(storedInt);
storedInt4.NumericPrecisionStep = 4;
FieldType storedInt2 = new FieldType(storedInt);
storedInt2.NumericPrecisionStep = 2;
FieldType storedIntNone = new FieldType(storedInt);
storedIntNone.NumericPrecisionStep = int.MaxValue;
FieldType unstoredInt = Int32Field.TYPE_NOT_STORED;
FieldType unstoredInt8 = new FieldType(unstoredInt);
unstoredInt8.NumericPrecisionStep = 8;
FieldType unstoredInt4 = new FieldType(unstoredInt);
unstoredInt4.NumericPrecisionStep = 4;
FieldType unstoredInt2 = new FieldType(unstoredInt);
unstoredInt2.NumericPrecisionStep = 2;
Int32Field field8 = new Int32Field("field8", 0, storedInt8), field4 = new Int32Field("field4", 0, storedInt4), field2 = new Int32Field("field2", 0, storedInt2), fieldNoTrie = new Int32Field("field" + int.MaxValue, 0, storedIntNone), ascfield8 = new Int32Field("ascfield8", 0, unstoredInt8), ascfield4 = new Int32Field("ascfield4", 0, unstoredInt4), ascfield2 = new Int32Field("ascfield2", 0, unstoredInt2);
Document doc = new Document();
// add fields, that have a distance to test general functionality
doc.Add(field8);
doc.Add(field4);
doc.Add(field2);
doc.Add(fieldNoTrie);
// add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive
doc.Add(ascfield8);
doc.Add(ascfield4);
doc.Add(ascfield2);
// Add a series of noDocs docs with increasing int values
for (int l = 0; l < noDocs; l++)
{
int val = distance * l + startOffset;
field8.SetInt32Value(val);
field4.SetInt32Value(val);
field2.SetInt32Value(val);
fieldNoTrie.SetInt32Value(val);
val = l - (noDocs / 2);
ascfield8.SetInt32Value(val);
ascfield4.SetInt32Value(val);
ascfield2.SetInt32Value(val);
writer.AddDocument(doc);
}
reader = writer.GetReader();
searcher = NewSearcher(reader);
writer.Dispose();
}
[OneTimeTearDown]
public override void AfterClass()
{
searcher = null;
reader.Dispose();
reader = null;
directory.Dispose();
directory = null;
base.AfterClass();
}
[SetUp]
public override void SetUp()
{
base.SetUp();
// set the theoretical maximum term count for 8bit (see docs for the number)
// super.tearDown will restore the default
BooleanQuery.MaxClauseCount = 3 * 255 * 2 + 255;
}
/// <summary>
/// test for both constant score and boolean query, the other tests only use the constant score mode </summary>
private void TestRange(int precisionStep)
{
string field = "field" + precisionStep;
int count = 3000;
int lower = (distance * 3 / 2) + startOffset, upper = lower + count * distance + (distance / 3);
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
NumericRangeFilter<int> f = NumericRangeFilter.NewInt32Range(field, precisionStep, lower, upper, true, true);
for (sbyte i = 0; i < 3; i++)
{
TopDocs topDocs;
string type;
switch (i)
{
case 0:
type = " (constant score filter rewrite)";
q.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE;
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
break;
case 1:
type = " (constant score boolean rewrite)";
q.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
break;
case 2:
type = " (filter)";
topDocs = searcher.Search(new MatchAllDocsQuery(), f, noDocs, Sort.INDEXORDER);
break;
default:
return;
}
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count" + type);
Document doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(2 * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "First doc" + type);
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((1 + count) * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "Last doc" + type);
}
}
[Test]
public virtual void TestRange_8bit()
{
TestRange(8);
}
[Test]
public virtual void TestRange_4bit()
{
TestRange(4);
}
[Test]
public virtual void TestRange_2bit()
{
TestRange(2);
}
[Test]
public virtual void TestInverseRange()
{
AtomicReaderContext context = (AtomicReaderContext)SlowCompositeReaderWrapper.Wrap(reader).Context;
NumericRangeFilter<int> f = NumericRangeFilter.NewInt32Range("field8", 8, 1000, -1000, true, true);
Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A inverse range should return the null instance");
f = NumericRangeFilter.NewInt32Range("field8", 8, int.MaxValue, null, false, false);
Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range starting with Integer.MAX_VALUE should return the null instance");
f = NumericRangeFilter.NewInt32Range("field8", 8, null, int.MinValue, false, false);
Assert.IsNull(f.GetDocIdSet(context, (context.AtomicReader).LiveDocs), "A exclusive range ending with Integer.MIN_VALUE should return the null instance");
}
[Test]
public virtual void TestOneMatchQuery()
{
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range("ascfield8", 8, 1000, 1000, true, true);
TopDocs topDocs = searcher.Search(q, noDocs);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(1, sd.Length, "Score doc count");
}
private void TestLeftOpenRange(int precisionStep)
{
string field = "field" + precisionStep;
int count = 3000;
int upper = (count - 1) * distance + (distance / 3) + startOffset;
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range(field, precisionStep, null, upper, true, true);
TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count");
Document doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(startOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((count - 1) * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
q = NumericRangeQuery.NewInt32Range(field, precisionStep, null, upper, false, true);
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count");
doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(startOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((count - 1) * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
}
[Test]
public virtual void TestLeftOpenRange_8bit()
{
TestLeftOpenRange(8);
}
[Test]
public virtual void TestLeftOpenRange_4bit()
{
TestLeftOpenRange(4);
}
[Test]
public virtual void TestLeftOpenRange_2bit()
{
TestLeftOpenRange(2);
}
private void TestRightOpenRange(int precisionStep)
{
string field = "field" + precisionStep;
int count = 3000;
int lower = (count - 1) * distance + (distance / 3) + startOffset;
NumericRangeQuery<int> q = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, null, true, true);
TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(noDocs - count, sd.Length, "Score doc count");
Document doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(count * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((noDocs - 1) * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
q = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, null, true, false);
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(noDocs - count, sd.Length, "Score doc count");
doc = searcher.Doc(sd[0].Doc);
Assert.AreEqual(count * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "First doc");
doc = searcher.Doc(sd[sd.Length - 1].Doc);
Assert.AreEqual((noDocs - 1) * distance + startOffset, doc.GetField(field).GetInt32Value().Value, "Last doc");
}
[Test]
public virtual void TestRightOpenRange_8bit()
{
TestRightOpenRange(8);
}
[Test]
public virtual void TestRightOpenRange_4bit()
{
TestRightOpenRange(4);
}
[Test]
public virtual void TestRightOpenRange_2bit()
{
TestRightOpenRange(2);
}
[Test]
public virtual void TestInfiniteValues()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)));
Document doc = new Document();
doc.Add(new SingleField("float", float.NegativeInfinity, Field.Store.NO));
doc.Add(new Int32Field("int", int.MinValue, Field.Store.NO));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new SingleField("float", float.PositiveInfinity, Field.Store.NO));
doc.Add(new Int32Field("int", int.MaxValue, Field.Store.NO));
writer.AddDocument(doc);
doc = new Document();
doc.Add(new SingleField("float", 0.0f, Field.Store.NO));
doc.Add(new Int32Field("int", 0, Field.Store.NO));
writer.AddDocument(doc);
foreach (float f in TestNumericUtils.FLOAT_NANs)
{
doc = new Document();
doc.Add(new SingleField("float", f, Field.Store.NO));
writer.AddDocument(doc);
}
writer.Dispose();
IndexReader r = DirectoryReader.Open(dir);
IndexSearcher s = NewSearcher(r);
Query q = NumericRangeQuery.NewInt32Range("int", null, null, true, true);
TopDocs topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewInt32Range("int", null, null, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewInt32Range("int", int.MinValue, int.MaxValue, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewInt32Range("int", int.MinValue, int.MaxValue, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", null, null, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", null, null, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", float.NegativeInfinity, float.PositiveInfinity, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(3, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", float.NegativeInfinity, float.PositiveInfinity, false, false);
topDocs = s.Search(q, 10);
Assert.AreEqual(1, topDocs.ScoreDocs.Length, "Score doc count");
q = NumericRangeQuery.NewSingleRange("float", float.NaN, float.NaN, true, true);
topDocs = s.Search(q, 10);
Assert.AreEqual(TestNumericUtils.FLOAT_NANs.Length, topDocs.ScoreDocs.Length, "Score doc count");
r.Dispose();
dir.Dispose();
}
private void TestRandomTrieAndClassicRangeQuery(int precisionStep)
{
string field = "field" + precisionStep;
int totalTermCountT = 0, totalTermCountC = 0, termCountT, termCountC;
int num = TestUtil.NextInt32(Random, 10, 20);
for (int i = 0; i < num; i++)
{
int lower = (int)(Random.NextDouble() * noDocs * distance) + startOffset;
int upper = (int)(Random.NextDouble() * noDocs * distance) + startOffset;
if (lower > upper)
{
int a = lower;
lower = upper;
upper = a;
}
BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_INT32), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_INT32);
NumericUtils.Int32ToPrefixCodedBytes(lower, 0, lowerBytes);
NumericUtils.Int32ToPrefixCodedBytes(upper, 0, upperBytes);
// test inclusive range
NumericRangeQuery<int> tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
TermRangeQuery cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
TopDocs cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
// test exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, false);
cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, false);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
// test left exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, true);
cq = new TermRangeQuery(field, lowerBytes, upperBytes, false, true);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
// test right exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, false);
cq = new TermRangeQuery(field, lowerBytes, upperBytes, true, false);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
totalTermCountT += termCountT = CountTerms(tq);
totalTermCountC += termCountC = CountTerms(cq);
CheckTermCounts(precisionStep, termCountT, termCountC);
}
CheckTermCounts(precisionStep, totalTermCountT, totalTermCountC);
if (Verbose && precisionStep != int.MaxValue)
{
Console.WriteLine("Average number of terms during random search on '" + field + "':");
Console.WriteLine(" Numeric query: " + (((double)totalTermCountT) / (num * 4)));
Console.WriteLine(" Classical query: " + (((double)totalTermCountC) / (num * 4)));
}
}
[Test]
public virtual void TestEmptyEnums()
{
int count = 3000;
int lower = (distance * 3 / 2) + startOffset, upper = lower + count * distance + (distance / 3);
// test empty enum
if (Debugging.AssertsEnabled) Debugging.Assert(lower < upper);
Assert.IsTrue(0 < CountTerms(NumericRangeQuery.NewInt32Range("field4", 4, lower, upper, true, true)));
Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewInt32Range("field4", 4, upper, lower, true, true)));
// test empty enum outside of bounds
lower = distance * noDocs + startOffset;
upper = 2 * lower;
if (Debugging.AssertsEnabled) Debugging.Assert(lower < upper);
Assert.AreEqual(0, CountTerms(NumericRangeQuery.NewInt32Range("field4", 4, lower, upper, true, true)));
}
private int CountTerms(MultiTermQuery q)
{
Terms terms = MultiFields.GetTerms(reader, q.Field);
if (terms is null)
{
return 0;
}
TermsEnum termEnum = q.GetTermsEnum(terms);
Assert.IsNotNull(termEnum);
int count = 0;
BytesRef cur, last = null;
while (termEnum.MoveNext())
{
cur = termEnum.Term;
count++;
if (last != null)
{
Assert.IsTrue(last.CompareTo(cur) < 0);
}
last = BytesRef.DeepCopyOf(cur);
}
// LUCENE-3314: the results after next() already returned null are undefined,
// Assert.IsNull(termEnum.Next());
return count;
}
private void CheckTermCounts(int precisionStep, int termCountT, int termCountC)
{
if (precisionStep == int.MaxValue)
{
Assert.AreEqual(termCountC, termCountT, "Number of terms should be equal for unlimited precStep");
}
else
{
Assert.IsTrue(termCountT <= termCountC, "Number of terms for NRQ should be <= compared to classical TRQ");
}
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_8bit()
{
TestRandomTrieAndClassicRangeQuery(8);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_4bit()
{
TestRandomTrieAndClassicRangeQuery(4);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_2bit()
{
TestRandomTrieAndClassicRangeQuery(2);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie()
{
TestRandomTrieAndClassicRangeQuery(int.MaxValue);
}
private void TestRangeSplit(int precisionStep)
{
string field = "ascfield" + precisionStep;
// 10 random tests
int num = TestUtil.NextInt32(Random, 10, 20);
for (int i = 0; i < num; i++)
{
int lower = (int)(Random.NextDouble() * noDocs - noDocs / 2);
int upper = (int)(Random.NextDouble() * noDocs - noDocs / 2);
if (lower > upper)
{
int a = lower;
lower = upper;
upper = a;
}
// test inclusive range
Query tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
// test exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, false);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length");
// test left exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, false, true);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
// test right exclusive range
tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, false);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
}
}
[Test]
public virtual void TestRangeSplit_8bit()
{
TestRangeSplit(8);
}
[Test]
public virtual void TestRangeSplit_4bit()
{
TestRangeSplit(4);
}
[Test]
public virtual void TestRangeSplit_2bit()
{
TestRangeSplit(2);
}
/// <summary>
/// we fake a float test using int2float conversion of NumericUtils </summary>
private void TestFloatRange(int precisionStep)
{
string field = "ascfield" + precisionStep;
const int lower = -1000, upper = +2000;
Query tq = NumericRangeQuery.NewSingleRange(field, precisionStep, NumericUtils.SortableInt32ToSingle(lower), NumericUtils.SortableInt32ToSingle(upper), true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
Filter tf = NumericRangeFilter.NewSingleRange(field, precisionStep, NumericUtils.SortableInt32ToSingle(lower), NumericUtils.SortableInt32ToSingle(upper), true, true);
tTopDocs = searcher.Search(new MatchAllDocsQuery(), tf, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length");
}
[Test]
public virtual void TestFloatRange_8bit()
{
TestFloatRange(8);
}
[Test]
public virtual void TestFloatRange_4bit()
{
TestFloatRange(4);
}
[Test]
public virtual void TestFloatRange_2bit()
{
TestFloatRange(2);
}
private void TestSorting(int precisionStep)
{
string field = "field" + precisionStep;
// 10 random tests, the index order is ascending,
// so using a reverse sort field should retun descending documents
int num = TestUtil.NextInt32(Random, 10, 20);
for (int i = 0; i < num; i++)
{
int lower = (int)(Random.NextDouble() * noDocs * distance) + startOffset;
int upper = (int)(Random.NextDouble() * noDocs * distance) + startOffset;
if (lower > upper)
{
int a = lower;
lower = upper;
upper = a;
}
Query tq = NumericRangeQuery.NewInt32Range(field, precisionStep, lower, upper, true, true);
TopDocs topDocs = searcher.Search(tq, null, noDocs, new Sort(new SortField(field, SortFieldType.INT32, true)));
if (topDocs.TotalHits == 0)
{
continue;
}
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
int last = searcher.Doc(sd[0].Doc).GetField(field).GetInt32Value().Value;
for (int j = 1; j < sd.Length; j++)
{
int act = searcher.Doc(sd[j].Doc).GetField(field).GetInt32Value().Value;
Assert.IsTrue(last > act, "Docs should be sorted backwards");
last = act;
}
}
}
[Test]
public virtual void TestSorting_8bit()
{
TestSorting(8);
}
[Test]
public virtual void TestSorting_4bit()
{
TestSorting(4);
}
[Test]
public virtual void TestSorting_2bit()
{
TestSorting(2);
}
[Test]
public virtual void TestEqualsAndHash()
{
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test1", 4, 10, 20, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test2", 4, 10, 20, false, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test3", 4, 10, 20, true, false));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test4", 4, 10, 20, false, false));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test5", 4, 10, null, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test6", 4, null, 20, true, true));
QueryUtils.CheckHashEquals(NumericRangeQuery.NewInt32Range("test7", 4, null, null, true, true));
QueryUtils.CheckEqual(NumericRangeQuery.NewInt32Range("test8", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test8", 4, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test9", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test9", 8, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test10a", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test10b", 4, 10, 20, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test11", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test11", 4, 20, 10, true, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test12", 4, 10, 20, true, true), NumericRangeQuery.NewInt32Range("test12", 4, 10, 20, false, true));
QueryUtils.CheckUnequal(NumericRangeQuery.NewInt32Range("test13", 4, 10, 20, true, true), NumericRangeQuery.NewSingleRange("test13", 4, 10f, 20f, true, true));
// the following produces a hash collision, because Long and Integer have the same hashcode, so only test equality:
Query q1 = NumericRangeQuery.NewInt32Range("test14", 4, 10, 20, true, true);
Query q2 = NumericRangeQuery.NewInt64Range("test14", 4, 10L, 20L, true, true);
Assert.IsFalse(q1.Equals(q2));
Assert.IsFalse(q2.Equals(q1));
}
}
}
| |
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="System.PerformanceSFlowBinding", Namespace="urn:iControl")]
public partial class SystemPerformanceSFlow : iControlInterface {
public SystemPerformanceSFlow() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void create(
string [] receivers,
string [] addresses
) {
this.Invoke("create", new object [] {
receivers,
addresses});
}
public System.IAsyncResult Begincreate(string [] receivers,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
receivers,
addresses}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_sflow_receivers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void delete_all_sflow_receivers(
) {
this.Invoke("delete_all_sflow_receivers", new object [0]);
}
public System.IAsyncResult Begindelete_all_sflow_receivers(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_sflow_receivers", new object[0], callback, asyncState);
}
public void Enddelete_all_sflow_receivers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_sflow_receiver
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void delete_sflow_receiver(
string [] receivers
) {
this.Invoke("delete_sflow_receiver", new object [] {
receivers});
}
public System.IAsyncResult Begindelete_sflow_receiver(string [] receivers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_sflow_receiver", new object[] {
receivers}, callback, asyncState);
}
public void Enddelete_sflow_receiver(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_address(
string [] receivers
) {
object [] results = this.Invoke("get_address", new object [] {
receivers});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_address(string [] receivers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_address", new object[] {
receivers}, callback, asyncState);
}
public string [] Endget_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_datagram_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_datagram_version(
string [] receivers
) {
object [] results = this.Invoke("get_datagram_version", new object [] {
receivers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_datagram_version(string [] receivers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_datagram_version", new object[] {
receivers}, callback, asyncState);
}
public long [] Endget_datagram_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[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_maximum_datagram_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_maximum_datagram_size(
string [] receivers
) {
object [] results = this.Invoke("get_maximum_datagram_size", new object [] {
receivers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_maximum_datagram_size(string [] receivers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_maximum_datagram_size", new object[] {
receivers}, callback, asyncState);
}
public long [] Endget_maximum_datagram_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_poll_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_poll_interval(
string [] receivers
) {
object [] results = this.Invoke("get_poll_interval", new object [] {
receivers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_poll_interval(string [] receivers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_poll_interval", new object[] {
receivers}, callback, asyncState);
}
public long [] Endget_poll_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_port(
string [] receivers
) {
object [] results = this.Invoke("get_port", new object [] {
receivers});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_port(string [] receivers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_port", new object[] {
receivers}, callback, asyncState);
}
public long [] Endget_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
[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]));
}
//-----------------------------------------------------------------------
// set_address
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void set_address(
string [] receivers,
string [] addresses
) {
this.Invoke("set_address", new object [] {
receivers,
addresses});
}
public System.IAsyncResult Beginset_address(string [] receivers,string [] addresses, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_address", new object[] {
receivers,
addresses}, callback, asyncState);
}
public void Endset_address(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_maximum_datagram_size
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void set_maximum_datagram_size(
string [] receivers,
long [] sizes
) {
this.Invoke("set_maximum_datagram_size", new object [] {
receivers,
sizes});
}
public System.IAsyncResult Beginset_maximum_datagram_size(string [] receivers,long [] sizes, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_maximum_datagram_size", new object[] {
receivers,
sizes}, callback, asyncState);
}
public void Endset_maximum_datagram_size(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_poll_interval
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void set_poll_interval(
string [] receivers,
long [] intervals
) {
this.Invoke("set_poll_interval", new object [] {
receivers,
intervals});
}
public System.IAsyncResult Beginset_poll_interval(string [] receivers,long [] intervals, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_poll_interval", new object[] {
receivers,
intervals}, callback, asyncState);
}
public void Endset_poll_interval(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_port
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:System/PerformanceSFlow",
RequestNamespace="urn:iControl:System/PerformanceSFlow", ResponseNamespace="urn:iControl:System/PerformanceSFlow")]
public void set_port(
string [] receivers,
long [] ports
) {
this.Invoke("set_port", new object [] {
receivers,
ports});
}
public System.IAsyncResult Beginset_port(string [] receivers,long [] ports, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_port", new object[] {
receivers,
ports}, callback, asyncState);
}
public void Endset_port(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Security;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Data;
using System.Windows.Input;
using GalaSoft.MvvmLight.CommandWpf;
using MahApps.Metro.Controls.Dialogs;
using Noterium.Code.Commands;
using Noterium.Code.Messages;
using Noterium.Core;
using Noterium.Core.Constants;
using Noterium.Core.DataCarriers;
using Noterium.Core.Utilities;
using Noterium.Properties;
namespace Noterium.ViewModels
{
public class MainViewModel : NoteriumViewModelBase, IDisposable
{
private readonly Timer _quickMessageTimer;
private readonly object _searchResultLockObject = new object();
private readonly Timer _searchTimer;
private bool _addNoteButtonVisible;
private Timer _intervallTimer;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
MainWindowLoadedCommand = new RelayCommand(MainWindowLoaded);
ToggleNoteMenu = new SimpleCommand(ToggleNoteMenuVisibility);
ToggleNotebookMenu = new SimpleCommand(ToggleNotebookMenuVisibility);
ToggleSearchFlyoutCommand = new SimpleCommand(ToggleSearchFlyout);
//SearchTextChangedCommand = new SimpleCommand(Search);
SearchResultSelectedCommand = new SimpleCommand(SearchResultSelected);
CloseSearchCommand = new RelayCommand(CloseSearch);
ToggleHelpViewCommand = new RelayCommand(ToggleHelpView);
PerformLockActionsCommand = new RelayCommand(PerformLockActions);
ToggleSettingsFlyoutCommand = new RelayCommand(ToggleSettingsFlyout);
NoteViewModels = new Dictionary<Guid, NoteViewModel>();
TopMainMenuItems = new ObservableCollection<TopMainMenuItemViewModel>();
SearchResult = new ObservableCollection<NoteViewModel>();
EditNoteCommand = new RelayCommand(() => { MessengerInstance.Send(new ChangeViewMode(NoteViewModes.Edit)); });
BindingOperations.EnableCollectionSynchronization(SearchResult, _searchResultLockObject);
PropertyChanged += MainViewModelPropertyChanged;
Hub.Instance.Settings.PropertyChanged += SettingsPropertyChanged;
Hub.Instance.EncryptionManager.PropertyChanged += SettingsPropertyChanged;
IsSecureNotesEnabled = Hub.Instance.EncryptionManager.SecureNotesEnabled;
_quickMessageTimer = new Timer {AutoReset = false};
_quickMessageTimer.Elapsed += QuickMessageTimerElapsed;
_quickMessageTimer.Interval = 2000;
_searchTimer = new Timer {AutoReset = false};
_searchTimer.Elapsed += SearchTimerElapsed;
_searchTimer.Interval = 250;
HelpDocumentText = Resources.Help_Document;
MessengerInstance.Register<ConfigureControlsForParnetType>(this, ConfigureControlsForParentType);
MessengerInstance.Register<QuickMessage>(this, ShowQuickMessage);
}
public ICommand ToggleNoteMenu { get; set; }
public ICommand ToggleHelpViewCommand { get; set; }
public ICommand ToggleNotebookMenu { get; set; }
public ICommand MainWindowLoadedCommand { get; set; }
public ICommand LockCommand { get; set; }
public ICommand ToggleSearchFlyoutCommand { get; set; }
public ICommand SearchTextChangedCommand { get; set; }
public ICommand SearchResultSelectedCommand { get; set; }
public ICommand CloseSearchCommand { get; set; }
public ICommand PerformLockActionsCommand { get; set; }
public ICommand ToggleSettingsFlyoutCommand { get; set; }
public ICommand EditNoteCommand { get; set; }
public Dictionary<Guid, NoteViewModel> NoteViewModels { get; set; }
public ObservableCollection<TopMainMenuItemViewModel> TopMainMenuItems { get; set; }
public void Dispose()
{
_quickMessageTimer?.Dispose();
_intervallTimer?.Dispose();
_searchTimer?.Dispose();
}
private void ConfigureControlsForParentType(ConfigureControlsForParnetType obj)
{
if (obj.Type == ConfigureControlsForParnetType.ParentType.Tag || obj.Type == ConfigureControlsForParnetType.ParentType.Library)
{
AddNoteContextMenuButtonVisible = false;
AddNoteButtonVisible = false;
}
else if (obj.Type == ConfigureControlsForParnetType.ParentType.Notebook)
{
if (Hub.Instance.EncryptionManager.SecureNotesEnabled)
{
AddNoteButtonVisible = false;
AddNoteContextMenuButtonVisible = true;
}
else
{
AddNoteContextMenuButtonVisible = false;
AddNoteButtonVisible = true;
}
}
}
private void ToggleSettingsFlyout()
{
SettingsFlyoutIsVisible = !SettingsFlyoutIsVisible;
}
private void PerformLockActions()
{
if (IsHelpVisible)
IsHelpVisible = false;
if (SettingsFlyoutIsVisible)
SettingsFlyoutIsVisible = false;
if (SearchFlyoutIsVisible)
SearchFlyoutIsVisible = false;
}
private void ToggleHelpView()
{
IsHelpVisible = !IsHelpVisible;
}
private void CloseSearch()
{
SearchFlyoutIsVisible = false;
SearchResult.Clear();
SearchTerm = string.Empty;
}
private void SearchResultSelected(object obj)
{
var model = obj as NoteViewModel;
if (model != null)
{
MessengerInstance.Send(new ReloadNoteMenuList(model.Notebook, model.Note));
CloseSearch();
}
}
private void Search()
{
lock (_searchResultLockObject)
{
_searchTimer.Stop();
_searchTimer.Start();
}
}
private void SearchTimerElapsed(object sender, ElapsedEventArgs e)
{
if (string.IsNullOrWhiteSpace(SearchTerm))
return;
InvokeOnCurrentDispatcher(() => { IsSearching = true; });
var searchResult = Hub.Instance.SearchManager.Search(SearchTerm);
InvokeOnCurrentDispatcher(() =>
{
var models = ViewModelLocator.Instance.GetNoteViewModels(searchResult);
SearchResult.Clear();
models.ForEach(SearchResult.Add);
IsSearching = false;
});
}
private void ToggleSearchFlyout(object obj)
{
SearchFlyoutIsVisible = !SearchFlyoutIsVisible;
}
private void ToggleNotebookMenuVisibility(object obj)
{
NotebookColumnVisibility = !NotebookColumnVisibility;
}
private void ToggleNoteMenuVisibility(object obj)
{
ShowNoteColumn = !ShowNoteColumn;
}
private void QuickMessageTimerElapsed(object sender, ElapsedEventArgs e)
{
InvokeOnCurrentDispatcher(() => { QuickInformationIsOpen = false; });
}
private void ShowQuickMessage(QuickMessage message)
{
QuickInformationMessage = message.Message;
QuickInformationIsOpen = true;
_quickMessageTimer.Start();
}
private void SettingsPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SecureNotesEnabled") IsSecureNotesEnabled = Hub.Instance.EncryptionManager.SecureNotesEnabled;
}
public void MainWindowLoaded()
{
Init();
}
private void Init()
{
Hub.Instance.EncryptionManager.OnPasswordNeeded += SystemNeedsEncryptionPassword;
Hub.Instance.Storage.EnsureOneNotebook();
if (Hub.Instance.Settings.EnableTextClipper)
{
//Hub.Instance.TextClipper.Init(this.Handle);
//Hub.Instance.TextClipper.OnTextClipped += TextClipper_OnTextClipped;
}
_intervallTimer = new Timer(TimeSpan.FromMinutes(1).TotalMilliseconds);
_intervallTimer.Elapsed += IntervallTimerOnElapsed;
_intervallTimer.Enabled = true;
}
private SecureString SystemNeedsEncryptionPassword()
{
//string password = "abc123";
var pass = MainWindowInstance.ShowInputAsync("Password required", "Password:").ContinueWith(delegate(Task<string> task)
{
var name = task.Result;
if (!string.IsNullOrWhiteSpace(name)) return FileSecurity.ConvertToSecureString(name);
throw new Exception("Password required.");
});
if (pass?.Result == null)
throw new Exception("Password required.");
return pass.Result;
}
private void IntervallTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
if (Hub.Instance.Settings.AutoBackup)
{
var date = Hub.Instance.Storage.GetLastBackupDate();
var ts = DateTime.Now - date;
if (ts.Days > 0)
{
Hub.Instance.Storage.Backup();
Hub.Instance.Storage.CleanBackupData();
}
}
}
private void MainViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "SearchTerm")
Search();
}
private void FocusNote(Note note)
{
var nvm = ViewModelLocator.Instance.GetNoteViewModel(note);
InvokeOnCurrentDispatcher(() =>
{
NoteMenuContext.DataSource.Add(nvm);
NoteMenuContext.SelectedNote = nvm;
});
}
#region -- Static menu items --
private bool _secureNotesEnabled;
private bool _quickInformationIsOpen;
private string _quickInformationMessage;
private bool _notebookColumnVisibility = true;
private bool _showNoteColumn = true;
private bool _searchFlyoutIsVisible;
private string _searchTerm;
private bool _isSearching;
private bool _isHelpVisible;
private bool _settingsFlyoutIsVisible;
private bool _librarysFlyoutIsVisible;
private string _helpDocumentText;
#endregion
#region -- Propertys --
public bool AddNoteContextMenuButtonVisible
{
get => _addNoteButtonVisible;
set
{
var oldValue = _addNoteButtonVisible;
_addNoteButtonVisible = value;
if (oldValue != value)
RaisePropertyChanged();
}
}
public bool AddNoteButtonVisible
{
get => _addNoteButtonVisible;
set
{
var oldValue = _addNoteButtonVisible;
_addNoteButtonVisible = value;
if (oldValue != value)
RaisePropertyChanged();
}
}
public bool SearchFlyoutIsVisible
{
get => _searchFlyoutIsVisible;
set
{
_searchFlyoutIsVisible = value;
RaisePropertyChanged();
}
}
public ObservableCollection<Tag> Tags => Hub.Instance.Settings.Tags;
public NotebookMenuViewModel MenuContext => ViewModelLocator.Instance.NotebookMenu;
public NoteMenuViewModel NoteMenuContext => ViewModelLocator.Instance.NoteMenu;
public NoteViewerViewModel NoteViewContext => ViewModelLocator.Instance.NoteView;
public bool IsSecureNotesEnabled
{
get => _secureNotesEnabled;
set
{
_secureNotesEnabled = value;
RaisePropertyChanged();
}
}
public bool QuickInformationIsOpen
{
get => _quickInformationIsOpen;
set
{
_quickInformationIsOpen = value;
RaisePropertyChanged();
}
}
public string QuickInformationMessage
{
get => _quickInformationMessage;
set
{
_quickInformationMessage = value;
RaisePropertyChanged();
}
}
public bool NotebookColumnVisibility
{
get => _notebookColumnVisibility;
set
{
_notebookColumnVisibility = value;
RaisePropertyChanged();
}
}
public bool ShowNoteColumn
{
get => _showNoteColumn;
set
{
_showNoteColumn = value;
RaisePropertyChanged();
}
}
public string SearchTerm
{
get => _searchTerm;
set
{
_searchTerm = value;
RaisePropertyChanged();
}
}
public ObservableCollection<NoteViewModel> SearchResult { get; }
public bool IsSearching
{
get => _isSearching;
set
{
_isSearching = value;
RaisePropertyChanged();
}
}
public bool IsHelpVisible
{
get => _isHelpVisible;
set
{
_isHelpVisible = value;
RaisePropertyChanged();
}
}
public bool SettingsFlyoutIsVisible
{
get => _settingsFlyoutIsVisible;
set
{
_settingsFlyoutIsVisible = value;
RaisePropertyChanged();
}
}
public bool LibrarysFlyoutIsVisible
{
get => _librarysFlyoutIsVisible;
set
{
_librarysFlyoutIsVisible = value;
RaisePropertyChanged();
}
}
public string HelpDocumentText
{
get => _helpDocumentText;
set
{
_helpDocumentText = value;
RaisePropertyChanged();
}
}
public bool Loaded { get; internal set; }
#endregion
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: bgs/low/pb/client/friends_types.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Bgs.Protocol.Friends.V1 {
/// <summary>Holder for reflection information generated from bgs/low/pb/client/friends_types.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class FriendsTypesReflection {
#region Descriptor
/// <summary>File descriptor for bgs/low/pb/client/friends_types.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static FriendsTypesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiViZ3MvbG93L3BiL2NsaWVudC9mcmllbmRzX3R5cGVzLnByb3RvEhdiZ3Mu",
"cHJvdG9jb2wuZnJpZW5kcy52MRonYmdzL2xvdy9wYi9jbGllbnQvYXR0cmli",
"dXRlX3R5cGVzLnByb3RvGiRiZ3MvbG93L3BiL2NsaWVudC9lbnRpdHlfdHlw",
"ZXMucHJvdG8aKGJncy9sb3cvcGIvY2xpZW50L2ludml0YXRpb25fdHlwZXMu",
"cHJvdG8ixwEKBkZyaWVuZBIqCgphY2NvdW50X2lkGAEgASgLMhYuYmdzLnBy",
"b3RvY29sLkVudGl0eUlkEioKCWF0dHJpYnV0ZRgCIAMoCzIXLmJncy5wcm90",
"b2NvbC5BdHRyaWJ1dGUSEAoEcm9sZRgDIAMoDUICEAESEgoKcHJpdmlsZWdl",
"cxgEIAEoBBIYChBhdHRyaWJ1dGVzX2Vwb2NoGAUgASgEEhEKCWZ1bGxfbmFt",
"ZRgGIAEoCRISCgpiYXR0bGVfdGFnGAcgASgJIoIBChBGcmllbmRJbnZpdGF0",
"aW9uEhYKDmZpcnN0X3JlY2VpdmVkGAEgASgIEhAKBHJvbGUYAiADKA1CAhAB",
"EkQKEWZyaWVuZF9pbnZpdGF0aW9uGGcgASgLMikuYmdzLnByb3RvY29sLmZy",
"aWVuZHMudjEuRnJpZW5kSW52aXRhdGlvbiKgAgoWRnJpZW5kSW52aXRhdGlv",
"blBhcmFtcxIUCgx0YXJnZXRfZW1haWwYASABKAkSGQoRdGFyZ2V0X2JhdHRs",
"ZV90YWcYAiABKAkSGgoSaW52aXRlcl9iYXR0bGVfdGFnGAMgASgJEhkKEWlu",
"dml0ZXJfZnVsbF9uYW1lGAQgASgJEhwKFGludml0ZWVfZGlzcGxheV9uYW1l",
"GAUgASgJEhAKBHJvbGUYBiADKA1CAhABEiYKGHByZXZpb3VzX3JvbGVfZGVw",
"cmVjYXRlZBgHIAMoDUIEEAEYARJGCg1mcmllbmRfcGFyYW1zGGcgASgLMi8u",
"YmdzLnByb3RvY29sLmZyaWVuZHMudjEuRnJpZW5kSW52aXRhdGlvblBhcmFt",
"c0IvChhibmV0LnByb3RvY29sLmZyaWVuZHMudjFCEUZyaWVuZHNUeXBlc1By",
"b3RvSAJiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Bgs.Protocol.AttributeTypesReflection.Descriptor, global::Bgs.Protocol.EntityTypesReflection.Descriptor, global::Bgs.Protocol.InvitationTypesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Friends.V1.Friend), global::Bgs.Protocol.Friends.V1.Friend.Parser, new[]{ "AccountId", "Attribute", "Role", "Privileges", "AttributesEpoch", "FullName", "BattleTag" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Friends.V1.FriendInvitation), global::Bgs.Protocol.Friends.V1.FriendInvitation.Parser, new[]{ "FirstReceived", "Role", "FriendInvitation_" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Friends.V1.FriendInvitationParams), global::Bgs.Protocol.Friends.V1.FriendInvitationParams.Parser, new[]{ "TargetEmail", "TargetBattleTag", "InviterBattleTag", "InviterFullName", "InviteeDisplayName", "Role", "PreviousRoleDeprecated", "FriendParams" }, null, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Friend : pb::IMessage<Friend> {
private static readonly pb::MessageParser<Friend> _parser = new pb::MessageParser<Friend>(() => new Friend());
public static pb::MessageParser<Friend> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Friends.V1.FriendsTypesReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public Friend() {
OnConstruction();
}
partial void OnConstruction();
public Friend(Friend other) : this() {
AccountId = other.accountId_ != null ? other.AccountId.Clone() : null;
attribute_ = other.attribute_.Clone();
role_ = other.role_.Clone();
privileges_ = other.privileges_;
attributesEpoch_ = other.attributesEpoch_;
fullName_ = other.fullName_;
battleTag_ = other.battleTag_;
}
public Friend Clone() {
return new Friend(this);
}
/// <summary>Field number for the "account_id" field.</summary>
public const int AccountIdFieldNumber = 1;
private global::Bgs.Protocol.EntityId accountId_;
public global::Bgs.Protocol.EntityId AccountId {
get { return accountId_; }
set {
accountId_ = value;
}
}
/// <summary>Field number for the "attribute" field.</summary>
public const int AttributeFieldNumber = 2;
private static readonly pb::FieldCodec<global::Bgs.Protocol.Attribute> _repeated_attribute_codec
= pb::FieldCodec.ForMessage(18, global::Bgs.Protocol.Attribute.Parser);
private readonly pbc::RepeatedField<global::Bgs.Protocol.Attribute> attribute_ = new pbc::RepeatedField<global::Bgs.Protocol.Attribute>();
public pbc::RepeatedField<global::Bgs.Protocol.Attribute> Attribute {
get { return attribute_; }
}
/// <summary>Field number for the "role" field.</summary>
public const int RoleFieldNumber = 3;
private static readonly pb::FieldCodec<uint> _repeated_role_codec
= pb::FieldCodec.ForUInt32(26);
private readonly pbc::RepeatedField<uint> role_ = new pbc::RepeatedField<uint>();
public pbc::RepeatedField<uint> Role {
get { return role_; }
}
/// <summary>Field number for the "privileges" field.</summary>
public const int PrivilegesFieldNumber = 4;
private ulong privileges_;
public ulong Privileges {
get { return privileges_; }
set {
privileges_ = value;
}
}
/// <summary>Field number for the "attributes_epoch" field.</summary>
public const int AttributesEpochFieldNumber = 5;
private ulong attributesEpoch_;
public ulong AttributesEpoch {
get { return attributesEpoch_; }
set {
attributesEpoch_ = value;
}
}
/// <summary>Field number for the "full_name" field.</summary>
public const int FullNameFieldNumber = 6;
private string fullName_ = "";
public string FullName {
get { return fullName_; }
set {
fullName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "battle_tag" field.</summary>
public const int BattleTagFieldNumber = 7;
private string battleTag_ = "";
public string BattleTag {
get { return battleTag_; }
set {
battleTag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as Friend);
}
public bool Equals(Friend other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(AccountId, other.AccountId)) return false;
if(!attribute_.Equals(other.attribute_)) return false;
if(!role_.Equals(other.role_)) return false;
if (Privileges != other.Privileges) return false;
if (AttributesEpoch != other.AttributesEpoch) return false;
if (FullName != other.FullName) return false;
if (BattleTag != other.BattleTag) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (accountId_ != null) hash ^= AccountId.GetHashCode();
hash ^= attribute_.GetHashCode();
hash ^= role_.GetHashCode();
if (Privileges != 0UL) hash ^= Privileges.GetHashCode();
if (AttributesEpoch != 0UL) hash ^= AttributesEpoch.GetHashCode();
if (FullName.Length != 0) hash ^= FullName.GetHashCode();
if (BattleTag.Length != 0) hash ^= BattleTag.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (accountId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(AccountId);
}
attribute_.WriteTo(output, _repeated_attribute_codec);
role_.WriteTo(output, _repeated_role_codec);
if (Privileges != 0UL) {
output.WriteRawTag(32);
output.WriteUInt64(Privileges);
}
if (AttributesEpoch != 0UL) {
output.WriteRawTag(40);
output.WriteUInt64(AttributesEpoch);
}
if (FullName.Length != 0) {
output.WriteRawTag(50);
output.WriteString(FullName);
}
if (BattleTag.Length != 0) {
output.WriteRawTag(58);
output.WriteString(BattleTag);
}
}
public int CalculateSize() {
int size = 0;
if (accountId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(AccountId);
}
size += attribute_.CalculateSize(_repeated_attribute_codec);
size += role_.CalculateSize(_repeated_role_codec);
if (Privileges != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Privileges);
}
if (AttributesEpoch != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(AttributesEpoch);
}
if (FullName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FullName);
}
if (BattleTag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(BattleTag);
}
return size;
}
public void MergeFrom(Friend other) {
if (other == null) {
return;
}
if (other.accountId_ != null) {
if (accountId_ == null) {
accountId_ = new global::Bgs.Protocol.EntityId();
}
AccountId.MergeFrom(other.AccountId);
}
attribute_.Add(other.attribute_);
role_.Add(other.role_);
if (other.Privileges != 0UL) {
Privileges = other.Privileges;
}
if (other.AttributesEpoch != 0UL) {
AttributesEpoch = other.AttributesEpoch;
}
if (other.FullName.Length != 0) {
FullName = other.FullName;
}
if (other.BattleTag.Length != 0) {
BattleTag = other.BattleTag;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (accountId_ == null) {
accountId_ = new global::Bgs.Protocol.EntityId();
}
input.ReadMessage(accountId_);
break;
}
case 18: {
attribute_.AddEntriesFrom(input, _repeated_attribute_codec);
break;
}
case 26:
case 24: {
role_.AddEntriesFrom(input, _repeated_role_codec);
break;
}
case 32: {
Privileges = input.ReadUInt64();
break;
}
case 40: {
AttributesEpoch = input.ReadUInt64();
break;
}
case 50: {
FullName = input.ReadString();
break;
}
case 58: {
BattleTag = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FriendInvitation : pb::IMessage<FriendInvitation> {
private static readonly pb::MessageParser<FriendInvitation> _parser = new pb::MessageParser<FriendInvitation>(() => new FriendInvitation());
public static pb::MessageParser<FriendInvitation> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Friends.V1.FriendsTypesReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FriendInvitation() {
OnConstruction();
}
partial void OnConstruction();
public FriendInvitation(FriendInvitation other) : this() {
firstReceived_ = other.firstReceived_;
role_ = other.role_.Clone();
FriendInvitation_ = other.friendInvitation_ != null ? other.FriendInvitation_.Clone() : null;
}
public FriendInvitation Clone() {
return new FriendInvitation(this);
}
/// <summary>Field number for the "first_received" field.</summary>
public const int FirstReceivedFieldNumber = 1;
private bool firstReceived_;
public bool FirstReceived {
get { return firstReceived_; }
set {
firstReceived_ = value;
}
}
/// <summary>Field number for the "role" field.</summary>
public const int RoleFieldNumber = 2;
private static readonly pb::FieldCodec<uint> _repeated_role_codec
= pb::FieldCodec.ForUInt32(18);
private readonly pbc::RepeatedField<uint> role_ = new pbc::RepeatedField<uint>();
public pbc::RepeatedField<uint> Role {
get { return role_; }
}
/// <summary>Field number for the "friend_invitation" field.</summary>
public const int FriendInvitation_FieldNumber = 103;
private global::Bgs.Protocol.Friends.V1.FriendInvitation friendInvitation_;
public global::Bgs.Protocol.Friends.V1.FriendInvitation FriendInvitation_ {
get { return friendInvitation_; }
set {
friendInvitation_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FriendInvitation);
}
public bool Equals(FriendInvitation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FirstReceived != other.FirstReceived) return false;
if(!role_.Equals(other.role_)) return false;
if (!object.Equals(FriendInvitation_, other.FriendInvitation_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (FirstReceived != false) hash ^= FirstReceived.GetHashCode();
hash ^= role_.GetHashCode();
if (friendInvitation_ != null) hash ^= FriendInvitation_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (FirstReceived != false) {
output.WriteRawTag(8);
output.WriteBool(FirstReceived);
}
role_.WriteTo(output, _repeated_role_codec);
if (friendInvitation_ != null) {
output.WriteRawTag(186, 6);
output.WriteMessage(FriendInvitation_);
}
}
public int CalculateSize() {
int size = 0;
if (FirstReceived != false) {
size += 1 + 1;
}
size += role_.CalculateSize(_repeated_role_codec);
if (friendInvitation_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(FriendInvitation_);
}
return size;
}
public void MergeFrom(FriendInvitation other) {
if (other == null) {
return;
}
if (other.FirstReceived != false) {
FirstReceived = other.FirstReceived;
}
role_.Add(other.role_);
if (other.friendInvitation_ != null) {
if (friendInvitation_ == null) {
friendInvitation_ = new global::Bgs.Protocol.Friends.V1.FriendInvitation();
}
FriendInvitation_.MergeFrom(other.FriendInvitation_);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
FirstReceived = input.ReadBool();
break;
}
case 18:
case 16: {
role_.AddEntriesFrom(input, _repeated_role_codec);
break;
}
case 826: {
if (friendInvitation_ == null) {
friendInvitation_ = new global::Bgs.Protocol.Friends.V1.FriendInvitation();
}
input.ReadMessage(friendInvitation_);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FriendInvitationParams : pb::IMessage<FriendInvitationParams> {
private static readonly pb::MessageParser<FriendInvitationParams> _parser = new pb::MessageParser<FriendInvitationParams>(() => new FriendInvitationParams());
public static pb::MessageParser<FriendInvitationParams> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Friends.V1.FriendsTypesReflection.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public FriendInvitationParams() {
OnConstruction();
}
partial void OnConstruction();
public FriendInvitationParams(FriendInvitationParams other) : this() {
targetEmail_ = other.targetEmail_;
targetBattleTag_ = other.targetBattleTag_;
inviterBattleTag_ = other.inviterBattleTag_;
inviterFullName_ = other.inviterFullName_;
inviteeDisplayName_ = other.inviteeDisplayName_;
role_ = other.role_.Clone();
previousRoleDeprecated_ = other.previousRoleDeprecated_.Clone();
FriendParams = other.friendParams_ != null ? other.FriendParams.Clone() : null;
}
public FriendInvitationParams Clone() {
return new FriendInvitationParams(this);
}
/// <summary>Field number for the "target_email" field.</summary>
public const int TargetEmailFieldNumber = 1;
private string targetEmail_ = "";
public string TargetEmail {
get { return targetEmail_; }
set {
targetEmail_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "target_battle_tag" field.</summary>
public const int TargetBattleTagFieldNumber = 2;
private string targetBattleTag_ = "";
public string TargetBattleTag {
get { return targetBattleTag_; }
set {
targetBattleTag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "inviter_battle_tag" field.</summary>
public const int InviterBattleTagFieldNumber = 3;
private string inviterBattleTag_ = "";
public string InviterBattleTag {
get { return inviterBattleTag_; }
set {
inviterBattleTag_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "inviter_full_name" field.</summary>
public const int InviterFullNameFieldNumber = 4;
private string inviterFullName_ = "";
public string InviterFullName {
get { return inviterFullName_; }
set {
inviterFullName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "invitee_display_name" field.</summary>
public const int InviteeDisplayNameFieldNumber = 5;
private string inviteeDisplayName_ = "";
public string InviteeDisplayName {
get { return inviteeDisplayName_; }
set {
inviteeDisplayName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "role" field.</summary>
public const int RoleFieldNumber = 6;
private static readonly pb::FieldCodec<uint> _repeated_role_codec
= pb::FieldCodec.ForUInt32(50);
private readonly pbc::RepeatedField<uint> role_ = new pbc::RepeatedField<uint>();
public pbc::RepeatedField<uint> Role {
get { return role_; }
}
/// <summary>Field number for the "previous_role_deprecated" field.</summary>
public const int PreviousRoleDeprecatedFieldNumber = 7;
private static readonly pb::FieldCodec<uint> _repeated_previousRoleDeprecated_codec
= pb::FieldCodec.ForUInt32(58);
private readonly pbc::RepeatedField<uint> previousRoleDeprecated_ = new pbc::RepeatedField<uint>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<uint> PreviousRoleDeprecated {
get { return previousRoleDeprecated_; }
}
/// <summary>Field number for the "friend_params" field.</summary>
public const int FriendParamsFieldNumber = 103;
private global::Bgs.Protocol.Friends.V1.FriendInvitationParams friendParams_;
public global::Bgs.Protocol.Friends.V1.FriendInvitationParams FriendParams {
get { return friendParams_; }
set {
friendParams_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as FriendInvitationParams);
}
public bool Equals(FriendInvitationParams other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (TargetEmail != other.TargetEmail) return false;
if (TargetBattleTag != other.TargetBattleTag) return false;
if (InviterBattleTag != other.InviterBattleTag) return false;
if (InviterFullName != other.InviterFullName) return false;
if (InviteeDisplayName != other.InviteeDisplayName) return false;
if(!role_.Equals(other.role_)) return false;
if(!previousRoleDeprecated_.Equals(other.previousRoleDeprecated_)) return false;
if (!object.Equals(FriendParams, other.FriendParams)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (TargetEmail.Length != 0) hash ^= TargetEmail.GetHashCode();
if (TargetBattleTag.Length != 0) hash ^= TargetBattleTag.GetHashCode();
if (InviterBattleTag.Length != 0) hash ^= InviterBattleTag.GetHashCode();
if (InviterFullName.Length != 0) hash ^= InviterFullName.GetHashCode();
if (InviteeDisplayName.Length != 0) hash ^= InviteeDisplayName.GetHashCode();
hash ^= role_.GetHashCode();
hash ^= previousRoleDeprecated_.GetHashCode();
if (friendParams_ != null) hash ^= FriendParams.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (TargetEmail.Length != 0) {
output.WriteRawTag(10);
output.WriteString(TargetEmail);
}
if (TargetBattleTag.Length != 0) {
output.WriteRawTag(18);
output.WriteString(TargetBattleTag);
}
if (InviterBattleTag.Length != 0) {
output.WriteRawTag(26);
output.WriteString(InviterBattleTag);
}
if (InviterFullName.Length != 0) {
output.WriteRawTag(34);
output.WriteString(InviterFullName);
}
if (InviteeDisplayName.Length != 0) {
output.WriteRawTag(42);
output.WriteString(InviteeDisplayName);
}
role_.WriteTo(output, _repeated_role_codec);
previousRoleDeprecated_.WriteTo(output, _repeated_previousRoleDeprecated_codec);
if (friendParams_ != null) {
output.WriteRawTag(186, 6);
output.WriteMessage(FriendParams);
}
}
public int CalculateSize() {
int size = 0;
if (TargetEmail.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TargetEmail);
}
if (TargetBattleTag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(TargetBattleTag);
}
if (InviterBattleTag.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(InviterBattleTag);
}
if (InviterFullName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(InviterFullName);
}
if (InviteeDisplayName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(InviteeDisplayName);
}
size += role_.CalculateSize(_repeated_role_codec);
size += previousRoleDeprecated_.CalculateSize(_repeated_previousRoleDeprecated_codec);
if (friendParams_ != null) {
size += 2 + pb::CodedOutputStream.ComputeMessageSize(FriendParams);
}
return size;
}
public void MergeFrom(FriendInvitationParams other) {
if (other == null) {
return;
}
if (other.TargetEmail.Length != 0) {
TargetEmail = other.TargetEmail;
}
if (other.TargetBattleTag.Length != 0) {
TargetBattleTag = other.TargetBattleTag;
}
if (other.InviterBattleTag.Length != 0) {
InviterBattleTag = other.InviterBattleTag;
}
if (other.InviterFullName.Length != 0) {
InviterFullName = other.InviterFullName;
}
if (other.InviteeDisplayName.Length != 0) {
InviteeDisplayName = other.InviteeDisplayName;
}
role_.Add(other.role_);
previousRoleDeprecated_.Add(other.previousRoleDeprecated_);
if (other.friendParams_ != null) {
if (friendParams_ == null) {
friendParams_ = new global::Bgs.Protocol.Friends.V1.FriendInvitationParams();
}
FriendParams.MergeFrom(other.FriendParams);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
TargetEmail = input.ReadString();
break;
}
case 18: {
TargetBattleTag = input.ReadString();
break;
}
case 26: {
InviterBattleTag = input.ReadString();
break;
}
case 34: {
InviterFullName = input.ReadString();
break;
}
case 42: {
InviteeDisplayName = input.ReadString();
break;
}
case 50:
case 48: {
role_.AddEntriesFrom(input, _repeated_role_codec);
break;
}
case 58:
case 56: {
previousRoleDeprecated_.AddEntriesFrom(input, _repeated_previousRoleDeprecated_codec);
break;
}
case 826: {
if (friendParams_ == null) {
friendParams_ = new global::Bgs.Protocol.Friends.V1.FriendInvitationParams();
}
input.ReadMessage(friendParams_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System;
using InMobiAds.Editor.ThirdParty.xcodeapi.PBX;
namespace InMobiAds.Editor.ThirdParty.xcodeapi
{
using PBX;
using PBXBuildFileSection = KnownSectionBase<PBXBuildFile>;
using PBXFileReferenceSection = KnownSectionBase<PBXFileReference>;
using PBXGroupSection = KnownSectionBase<PBXGroup>;
using PBXContainerItemProxySection = KnownSectionBase<PBXContainerItemProxy>;
using PBXReferenceProxySection = KnownSectionBase<PBXReferenceProxy>;
using PBXSourcesBuildPhaseSection = KnownSectionBase<PBXSourcesBuildPhase>;
using PBXFrameworksBuildPhaseSection= KnownSectionBase<PBXFrameworksBuildPhase>;
using PBXResourcesBuildPhaseSection = KnownSectionBase<PBXResourcesBuildPhase>;
using PBXCopyFilesBuildPhaseSection = KnownSectionBase<PBXCopyFilesBuildPhase>;
using PBXShellScriptBuildPhaseSection = KnownSectionBase<PBXShellScriptBuildPhase>;
using PBXVariantGroupSection = KnownSectionBase<PBXVariantGroup>;
using PBXNativeTargetSection = KnownSectionBase<PBXNativeTarget>;
using PBXTargetDependencySection = KnownSectionBase<PBXTargetDependency>;
using XCBuildConfigurationSection = KnownSectionBase<XCBuildConfiguration>;
using XCConfigurationListSection = KnownSectionBase<XCConfigurationList>;
using UnknownSection = KnownSectionBase<PBXObject>;
// Determines the tree the given path is relative to
public enum PBXSourceTree
{
Absolute, // The path is absolute
Source, // The path is relative to the source folder
Group, // The path is relative to the folder it's in. This enum is used only internally,
// do not use it as function parameter
Build, // The path is relative to the build products folder
Developer, // The path is relative to the developer folder
Sdk // The path is relative to the sdk folder
};
public class PBXProject
{
private Dictionary<string, SectionBase> m_Section = null;
private PBXElementDict m_RootElements = null;
private PBXElementDict m_UnknownObjects = null;
private string m_ObjectVersion = null;
private List<string> m_SectionOrder = null;
private Dictionary<string, UnknownSection> m_UnknownSections;
private PBXBuildFileSection buildFiles = null;
private PBXFileReferenceSection fileRefs = null;
private PBXGroupSection groups = null;
private PBXContainerItemProxySection containerItems = null;
private PBXReferenceProxySection references = null;
private PBXSourcesBuildPhaseSection sources = null;
private PBXFrameworksBuildPhaseSection frameworks = null;
private PBXResourcesBuildPhaseSection resources = null;
private PBXCopyFilesBuildPhaseSection copyFiles = null;
private PBXShellScriptBuildPhaseSection shellScripts = null;
private PBXNativeTargetSection nativeTargets = null;
private PBXTargetDependencySection targetDependencies = null;
private PBXVariantGroupSection variantGroups = null;
private XCBuildConfigurationSection buildConfigs = null;
private XCConfigurationListSection configs = null;
private PBXProjectSection project = null;
// FIXME: create a separate PBXObject tree to represent these relationships
// A build file can be represented only once in all *BuildPhaseSection sections, thus
// we can simplify the cache by not caring about the file extension
private Dictionary<string, Dictionary<string, PBXBuildFile>> m_FileGuidToBuildFileMap = null;
private Dictionary<string, PBXFileReference> m_ProjectPathToFileRefMap = null;
private Dictionary<string, string> m_FileRefGuidToProjectPathMap = null;
private Dictionary<PBXSourceTree, Dictionary<string, PBXFileReference>> m_RealPathToFileRefMap = null;
private Dictionary<string, PBXGroup> m_ProjectPathToGroupMap = null;
private Dictionary<string, string> m_GroupGuidToProjectPathMap = null;
private Dictionary<string, PBXGroup> m_GuidToParentGroupMap = null;
// targetGuid is the guid of the target that contains the section that contains the buildFile
void BuildFilesAdd(string targetGuid, PBXBuildFile buildFile)
{
if (!m_FileGuidToBuildFileMap.ContainsKey(targetGuid))
m_FileGuidToBuildFileMap[targetGuid] = new Dictionary<string, PBXBuildFile>();
m_FileGuidToBuildFileMap[targetGuid][buildFile.fileRef] = buildFile;
buildFiles.AddEntry(buildFile);
}
void BuildFilesRemove(string targetGuid, string fileGuid)
{
var buildFile = GetBuildFileForFileGuid(targetGuid, fileGuid);
if (buildFile != null)
{
m_FileGuidToBuildFileMap[targetGuid].Remove(buildFile.fileRef);
buildFiles.RemoveEntry(buildFile.guid);
}
}
PBXBuildFile GetBuildFileForFileGuid(string targetGuid, string fileGuid)
{
if (!m_FileGuidToBuildFileMap.ContainsKey(targetGuid))
return null;
if (!m_FileGuidToBuildFileMap[targetGuid].ContainsKey(fileGuid))
return null;
return m_FileGuidToBuildFileMap[targetGuid][fileGuid];
}
void FileRefsAdd(string realPath, string projectPath, PBXGroup parent, PBXFileReference fileRef)
{
fileRefs.AddEntry(fileRef);
m_ProjectPathToFileRefMap.Add(projectPath, fileRef);
m_FileRefGuidToProjectPathMap.Add(fileRef.guid, projectPath);
m_RealPathToFileRefMap[fileRef.tree].Add(realPath, fileRef); // FIXME
m_GuidToParentGroupMap.Add(fileRef.guid, parent);
}
void FileRefsRemove(string guid)
{
PBXFileReference fileRef = fileRefs[guid];
fileRefs.RemoveEntry(guid);
m_ProjectPathToFileRefMap.Remove(m_FileRefGuidToProjectPathMap[guid]);
m_FileRefGuidToProjectPathMap.Remove(guid);
foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees())
m_RealPathToFileRefMap[tree].Remove(fileRef.path);
m_GuidToParentGroupMap.Remove(guid);
}
void GroupsAdd(string projectPath, PBXGroup parent, PBXGroup gr)
{
m_ProjectPathToGroupMap.Add(projectPath, gr);
m_GroupGuidToProjectPathMap.Add(gr.guid, projectPath);
m_GuidToParentGroupMap.Add(gr.guid, parent);
groups.AddEntry(gr);
}
void GroupsRemove(string guid)
{
m_ProjectPathToGroupMap.Remove(m_GroupGuidToProjectPathMap[guid]);
m_GroupGuidToProjectPathMap.Remove(guid);
m_GuidToParentGroupMap.Remove(guid);
groups.RemoveEntry(guid);
}
void RefreshBuildFilesMapForBuildFileGuidList(Dictionary<string, PBXBuildFile> mapForTarget,
FileGUIDListBase list)
{
foreach (string guid in list.files)
{
var buildFile = buildFiles[guid];
mapForTarget[buildFile.fileRef] = buildFile;
}
}
void CombinePaths(string path1, PBXSourceTree tree1, string path2, PBXSourceTree tree2,
out string resPath, out PBXSourceTree resTree)
{
if (tree2 == PBXSourceTree.Group)
{
resPath = Path.Combine(path1, path2);
resTree = tree1;
return;
}
resPath = path2;
resTree = tree2;
}
void RefreshMapsForGroupChildren(string projectPath, string realPath, PBXSourceTree realPathTree, PBXGroup parent)
{
var children = new List<string>(parent.children);
foreach (string guid in children)
{
PBXFileReference fileRef = fileRefs[guid];
string pPath;
string rPath;
PBXSourceTree rTree;
if (fileRef != null)
{
pPath = Path.Combine(projectPath, fileRef.name);
CombinePaths(realPath, realPathTree, fileRef.path, fileRef.tree, out rPath, out rTree);
m_ProjectPathToFileRefMap.Add(pPath, fileRef);
m_FileRefGuidToProjectPathMap.Add(fileRef.guid, pPath);
m_RealPathToFileRefMap[rTree].Add(rPath, fileRef);
m_GuidToParentGroupMap.Add(guid, parent);
continue;
}
PBXGroup gr = groups[guid];
if (gr != null)
{
pPath = Path.Combine(projectPath, gr.name);
CombinePaths(realPath, realPathTree, gr.path, gr.tree, out rPath, out rTree);
m_ProjectPathToGroupMap.Add(pPath, gr);
m_GroupGuidToProjectPathMap.Add(gr.guid, pPath);
m_GuidToParentGroupMap.Add(guid, parent);
RefreshMapsForGroupChildren(pPath, rPath, rTree, gr);
}
}
}
void RefreshAuxMaps()
{
foreach (var targetEntry in nativeTargets.entries)
{
var map = new Dictionary<string, PBXBuildFile>();
foreach (string phaseGuid in targetEntry.Value.phases)
{
if (frameworks.entries.ContainsKey(phaseGuid))
RefreshBuildFilesMapForBuildFileGuidList(map, frameworks.entries[phaseGuid]);
if (resources.entries.ContainsKey(phaseGuid))
RefreshBuildFilesMapForBuildFileGuidList(map, resources.entries[phaseGuid]);
if (sources.entries.ContainsKey(phaseGuid))
RefreshBuildFilesMapForBuildFileGuidList(map, sources.entries[phaseGuid]);
if (copyFiles.entries.ContainsKey(phaseGuid))
RefreshBuildFilesMapForBuildFileGuidList(map, copyFiles.entries[phaseGuid]);
}
m_FileGuidToBuildFileMap[targetEntry.Key] = map;
}
RefreshMapsForGroupChildren("", "", PBXSourceTree.Source, groups[project.project.mainGroup]);
}
void Clear()
{
buildFiles = new PBXBuildFileSection("PBXBuildFile");
fileRefs = new PBXFileReferenceSection("PBXFileReference");
groups = new PBXGroupSection("PBXGroup");
containerItems = new PBXContainerItemProxySection("PBXContainerItemProxy");
references = new PBXReferenceProxySection("PBXReferenceProxy");
sources = new PBXSourcesBuildPhaseSection("PBXSourcesBuildPhase");
frameworks = new PBXFrameworksBuildPhaseSection("PBXFrameworksBuildPhase");
resources = new PBXResourcesBuildPhaseSection("PBXResourcesBuildPhase");
copyFiles = new PBXCopyFilesBuildPhaseSection("PBXCopyFilesBuildPhase");
shellScripts = new PBXShellScriptBuildPhaseSection("PBXShellScriptBuildPhase");
nativeTargets = new PBXNativeTargetSection("PBXNativeTarget");
targetDependencies = new PBXTargetDependencySection("PBXTargetDependency");
variantGroups = new PBXVariantGroupSection("PBXVariantGroup");
buildConfigs = new XCBuildConfigurationSection("XCBuildConfiguration");
configs = new XCConfigurationListSection("XCConfigurationList");
project = new PBXProjectSection();
m_UnknownSections = new Dictionary<string, UnknownSection>();
m_Section = new Dictionary<string, SectionBase>
{
{ "PBXBuildFile", buildFiles },
{ "PBXFileReference", fileRefs },
{ "PBXGroup", groups },
{ "PBXContainerItemProxy", containerItems },
{ "PBXReferenceProxy", references },
{ "PBXSourcesBuildPhase", sources },
{ "PBXFrameworksBuildPhase", frameworks },
{ "PBXResourcesBuildPhase", resources },
{ "PBXCopyFilesBuildPhase", copyFiles },
{ "PBXShellScriptBuildPhase", shellScripts },
{ "PBXNativeTarget", nativeTargets },
{ "PBXTargetDependency", targetDependencies },
{ "PBXVariantGroup", variantGroups },
{ "XCBuildConfiguration", buildConfigs },
{ "XCConfigurationList", configs },
{ "PBXProject", project },
};
m_RootElements = new PBXElementDict();
m_UnknownObjects = new PBXElementDict();
m_ObjectVersion = null;
m_SectionOrder = new List<string>{
"PBXBuildFile", "PBXContainerItemProxy", "PBXCopyFilesBuildPhase", "PBXFileReference",
"PBXFrameworksBuildPhase", "PBXGroup", "PBXNativeTarget", "PBXProject", "PBXReferenceProxy",
"PBXResourcesBuildPhase", "PBXShellScriptBuildPhase", "PBXSourcesBuildPhase", "PBXTargetDependency",
"PBXVariantGroup", "XCBuildConfiguration", "XCConfigurationList"
};
m_FileGuidToBuildFileMap = new Dictionary<string, Dictionary<string, PBXBuildFile>>();
m_ProjectPathToFileRefMap = new Dictionary<string, PBXFileReference>();
m_FileRefGuidToProjectPathMap = new Dictionary<string, string>();
m_RealPathToFileRefMap = new Dictionary<PBXSourceTree, Dictionary<string, PBXFileReference>>();
foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees())
m_RealPathToFileRefMap.Add(tree, new Dictionary<string, PBXFileReference>());
m_ProjectPathToGroupMap = new Dictionary<string, PBXGroup>();
m_GroupGuidToProjectPathMap = new Dictionary<string, string>();
m_GuidToParentGroupMap = new Dictionary<string, PBXGroup>();
}
public static string GetPBXProjectPath(string buildPath)
{
return Path.Combine(buildPath, "Unity-iPhone/project.pbxproj");
}
public static string GetUnityTargetName()
{
return "Unity-iPhone";
}
public static string GetUnityTestTargetName()
{
return "Unity-iPhone Tests";
}
/// Returns a guid identifying native target with name @a name
public string TargetGuidByName(string name)
{
foreach (var entry in nativeTargets.entries)
if (entry.Value.name == name)
return entry.Key;
return null;
}
private FileGUIDListBase BuildSection(PBXNativeTarget target, string path)
{
string ext = Path.GetExtension(path);
var phase = FileTypeUtils.GetFileType(ext);
switch (phase) {
case PBXFileType.Framework:
foreach (var guid in target.phases)
if (frameworks.entries.ContainsKey(guid))
return frameworks.entries[guid];
break;
case PBXFileType.Resource:
foreach (var guid in target.phases)
if (resources.entries.ContainsKey(guid))
return resources.entries[guid];
break;
case PBXFileType.Source:
foreach (var guid in target.phases)
if (sources.entries.ContainsKey(guid))
return sources.entries[guid];
break;
case PBXFileType.CopyFile:
foreach (var guid in target.phases)
if (copyFiles.entries.ContainsKey(guid))
return copyFiles.entries[guid];
break;
}
return null;
}
public static bool IsKnownExtension(string ext)
{
return FileTypeUtils.IsKnownExtension(ext);
}
public static bool IsBuildable(string ext)
{
return FileTypeUtils.IsBuildable(ext);
}
// The same file can be referred to by more than one project path.
private string AddFileImpl(string path, string projectPath, PBXSourceTree tree)
{
path = FixSlashesInPath(path);
projectPath = FixSlashesInPath(projectPath);
string ext = Path.GetExtension(path);
if (ext != Path.GetExtension(projectPath))
throw new Exception("Project and real path extensions do not match");
string guid = FindFileGuidByProjectPath(projectPath);
if (guid == null)
guid = FindFileGuidByRealPath(path);
if (guid == null)
{
PBXFileReference fileRef = PBXFileReference.CreateFromFile(path, GetFilenameFromPath(projectPath), tree);
PBXGroup parent = CreateSourceGroup(GetDirectoryFromPath(projectPath));
parent.children.AddGUID(fileRef.guid);
FileRefsAdd(path, projectPath, parent, fileRef);
guid = fileRef.guid;
}
return guid;
}
// The extension of the files identified by path and projectPath must be the same.
public string AddFile(string path, string projectPath)
{
return AddFileImpl(path, projectPath, PBXSourceTree.Source);
}
// sourceTree must not be PBXSourceTree.Group
public string AddFile(string path, string projectPath, PBXSourceTree sourceTree)
{
if (sourceTree == PBXSourceTree.Group)
throw new Exception("sourceTree must not be PBXSourceTree.Group");
return AddFileImpl(path, projectPath, sourceTree);
}
private void AddBuildFileImpl(string targetGuid, string fileGuid, bool weak, string compileFlags)
{
PBXNativeTarget target = nativeTargets[targetGuid];
string ext = Path.GetExtension(fileRefs[fileGuid].path);
if (FileTypeUtils.IsBuildable(ext) &&
GetBuildFileForFileGuid(targetGuid, fileGuid) == null)
{
PBXBuildFile buildFile = PBXBuildFile.CreateFromFile(fileGuid, weak, compileFlags);
BuildFilesAdd(targetGuid, buildFile);
BuildSection(target, ext).files.AddGUID(buildFile.guid);
}
}
public void AddFileToBuild(string targetGuid, string fileGuid)
{
AddBuildFileImpl(targetGuid, fileGuid, false, null);
}
public void AddFileToBuildWithFlags(string targetGuid, string fileGuid, string compileFlags)
{
AddBuildFileImpl(targetGuid, fileGuid, false, compileFlags);
}
// returns null on error
// FIXME: at the moment returns all flags as the first element of the array
public List<string> GetCompileFlagsForFile(string targetGuid, string fileGuid)
{
var buildFile = GetBuildFileForFileGuid(targetGuid, fileGuid);
if (buildFile == null)
return null;
if (buildFile.compileFlags == null)
return new List<string>();
return new List<string>{buildFile.compileFlags};
}
public void SetCompileFlagsForFile(string targetGuid, string fileGuid, List<string> compileFlags)
{
var buildFile = GetBuildFileForFileGuid(targetGuid, fileGuid);
if (buildFile == null)
return;
buildFile.compileFlags = string.Join(" ", compileFlags.ToArray());
}
public bool ContainsFileByRealPath(string path)
{
return FindFileGuidByRealPath(path) != null;
}
// sourceTree must not be PBXSourceTree.Group
public bool ContainsFileByRealPath(string path, PBXSourceTree sourceTree)
{
if (sourceTree == PBXSourceTree.Group)
throw new Exception("sourceTree must not be PBXSourceTree.Group");
return FindFileGuidByRealPath(path, sourceTree) != null;
}
public bool ContainsFileByProjectPath(string path)
{
return FindFileGuidByProjectPath(path) != null;
}
public bool HasFramework(string framework)
{
return ContainsFileByRealPath("System/Library/Frameworks/"+framework);
}
/// The framework must be specified with the '.framework' extension
public void AddFrameworkToProject(string targetGuid, string framework, bool weak)
{
string fileGuid = AddFile("System/Library/Frameworks/"+framework, "Frameworks/"+framework, PBXSourceTree.Sdk);
AddBuildFileImpl(targetGuid, fileGuid, weak, null);
}
private string GetDirectoryFromPath(string path)
{
int pos = path.LastIndexOf('/');
if (pos == -1)
return "";
else
return path.Substring(0, pos);
}
private string GetFilenameFromPath(string path)
{
int pos = path.LastIndexOf('/');
if (pos == -1)
return path;
else
return path.Substring(pos + 1);
}
// sourceTree must not be PBXSourceTree.Group
public string FindFileGuidByRealPath(string path, PBXSourceTree sourceTree)
{
if (sourceTree == PBXSourceTree.Group)
throw new Exception("sourceTree must not be PBXSourceTree.Group");
path = FixSlashesInPath(path);
if (m_RealPathToFileRefMap[sourceTree].ContainsKey(path))
return m_RealPathToFileRefMap[sourceTree][path].guid;
return null;
}
public string FindFileGuidByRealPath(string path)
{
path = FixSlashesInPath(path);
foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees())
{
string res = FindFileGuidByRealPath(path, tree);
if (res != null)
return res;
}
return null;
}
public string FindFileGuidByProjectPath(string path)
{
path = FixSlashesInPath(path);
if (m_ProjectPathToFileRefMap.ContainsKey(path))
return m_ProjectPathToFileRefMap[path].guid;
return null;
}
public void RemoveFileFromBuild(string targetGuid, string fileGuid)
{
var buildFile = GetBuildFileForFileGuid(targetGuid, fileGuid);
if (buildFile == null)
return;
BuildFilesRemove(targetGuid, fileGuid);
string buildGuid = buildFile.guid;
if (buildGuid != null)
{
foreach (var section in sources.entries)
section.Value.files.RemoveGUID(buildGuid);
foreach (var section in resources.entries)
section.Value.files.RemoveGUID(buildGuid);
foreach (var section in copyFiles.entries)
section.Value.files.RemoveGUID(buildGuid);
foreach (var section in frameworks.entries)
section.Value.files.RemoveGUID(buildGuid);
}
}
public void RemoveFile(string fileGuid)
{
if (fileGuid == null)
return;
// remove from parent
PBXGroup parent = m_GuidToParentGroupMap[fileGuid];
if (parent != null)
parent.children.RemoveGUID(fileGuid);
RemoveGroupIfEmpty(parent);
// remove actual file
foreach (var target in nativeTargets.entries)
RemoveFileFromBuild(target.Value.guid, fileGuid);
FileRefsRemove(fileGuid);
}
void RemoveGroupIfEmpty(PBXGroup gr)
{
if (gr.children.Count == 0 && gr.guid != project.project.mainGroup)
{
// remove from parent
PBXGroup parent = m_GuidToParentGroupMap[gr.guid];
parent.children.RemoveGUID(gr.guid);
RemoveGroupIfEmpty(parent);
// remove actual group
GroupsRemove(gr.guid);
}
}
private void RemoveGroupChildrenRecursive(PBXGroup parent)
{
List<string> children = new List<string>(parent.children);
parent.children.Clear();
foreach (string guid in children)
{
PBXFileReference file = fileRefs[guid];
if (file != null)
{
foreach (var target in nativeTargets.entries)
RemoveFileFromBuild(target.Value.guid, guid);
FileRefsRemove(guid);
continue;
}
PBXGroup gr = groups[guid];
if (gr != null)
{
RemoveGroupChildrenRecursive(gr);
GroupsRemove(parent.guid);
continue;
}
}
}
internal void RemoveFilesByProjectPathRecursive(string projectPath)
{
PBXGroup gr = GetSourceGroup(projectPath);
if (gr == null)
return;
RemoveGroupChildrenRecursive(gr);
RemoveGroupIfEmpty(gr);
}
private PBXGroup GetPBXGroupChildByName(PBXGroup group, string name)
{
foreach (string guid in group.children)
{
var gr = groups[guid];
if (gr != null && gr.name == name)
return gr;
}
return null;
}
/// Returns the source group identified by sourceGroup. If sourceGroup is empty or null,
/// root group is returned. If no group is found, null is returned.
private PBXGroup GetSourceGroup(string sourceGroup)
{
sourceGroup = FixSlashesInPath(sourceGroup);
if (sourceGroup == null || sourceGroup == "")
return groups[project.project.mainGroup];
if (m_ProjectPathToGroupMap.ContainsKey(sourceGroup))
return m_ProjectPathToGroupMap[sourceGroup];
return null;
}
/// Creates source group identified by sourceGroup, if needed, and returns it.
/// If sourceGroup is empty or null, root group is returned
private PBXGroup CreateSourceGroup(string sourceGroup)
{
sourceGroup = FixSlashesInPath(sourceGroup);
if (m_ProjectPathToGroupMap.ContainsKey(sourceGroup))
return m_ProjectPathToGroupMap[sourceGroup];
PBXGroup gr = groups[project.project.mainGroup];
if (sourceGroup == null || sourceGroup == "")
return gr;
string[] elements = sourceGroup.Trim('/').Split('/');
string projectPath = null;
foreach (string pathEl in elements)
{
if (projectPath == null)
projectPath = pathEl;
else
projectPath += "/" + pathEl;
PBXGroup child = GetPBXGroupChildByName(gr, pathEl);
if (child != null)
gr = child;
else
{
PBXGroup newGroup = PBXGroup.Create(pathEl, pathEl, PBXSourceTree.Group);
gr.children.AddGUID(newGroup.guid);
GroupsAdd(projectPath, gr, newGroup);
gr = newGroup;
}
}
return gr;
}
// sourceTree must not be PBXSourceTree.Group
public void AddExternalProjectDependency(string path, string projectPath, PBXSourceTree sourceTree)
{
if (sourceTree == PBXSourceTree.Group)
throw new Exception("sourceTree must not be PBXSourceTree.Group");
path = FixSlashesInPath(path);
projectPath = FixSlashesInPath(projectPath);
// note: we are duplicating products group for the project reference. Otherwise Xcode crashes.
PBXGroup productGroup = PBXGroup.CreateRelative("Products");
groups.AddEntry(productGroup); // don't use GroupsAdd here
PBXFileReference fileRef = PBXFileReference.CreateFromFile(path, Path.GetFileName(projectPath),
sourceTree);
FileRefsAdd(path, projectPath, null, fileRef);
CreateSourceGroup(GetDirectoryFromPath(projectPath)).children.AddGUID(fileRef.guid);
project.project.AddReference(productGroup.guid, fileRef.guid);
}
/** This function must be called only after the project the library is in has
been added as a dependency via AddExternalProjectDependency. projectPath must be
the same as the 'path' parameter passed to the AddExternalProjectDependency.
remoteFileGuid must be the guid of the referenced file as specified in
PBXFileReference section of the external project
TODO: wtf. is remoteInfo entry in PBXContainerItemProxy? Is in referenced project name or
referenced library name without extension?
*/
public void AddExternalLibraryDependency(string targetGuid, string filename, string remoteFileGuid, string projectPath,
string remoteInfo)
{
PBXNativeTarget target = nativeTargets[targetGuid];
filename = FixSlashesInPath(filename);
projectPath = FixSlashesInPath(projectPath);
// find the products group to put the new library in
string projectGuid = FindFileGuidByRealPath(projectPath);
if (projectGuid == null)
throw new Exception("No such project");
string productsGroupGuid = null;
foreach (var proj in project.project.projectReferences)
{
if (proj.projectRef == projectGuid)
{
productsGroupGuid = proj.group;
break;
}
}
if (productsGroupGuid == null)
throw new Exception("Malformed project: no project in project references");
PBXGroup productGroup = groups[productsGroupGuid];
// verify file extension
string ext = Path.GetExtension(filename);
if (!FileTypeUtils.IsBuildable(ext))
throw new Exception("Wrong file extension");
// create ContainerItemProxy object
var container = PBXContainerItemProxy.Create(projectGuid, "2", remoteFileGuid, remoteInfo);
containerItems.AddEntry(container);
// create a reference and build file for the library
string typeName = FileTypeUtils.GetTypeName(ext);
var libRef = PBXReferenceProxy.Create(filename, typeName, container.guid, "BUILT_PRODUCTS_DIR");
references.AddEntry(libRef);
PBXBuildFile libBuildFile = PBXBuildFile.CreateFromFile(libRef.guid, false, null);
BuildFilesAdd(targetGuid, libBuildFile);
BuildSection(target, ext).files.AddGUID(libBuildFile.guid);
// add to products folder
productGroup.children.AddGUID(libRef.guid);
}
private void SetDefaultAppExtensionReleaseBuildFlags(XCBuildConfiguration config, string infoPlistPath)
{
config.AddProperty("ALWAYS_SEARCH_USER_PATHS", "NO");
config.AddProperty("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x");
config.AddProperty("CLANG_CXX_LIBRARY", "libc++");
config.AddProperty("CLANG_ENABLE_MODULES", "YES");
config.AddProperty("CLANG_ENABLE_OBJC_ARC", "YES");
config.AddProperty("CLANG_WARN_BOOL_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_CONSTANT_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR");
config.AddProperty("CLANG_WARN_EMPTY_BODY", "YES");
config.AddProperty("CLANG_WARN_ENUM_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_INT_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR");
config.AddProperty("CLANG_WARN_UNREACHABLE_CODE", "YES");
config.AddProperty("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES");
config.AddProperty("COPY_PHASE_STRIP", "YES");
config.AddProperty("ENABLE_NS_ASSERTIONS", "NO");
config.AddProperty("ENABLE_STRICT_OBJC_MSGSEND", "YES");
config.AddProperty("GCC_C_LANGUAGE_STANDARD", "gnu99");
config.AddProperty("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES");
config.AddProperty("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR");
config.AddProperty("GCC_WARN_UNDECLARED_SELECTOR", "YES");
config.AddProperty("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE");
config.AddProperty("GCC_WARN_UNUSED_FUNCTION", "YES");
config.AddProperty("INFOPLIST_FILE", infoPlistPath);
config.AddProperty("IPHONEOS_DEPLOYMENT_TARGET", "8.0");
config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks");
config.AddProperty("MTL_ENABLE_DEBUG_INFO", "NO");
config.AddProperty("PRODUCT_NAME", "$(TARGET_NAME)");
config.AddProperty("SKIP_INSTALL", "YES");
config.AddProperty("VALIDATE_PRODUCT", "YES");
}
private void SetDefaultAppExtensionDebugBuildFlags(XCBuildConfiguration config, string infoPlistPath)
{
config.AddProperty("ALWAYS_SEARCH_USER_PATHS", "NO");
config.AddProperty("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x");
config.AddProperty("CLANG_CXX_LIBRARY", "libc++");
config.AddProperty("CLANG_ENABLE_MODULES", "YES");
config.AddProperty("CLANG_ENABLE_OBJC_ARC", "YES");
config.AddProperty("CLANG_WARN_BOOL_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_CONSTANT_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR");
config.AddProperty("CLANG_WARN_EMPTY_BODY", "YES");
config.AddProperty("CLANG_WARN_ENUM_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_INT_CONVERSION", "YES");
config.AddProperty("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR");
config.AddProperty("CLANG_WARN_UNREACHABLE_CODE", "YES");
config.AddProperty("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES");
config.AddProperty("COPY_PHASE_STRIP", "NO");
config.AddProperty("ENABLE_STRICT_OBJC_MSGSEND", "YES");
config.AddProperty("GCC_C_LANGUAGE_STANDARD", "gnu99");
config.AddProperty("GCC_DYNAMIC_NO_PIC", "NO");
config.AddProperty("GCC_OPTIMIZATION_LEVEL", "0");
config.AddProperty("GCC_PREPROCESSOR_DEFINITIONS", "DEBUG=1");
config.AddProperty("GCC_PREPROCESSOR_DEFINITIONS", "$(inherited)");
config.AddProperty("GCC_SYMBOLS_PRIVATE_EXTERN", "NO");
config.AddProperty("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES");
config.AddProperty("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR");
config.AddProperty("GCC_WARN_UNDECLARED_SELECTOR", "YES");
config.AddProperty("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE");
config.AddProperty("GCC_WARN_UNUSED_FUNCTION", "YES");
config.AddProperty("INFOPLIST_FILE", infoPlistPath);
config.AddProperty("IPHONEOS_DEPLOYMENT_TARGET", "8.0");
config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "$(inherited)");
config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks");
config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "@executable_path/../../Frameworks");
config.AddProperty("MTL_ENABLE_DEBUG_INFO", "YES");
config.AddProperty("ONLY_ACTIVE_ARCH", "YES");
config.AddProperty("PRODUCT_NAME", "$(TARGET_NAME)");
config.AddProperty("SKIP_INSTALL", "YES");
}
// Returns the guid of the new target
internal string AddAppExtension(string mainTarget, string name, string infoPlistPath)
{
string ext = ".appex";
string fullName = name + ext;
var productFileRef = PBXFileReference.CreateFromFile("Products/" + fullName, "Products/" + fullName,
PBXSourceTree.Group);
var releaseBuildConfig = XCBuildConfiguration.Create("Release");
buildConfigs.AddEntry(releaseBuildConfig);
SetDefaultAppExtensionReleaseBuildFlags(releaseBuildConfig, infoPlistPath);
var debugBuildConfig = XCBuildConfiguration.Create("Debug");
buildConfigs.AddEntry(debugBuildConfig);
SetDefaultAppExtensionDebugBuildFlags(debugBuildConfig, infoPlistPath);
var buildConfigList = XCConfigurationList.Create();
configs.AddEntry(buildConfigList);
buildConfigList.buildConfigs.AddGUID(releaseBuildConfig.guid);
buildConfigList.buildConfigs.AddGUID(debugBuildConfig.guid);
var newTarget = PBXNativeTarget.Create(name, productFileRef.guid, "com.apple.product-type.app-extension", buildConfigList.guid);
nativeTargets.AddEntry(newTarget);
project.project.targets.Add(newTarget.guid);
var sourcesBuildPhase = PBXSourcesBuildPhase.Create();
sources.AddEntry(sourcesBuildPhase);
newTarget.phases.AddGUID(sourcesBuildPhase.guid);
var resourcesBuildPhase = PBXResourcesBuildPhase.Create();
resources.AddEntry(resourcesBuildPhase);
newTarget.phases.AddGUID(resourcesBuildPhase.guid);
var frameworksBuildPhase = PBXFrameworksBuildPhase.Create();
frameworks.AddEntry(frameworksBuildPhase);
newTarget.phases.AddGUID(frameworksBuildPhase.guid);
var copyFilesBuildPhase = PBXCopyFilesBuildPhase.Create("Embed App Extensions", "13");
copyFiles.AddEntry(copyFilesBuildPhase);
nativeTargets[mainTarget].phases.AddGUID(copyFilesBuildPhase.guid);
var containerProxy = PBXContainerItemProxy.Create(project.project.guid, "1", newTarget.guid, name);
containerItems.AddEntry(containerProxy);
var targetDependency = PBXTargetDependency.Create(newTarget.guid, containerProxy.guid);
targetDependencies.AddEntry(targetDependency);
nativeTargets[mainTarget].dependencies.AddGUID(targetDependency.guid);
AddFile(fullName, "Products/" + fullName, PBXSourceTree.Build);
var buildAppCopy = PBXBuildFile.CreateFromFile(FindFileGuidByProjectPath("Products/" + fullName), false, "");
BuildFilesAdd(mainTarget, buildAppCopy);
copyFilesBuildPhase.files.AddGUID(buildAppCopy.guid);
AddFile(infoPlistPath, name + "/Supporting Files/Info.plist", PBXSourceTree.Group);
return newTarget.guid;
}
public string BuildConfigByName(string targetGuid, string name)
{
PBXNativeTarget target = nativeTargets[targetGuid];
foreach (string guid in configs[target.buildConfigList].buildConfigs)
{
var buildConfig = buildConfigs[guid];
if (buildConfig != null && buildConfig.name == name)
return buildConfig.guid;
}
return null;
}
// Adds an item to a build property that contains a value list. Duplicate build properties
// are ignored. Values for name "LIBRARY_SEARCH_PATHS" are quoted if they contain spaces.
public void AddBuildProperty(string targetGuid, string name, string value)
{
PBXNativeTarget target = nativeTargets[targetGuid];
foreach (string guid in configs[target.buildConfigList].buildConfigs)
buildConfigs[guid].AddProperty(name, value);
}
public void AddBuildProperty(string[] targetGuids, string name, string value)
{
foreach (string t in targetGuids)
AddBuildProperty(t, name, value);
}
public void AddBuildPropertyForConfig(string configGuid, string name, string value)
{
buildConfigs[configGuid].AddProperty(name, value);
}
public void AddBuildPropertyForConfig(string[] configGuids, string name, string value)
{
foreach (string guid in configGuids)
AddBuildPropertyForConfig(guid, name, value);
}
public void SetBuildProperty(string targetGuid, string name, string value)
{
PBXNativeTarget target = nativeTargets[targetGuid];
foreach (string guid in configs[target.buildConfigList].buildConfigs)
buildConfigs[guid].SetProperty(name, value);
}
public void SetBuildProperty(string[] targetGuids, string name, string value)
{
foreach (string t in targetGuids)
SetBuildProperty(t, name, value);
}
public void SetBuildPropertyForConfig(string configGuid, string name, string value)
{
buildConfigs[configGuid].SetProperty(name, value);
}
public void SetBuildPropertyForConfig(string[] configGuids, string name, string value)
{
foreach (string guid in configGuids)
SetBuildPropertyForConfig(guid, name, value);
}
/// Interprets the value of the given property as a set of space-delimited strings, then
/// removes strings equal to items to removeValues and adds strings in addValues.
public void UpdateBuildProperty(string targetGuid, string name, string[] addValues, string[] removeValues)
{
PBXNativeTarget target = nativeTargets[targetGuid];
foreach (string guid in configs[target.buildConfigList].buildConfigs)
buildConfigs[guid].UpdateProperties(name, addValues, removeValues);
}
public void UpdateBuildProperty(string[] targetGuids, string name, string[] addValues, string[] removeValues)
{
foreach (string t in targetGuids)
UpdateBuildProperty(t, name, addValues, removeValues);
}
public void UpdateBuildPropertyForConfig(string configGuid, string name, string[] addValues, string[] removeValues)
{
buildConfigs[configGuid].UpdateProperties(name, addValues, removeValues);
}
public void UpdateBuildPropertyForConfig(string[] configGuids, string name, string[] addValues, string[] removeValues)
{
foreach (string guid in configGuids)
UpdateBuildProperty(guid, name, addValues, removeValues);
}
/// Replaces '\' with '/'. We need to apply this function to all paths that come from the user
/// of the API because we store paths to pbxproj and on windows we may get path with '\' slashes
/// instead of '/' slashes
private static string FixSlashesInPath(string path)
{
if (path == null)
return null;
return path.Replace('\\', '/');
}
private void BuildCommentMapForBuildFiles(GUIDToCommentMap comments, List<string> guids, string sectName)
{
foreach (var guid in guids)
{
var buildFile = buildFiles[guid];
if (buildFile != null)
{
var fileRef = fileRefs[buildFile.fileRef];
if (fileRef != null)
comments.Add(guid, String.Format("{0} in {1}", fileRef.name, sectName));
else
{
var reference = references[buildFile.fileRef];
if (reference != null)
comments.Add(guid, String.Format("{0} in {1}", reference.path, sectName));
}
}
}
}
private GUIDToCommentMap BuildCommentMap()
{
GUIDToCommentMap comments = new GUIDToCommentMap();
// buildFiles are handled below
// filerefs are handled below
foreach (var e in groups.entries.Values)
comments.Add(e.guid, e.name);
foreach (var e in containerItems.entries.Values)
comments.Add(e.guid, "PBXContainerItemProxy");
foreach (var e in references.entries.Values)
comments.Add(e.guid, e.path);
foreach (var e in sources.entries.Values)
{
comments.Add(e.guid, "Sources");
BuildCommentMapForBuildFiles(comments, e.files, "Sources");
}
foreach (var e in resources.entries.Values)
{
comments.Add(e.guid, "Resources");
BuildCommentMapForBuildFiles(comments, e.files, "Resources");
}
foreach (var e in frameworks.entries.Values)
{
comments.Add(e.guid, "Frameworks");
BuildCommentMapForBuildFiles(comments, e.files, "Frameworks");
}
foreach (var e in copyFiles.entries.Values)
{
string sectName = e.name;
if (sectName == null)
sectName = "CopyFiles";
comments.Add(e.guid, sectName);
BuildCommentMapForBuildFiles(comments, e.files, sectName);
}
foreach (var e in shellScripts.entries.Values)
comments.Add(e.guid, "ShellScript");
foreach (var e in targetDependencies.entries.Values)
comments.Add(e.guid, "PBXTargetDependency");
foreach (var e in nativeTargets.entries.Values)
{
comments.Add(e.guid, e.name);
comments.Add(e.buildConfigList, String.Format("Build configuration list for PBXNativeTarget \"{0}\"", e.name));
}
foreach (var e in variantGroups.entries.Values)
comments.Add(e.guid, e.name);
foreach (var e in buildConfigs.entries.Values)
comments.Add(e.guid, e.name);
foreach (var e in project.entries.Values)
{
comments.Add(e.guid, "Project object");
comments.Add(e.buildConfigList, "Build configuration list for PBXProject \"Unity-iPhone\""); // FIXME: project name is hardcoded
}
foreach (var e in fileRefs.entries.Values)
comments.Add(e.guid, e.name);
if (m_RootElements.Contains("rootObject") && m_RootElements["rootObject"] is PBXElementString)
comments.Add(m_RootElements["rootObject"].AsString(), "Project object");
return comments;
}
public void ReadFromFile(string path)
{
ReadFromString(File.ReadAllText(path));
}
public void ReadFromString(string src)
{
TextReader sr = new StringReader(src);
ReadFromStream(sr);
}
private static PBXElementDict ParseContent(string content)
{
TokenList tokens = Lexer.Tokenize(content);
var parser = new Parser(tokens);
TreeAST ast = parser.ParseTree();
return Serializer.ParseTreeAST(ast, tokens, content);
}
public void ReadFromStream(TextReader sr)
{
Clear();
m_RootElements = ParseContent(sr.ReadToEnd());
if (!m_RootElements.Contains("objects"))
throw new Exception("Invalid PBX project file: no objects element");
var objects = m_RootElements["objects"].AsDict();
m_RootElements.Remove("objects");
m_RootElements.SetString("objects", "OBJMARKER");
if (m_RootElements.Contains("objectVersion"))
{
m_ObjectVersion = m_RootElements["objectVersion"].AsString();
m_RootElements.Remove("objectVersion");
}
var allGuids = new List<string>();
string prevSectionName = null;
foreach (var kv in objects.values)
{
allGuids.Add(kv.Key);
var el = kv.Value;
if (!(el is PBXElementDict) || !el.AsDict().Contains("isa"))
{
m_UnknownObjects.values.Add(kv.Key, el);
continue;
}
var dict = el.AsDict();
var sectionName = dict["isa"].AsString();
if (m_Section.ContainsKey(sectionName))
{
var section = m_Section[sectionName];
section.AddObject(kv.Key, dict);
}
else
{
UnknownSection section;
if (m_UnknownSections.ContainsKey(sectionName))
section = m_UnknownSections[sectionName];
else
{
section = new UnknownSection(sectionName);
m_UnknownSections.Add(sectionName, section);
}
section.AddObject(kv.Key, dict);
// update section order
if (!m_SectionOrder.Contains(sectionName))
{
int pos = 0;
if (prevSectionName != null)
{
// this never fails, because we already added any previous unknown sections
// to m_SectionOrder
pos = m_SectionOrder.FindIndex(x => x == prevSectionName);
pos += 1;
}
m_SectionOrder.Insert(pos, sectionName);
}
}
prevSectionName = sectionName;
}
RepairStructure(allGuids);
RefreshAuxMaps();
}
public void WriteToFile(string path)
{
File.WriteAllText(path, WriteToString());
}
public void WriteToStream(TextWriter sw)
{
sw.Write(WriteToString());
}
public string WriteToString()
{
var commentMap = BuildCommentMap();
var emptyChecker = new PropertyCommentChecker();
var emptyCommentMap = new GUIDToCommentMap();
// since we need to add custom comments, the serialization is much more complex
StringBuilder objectsSb = new StringBuilder();
if (m_ObjectVersion != null) // objectVersion comes right before objects
objectsSb.AppendFormat("objectVersion = {0};\n\t", m_ObjectVersion);
objectsSb.Append("objects = {");
foreach (string sectionName in m_SectionOrder)
{
if (m_Section.ContainsKey(sectionName))
m_Section[sectionName].WriteSection(objectsSb, commentMap);
else if (m_UnknownSections.ContainsKey(sectionName))
m_UnknownSections[sectionName].WriteSection(objectsSb, commentMap);
}
foreach (var kv in m_UnknownObjects.values)
Serializer.WriteDictKeyValue(objectsSb, kv.Key, kv.Value, 2, false, emptyChecker, emptyCommentMap);
objectsSb.Append("\n\t};");
StringBuilder contentSb = new StringBuilder();
contentSb.AppendLine("// !$*UTF8*$!");
Serializer.WriteDict(contentSb, m_RootElements, 0, false,
new PropertyCommentChecker(new string[]{"rootObject/*"}), commentMap);
contentSb.AppendLine();
string content = contentSb.ToString();
content = content.Replace("objects = OBJMARKER;", objectsSb.ToString());
return content;
}
// This method walks the project structure and removes invalid entries.
void RepairStructure(List<string> allGuids)
{
var guidSet = new Dictionary<string, bool>(); // emulate HashSet on .Net 2.0
foreach (var guid in allGuids)
guidSet.Add(guid, false);
while (RepairStructureImpl(guidSet) == false)
;
}
static void RepairStructureRemoveMissingGuids(PBX.GUIDList guidList, Dictionary<string, bool> allGuids)
{
List<string> guidsToRemove = null;
foreach (var guid in guidList)
{
if (!allGuids.ContainsKey(guid))
{
if (guidsToRemove == null)
guidsToRemove = new List<string>();
guidsToRemove.Add(guid);
}
}
if (guidsToRemove != null)
{
foreach (var guid in guidsToRemove)
guidList.RemoveGUID(guid);
}
}
static void RepairStructureAnyType<T>(KnownSectionBase<T> section,
Func<T, bool> checker,
Dictionary<string, bool> allGuids, ref bool ok) where T : PBXObject, new()
{
List<string> guidsToRemove = null;
foreach (var kv in section.entries)
{
if (!checker(kv.Value))
{
if (guidsToRemove == null)
guidsToRemove = new List<string>();
guidsToRemove.Add(kv.Key);
}
}
if (guidsToRemove != null)
{
ok = false;
foreach (var guid in guidsToRemove)
{
section.RemoveEntry(guid);
allGuids.Remove(guid);
}
}
}
static void RepairStructureGuidList<T>(KnownSectionBase<T> section,
Func<T, PBX.GUIDList> listRetrieveFunc,
Dictionary<string, bool> allGuids, ref bool ok) where T : PBXObject, new()
{
Func<T, bool> checker = (T obj) =>
{
var list = listRetrieveFunc(obj);
if (list == null)
return false;
RepairStructureRemoveMissingGuids(list, allGuids);
return true;
};
RepairStructureAnyType(section, checker, allGuids, ref ok);
}
// Returns true if repair was successful
bool RepairStructureImpl(Dictionary<string, bool> allGuids)
{
bool ok = true;
// PBXBuildFile
Func<PBXBuildFile, bool> buildFilesChecker = (PBXBuildFile obj) =>
{
if (obj.fileRef == null || !allGuids.ContainsKey(obj.fileRef))
return false;
return true;
};
RepairStructureAnyType(buildFiles, buildFilesChecker, allGuids, ref ok);
// PBXFileReference / fileRefs not cleaned
// PBXGroup
RepairStructureGuidList(groups, o => o.children, allGuids, ref ok);
// PBXContainerItem / containerItems not cleaned
// PBXReferenceProxy / references not cleaned
// PBXSourcesBuildPhase
RepairStructureGuidList(sources, o => o.files, allGuids, ref ok);
// PBXFrameworksBuildPhase
RepairStructureGuidList(frameworks, o => o.files, allGuids, ref ok);
// PBXResourcesBuildPhase
RepairStructureGuidList(resources, o => o.files, allGuids, ref ok);
// PBXCopyFilesBuildPhase
RepairStructureGuidList(copyFiles, o => o.files, allGuids, ref ok);
// PBXShellScriptsBuildPhase
RepairStructureGuidList(shellScripts, o => o.files, allGuids, ref ok);
// PBXNativeTarget
RepairStructureGuidList(nativeTargets, o => o.phases, allGuids, ref ok);
// PBXTargetDependency / targetDependencies not cleaned
// PBXVariantGroup
RepairStructureGuidList(variantGroups, o => o.children, allGuids, ref ok);
// XCBuildConfiguration / buildConfigs not cleaned
// XCConfigurationList
RepairStructureGuidList(configs, o => o.buildConfigs, allGuids, ref ok);
// PBXProject project not cleaned
return ok;
}
}
} // namespace UnityEditor.iOS.Xcode
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
function WorldEditor::onSelect( %this, %obj )
{
EditorTree.addSelection( %obj );
_setShadowVizLight( %obj );
//Inspector.inspect( %obj );
if ( isObject( %obj ) && %obj.isMethod( "onEditorSelect" ) )
%obj.onEditorSelect( %this.getSelectionSize() );
EditorGui.currentEditor.onObjectSelected( %obj );
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the materialEditorList
$Tools::materialEditorList = %obj.getId();
// Used to help the Material Editor( the M.E doesn't utilize its own TS control )
// so this dirty extension is used to fake it
if ( MaterialEditorPreviewWindow.isVisible() )
MaterialEditorGui.prepareActiveObject();
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onMultiSelect( %this, %set )
{
// This is called when completing a drag selection ( on3DMouseUp )
// so we can avoid calling onSelect for every object. We can only
// do most of this stuff, like inspecting, on one object at a time anyway.
%count = %set.getCount();
%i = 0;
foreach( %obj in %set )
{
if ( %obj.isMethod( "onEditorSelect" ) )
%obj.onEditorSelect( %count );
%i ++;
EditorTree.addSelection( %obj, %i == %count );
EditorGui.currentEditor.onObjectSelected( %obj );
}
// Inform the camera
commandToServer( 'EditorOrbitCameraSelectChange', %count, %this.getSelectionCentroid() );
EditorGuiStatusBar.setSelectionObjectsByCount( EWorldEditor.getSelectionSize() );
// Update the Transform Selection window, if it is
// visible.
if( ETransformSelection.isVisible() )
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onUnSelect( %this, %obj )
{
if ( isObject( %obj ) && %obj.isMethod( "onEditorUnselect" ) )
%obj.onEditorUnselect();
EditorGui.currentEditor.onObjectDeselected( %obj );
Inspector.removeInspect( %obj );
EditorTree.removeSelection(%obj);
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onClearSelection( %this )
{
EditorGui.currentEditor.onSelectionCleared();
EditorTree.clearSelection();
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
EditorGuiStatusBar.setSelectionObjectsByCount(%this.getSelectionSize());
// Update the Transform Selection window
ETransformSelection.onSelectionChanged();
}
function WorldEditor::onSelectionCentroidChanged( %this )
{
// Inform the camera
commandToServer('EditorOrbitCameraSelectChange', %this.getSelectionSize(), %this.getSelectionCentroid());
// Refresh inspector.
Inspector.refresh();
}
//////////////////////////////////////////////////////////////////////////
function WorldEditor::init(%this)
{
// add objclasses which we do not want to collide with
%this.ignoreObjClass(Sky);
// editing modes
%this.numEditModes = 3;
%this.editMode[0] = "move";
%this.editMode[1] = "rotate";
%this.editMode[2] = "scale";
// context menu
new GuiControl(WEContextPopupDlg, EditorGuiGroup)
{
profile = "GuiModelessDialogProfile";
horizSizing = "width";
vertSizing = "height";
position = "0 0";
extent = "640 480";
minExtent = "8 8";
visible = "1";
setFirstResponder = "0";
modal = "1";
new GuiPopUpMenuCtrl(WEContextPopup)
{
profile = "GuiScrollProfile";
position = "0 0";
extent = "0 0";
minExtent = "0 0";
maxPopupHeight = "200";
command = "canvas.popDialog(WEContextPopupDlg);";
};
};
WEContextPopup.setVisible(false);
// Make sure we have an active selection set.
if( !%this.getActiveSelection() )
%this.setActiveSelection( new WorldEditorSelection( EWorldEditorSelection ) );
}
//------------------------------------------------------------------------------
function WorldEditor::onDblClick(%this, %obj)
{
// Commented out because making someone double click to do this is stupid
// and has the possibility of moving hte object
//Inspector.inspect(%obj);
//InspectorNameEdit.setValue(%obj.getName());
}
function WorldEditor::onClick( %this, %obj )
{
Inspector.inspect( %obj );
}
function WorldEditor::onEndDrag( %this, %obj )
{
Inspector.inspect( %obj );
Inspector.apply();
}
//------------------------------------------------------------------------------
function WorldEditor::export(%this)
{
getSaveFilename("~/editor/*.mac|mac file", %this @ ".doExport", "selection.mac");
}
function WorldEditor::doExport(%this, %file)
{
missionGroup.save("~/editor/" @ %file, true);
}
function WorldEditor::import(%this)
{
getLoadFilename("~/editor/*.mac|mac file", %this @ ".doImport");
}
function WorldEditor::doImport(%this, %file)
{
exec("~/editor/" @ %file);
}
function WorldEditor::onGuiUpdate(%this, %text)
{
}
function WorldEditor::getSelectionLockCount(%this)
{
%ret = 0;
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
if(%obj.locked)
%ret++;
}
return %ret;
}
function WorldEditor::getSelectionHiddenCount(%this)
{
%ret = 0;
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
if(%obj.hidden)
%ret++;
}
return %ret;
}
function WorldEditor::dropCameraToSelection(%this)
{
if(%this.getSelectionSize() == 0)
return;
%pos = %this.getSelectionCentroid();
%cam = LocalClientConnection.camera.getTransform();
// set the pnt
%cam = setWord(%cam, 0, getWord(%pos, 0));
%cam = setWord(%cam, 1, getWord(%pos, 1));
%cam = setWord(%cam, 2, getWord(%pos, 2));
LocalClientConnection.camera.setTransform(%cam);
}
/// Pastes the selection at the same place (used to move obj from a group to another)
function WorldEditor::moveSelectionInPlace(%this)
{
%saveDropType = %this.dropType;
%this.dropType = "atCentroid";
%this.copySelection();
%this.deleteSelection();
%this.pasteSelection();
%this.dropType = %saveDropType;
}
function WorldEditor::addSelectionToAddGroup(%this)
{
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
$InstantGroup.add(%obj);
}
}
// resets the scale and rotation on the selection set
function WorldEditor::resetTransforms(%this)
{
%this.addUndoState();
for(%i = 0; %i < %this.getSelectionSize(); %i++)
{
%obj = %this.getSelectedObject(%i);
%transform = %obj.getTransform();
%transform = setWord(%transform, 3, "0");
%transform = setWord(%transform, 4, "0");
%transform = setWord(%transform, 5, "1");
%transform = setWord(%transform, 6, "0");
//
%obj.setTransform(%transform);
%obj.setScale("1 1 1");
}
}
function WorldEditorToolbarDlg::init(%this)
{
WorldEditorInspectorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolInspectorGui" ) );
WorldEditorMissionAreaCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolMissionAreaGui" ) );
WorldEditorTreeCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolTreeViewGui" ) );
WorldEditorCreatorCheckBox.setValue( WorldEditorToolFrameSet.isMember( "EditorToolCreatorGui" ) );
}
function WorldEditor::onAddSelected(%this,%obj)
{
EditorTree.addSelection(%obj);
}
function WorldEditor::onWorldEditorUndo( %this )
{
Inspector.refresh();
}
function Inspector::onInspectorFieldModified( %this, %object, %fieldName, %arrayIndex, %oldValue, %newValue )
{
// The instant group will try to add our
// UndoAction if we don't disable it.
pushInstantGroup();
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%action = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %oldValue;
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
// If it's a datablock, initiate a retransmit. Don't do so
// immediately so as the actual field value will only be set
// by the inspector code after this method has returned.
if( %object.isMemberOfClass( "SimDataBlock" ) )
%object.schedule( 1, "reloadOnLocalClient" );
// Restore the instant group.
popInstantGroup();
%action.addToManager( Editor.getUndoManager() );
EWorldEditor.isDirty = true;
// Update the selection
if(EWorldEditor.getSelectionSize() > 0 && (%fieldName $= "position" || %fieldName $= "rotation" || %fieldName $= "scale"))
{
EWorldEditor.invalidateSelectionCentroid();
}
}
function Inspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc )
{
FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc );
}
// The following three methods are for fields that edit field value live and thus cannot record
// undo information during edits. For these fields, undo information is recorded in advance and
// then either queued or disarded when the field edit is finished.
function Inspector::onInspectorPreFieldModification( %this, %fieldName, %arrayIndex )
{
pushInstantGroup();
%undoManager = Editor.getUndoManager();
%numObjects = %this.getNumInspectObjects();
if( %numObjects > 1 )
%action = %undoManager.pushCompound( "Multiple Field Edit" );
for( %i = 0; %i < %numObjects; %i ++ )
{
%object = %this.getInspectObject( %i );
%nameOrClass = %object.getName();
if ( %nameOrClass $= "" )
%nameOrClass = %object.getClassname();
%undo = new InspectorFieldUndoAction()
{
actionName = %nameOrClass @ "." @ %fieldName @ " Change";
objectId = %object.getId();
fieldName = %fieldName;
fieldValue = %object.getFieldValue( %fieldName, %arrayIndex );
arrayIndex = %arrayIndex;
inspectorGui = %this;
};
if( %numObjects > 1 )
%undo.addToManager( %undoManager );
else
{
%action = %undo;
break;
}
}
%this.currentFieldEditAction = %action;
popInstantGroup();
}
function Inspector::onInspectorPostFieldModification( %this )
{
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) )
{
// Finish multiple field edit.
Editor.getUndoManager().popCompound();
}
else
{
// Queue single field undo.
%this.currentFieldEditAction.addToManager( Editor.getUndoManager() );
}
%this.currentFieldEditAction = "";
EWorldEditor.isDirty = true;
}
function Inspector::onInspectorDiscardFieldModification( %this )
{
%this.currentFieldEditAction.undo();
if( %this.currentFieldEditAction.isMemberOfClass( "CompoundUndoAction" ) )
{
// Multiple field editor. Pop and discard.
Editor.getUndoManager().popCompound( true );
}
else
{
// Single field edit. Just kill undo action.
%this.currentFieldEditAction.delete();
}
%this.currentFieldEditAction = "";
}
function Inspector::inspect( %this, %obj )
{
//echo( "inspecting: " @ %obj );
%name = "";
if ( isObject( %obj ) )
%name = %obj.getName();
else
FieldInfoControl.setText( "" );
//InspectorNameEdit.setValue( %name );
Parent::inspect( %this, %obj );
}
function Inspector::onBeginCompoundEdit( %this )
{
Editor.getUndoManager().pushCompound( "Multiple Field Edit" );
}
function Inspector::onEndCompoundEdit( %this )
{
Editor.getUndoManager().popCompound();
}
function Inspector::onCancelCompoundEdit( %this )
{
Editor.getUndoManager().popCompound( true );
}
function foCollaps (%this, %tab){
switch$ (%tab){
case "container0":
%tab.visible = "0";
buttxon1.position = getWord(buttxon0.position, 0)+32 SPC getWord(buttxon1.position, 1);
buttxon2.position = getWord(buttxon1.position, 0)+32 SPC getWord(buttxon2.position, 1);
case "container1":
%tab.visible = "0";
case "container2":
%tab.visible = "0";
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecontravar2.dlgatecontravar2
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecontravar2.dlgatecontravar2;
// <Area>variance</Area>
// <Title> Basic Error Contravariance on delegates</Title>
// <Description> basic errorcontravariance on delegates - Incorrect type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(42,37\).*CS0168</Expects>
//<Expects Status=warning>\(53,26\).*CS0168</Expects>
using System;
using System.Runtime.InteropServices;
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<Tiger>)((Tiger a) =>
{
}
);
try
{
Foo<Animal> f12 = f11;
result++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "C.Foo<Tiger>", "C.Foo<Animal>");
if (ret == false)
result++;
}
Foo<Tiger> f21 = (Tiger a) =>
{
}
;
try
{
dynamic f22 = (Foo<Animal>)f21;
result++;
}
catch (InvalidCastException e)
{
}
dynamic f31 = (Foo<Tiger>)((Tiger a) =>
{
}
);
try
{
dynamic f32 = (Foo<Animal>)f31;
result++;
}
catch (Exception e)
{
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgateconvar.dlgateconvar
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgateconvar.dlgateconvar;
// <Area>variance</Area>
// <Title> Basic Contravariance on delegates</Title>
// <Description> basic contravariance on delegates </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<Animal>)((Animal a) =>
{
}
);
Foo<Tiger> f12 = (Foo<Tiger>)f11;
f12(new Tiger());
Foo<Animal> f21 = (Animal a) =>
{
}
;
dynamic f22 = (Foo<Tiger>)f21;
f22(new Tiger());
dynamic f31 = (Foo<Animal>)((Animal a) =>
{
}
);
dynamic f32 = (Foo<Tiger>)f31;
f32(new Tiger());
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecov.dlgatecov
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecov.dlgatecov;
// <Area>variance</Area>
// <Title> Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<Tiger>)(() =>
{
return new Tiger();
}
);
Foo<Animal> f12 = f11;
Animal t1 = f12();
Foo<Tiger> f21 = () =>
{
return new Tiger();
}
;
dynamic f22 = (Foo<Animal>)f21;
Animal t2 = f22();
dynamic f31 = (Foo<Tiger>)(() =>
{
return new Tiger();
}
);
dynamic f32 = (Foo<Animal>)f31;
Animal t3 = f32();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecovar2.dlgatecovar2
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecovar2.dlgatecovar2;
// <Area>variance</Area>
// <Title> Error- Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type, incorrect types</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<Animal>)(() =>
{
return new Tiger();
}
);
try
{
result++;
Foo<Tiger> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "C.Foo<Animal>", "C.Foo<Tiger>");
if (!ret)
result++;
}
Foo<Animal> f21 = () =>
{
return new Tiger();
}
;
try
{
result++;
dynamic f22 = (Foo<Tiger>)f21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic f31 = (Foo<Animal>)(() =>
{
return new Tiger();
}
);
try
{
result++;
dynamic f32 = (Foo<Tiger>)f31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecontravar2.integeregererfacecontravar2
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecontravar2.integeregererfacecontravar2;
// <Area>variance</Area>
// <Title> Basic error contravariance on interfaces</Title>
// <Description> basic error contravariance on interfaces - wrong type assignments </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int count = 0;
int result = 0;
dynamic v11 = new Variance<Tiger>();
try
{
result++;
iVariance<Animal> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<Tiger>", "iVariance<Animal>");
if (ret)
{
result--;
}
}
Variance<Tiger> v21 = new Variance<Tiger>();
try
{
result++;
dynamic v22 = (iVariance<Animal>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
Variance<Tiger> v31 = new Variance<Tiger>();
try
{
result++;
dynamic v32 = (iVariance<Animal>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfaceconvar.integeregererfaceconvar
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfaceconvar.integeregererfaceconvar;
// <Area>variance</Area>
// <Title> Basic contravariance on interfaces</Title>
// <Description> basic contravariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v11 = new Variance<Animal>();
iVariance<Tiger> v12 = v11;
v12.Boo(new Tiger());
Variance<Animal> v21 = new Variance<Animal>();
dynamic v22 = (iVariance<Tiger>)v21;
v22.Boo(new Tiger());
Variance<Animal> v31 = new Variance<Animal>();
dynamic v32 = (iVariance<Tiger>)v31;
v32.Boo(new Tiger());
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar2.integeregererfacecovar2
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar2.integeregererfacecovar2;
// <Area>variance</Area>
// <Title> Basic error covariance on interfaces</Title>
// <Description> basic error coavariance on interfaces - type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<Animal>();
try
{
result++;
iVariance<Tiger> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<Animal>", "iVariance<Tiger>");
if (ret)
{
result--;
}
}
Variance<Animal> v21 = new Variance<Animal>();
try
{
result++;
dynamic v22 = (iVariance<Tiger>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<Animal>();
try
{
result++;
dynamic v32 = (iVariance<Tiger>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar.integeregererfacecovar
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar.integeregererfacecovar;
// <Area>variance</Area>
// <Title> Basic covariance on interfaces</Title>
// <Description> basic coavariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class Animal
{
}
public class Tiger : Animal
{
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Variance<Tiger> v11 = new Variance<Tiger>();
iVariance<Animal> v12 = v11;
var x1 = v12.Boo();
dynamic v21 = new Variance<Tiger>();
iVariance<Animal> v22 = v21;
var x2 = v22.Boo();
dynamic v31 = new Variance<Tiger>();
dynamic v32 = (iVariance<Animal>)v31;
var x3 = v32.Boo();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecontravar4.dlgatecontravar4
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecontravar4.dlgatecontravar4;
// <Area>variance</Area>
// <Title> Basic Error Contravariance on delegates</Title>
// <Description> basic errorcontravariance on delegates - Incorrect type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
//<Expects Status=warning>\(40,37\).*CS0168</Expects>
//<Expects Status=warning>\(51,37\).*CS0168</Expects>
using System;
using System.Runtime.InteropServices;
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<string>)((string a) =>
{
}
);
try
{
Foo<dynamic> f12 = f11;
result++;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "C.Foo<string>", "C.Foo<object>");
if (!ret)
result++;
}
Foo<string> f21 = (string a) =>
{
}
;
try
{
dynamic f22 = (Foo<dynamic>)f21;
result++;
}
catch (InvalidCastException e)
{
}
dynamic f31 = (Foo<string>)((string a) =>
{
}
);
try
{
dynamic f32 = (Foo<dynamic>)f31;
result++;
}
catch (InvalidCastException e)
{
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgateconvar3.dlgateconvar3
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgateconvar3.dlgateconvar3;
// <Area>variance</Area>
// <Title> Basic Contravariance on delegates</Title>
// <Description> basic contravariance on delegates </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class C
{
public delegate void Foo<in T>(T t);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<dynamic>)((dynamic a) =>
{
}
);
Foo<string> f12 = (Foo<string>)f11;
f12(string.Empty);
Foo<dynamic> f21 = (dynamic a) =>
{
}
;
dynamic f22 = (Foo<string>)f21;
f22(null);
dynamic f31 = (Foo<dynamic>)((dynamic a) =>
{
}
);
dynamic f32 = (Foo<string>)f31;
f32("ABC");
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecov3.dlgatecov3
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecov3.dlgatecov3;
// <Area>variance</Area>
// <Title> Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic f11 = (Foo<string>)(() =>
{
return null;
}
);
Foo<dynamic> f12 = f11;
dynamic t1 = f12();
Foo<string> f21 = () =>
{
return string.Empty;
}
;
dynamic f22 = (Foo<dynamic>)f21;
dynamic t2 = f22();
dynamic f31 = (Foo<string>)(() =>
{
return "ABC";
}
);
dynamic f32 = (Foo<dynamic>)f31;
dynamic t3 = f32();
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecovar4.dlgatecovar4
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.dlgatecovar4.dlgatecovar4;
// <Area>variance</Area>
// <Title> Error- Basic covariance on delegate types </Title>
// <Description> Having a covariant delegate and assigning it to a bigger type, incorrect types</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public class C
{
public delegate T Foo<out T>();
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
bool ret = true;
dynamic f11 = (Foo<dynamic>)(() =>
{
return 10;
}
);
try
{
result++;
Foo<C> f12 = f11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
result--;
ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "C.Foo<object>", "C.Foo<C>");
if (!ret)
result++;
}
Foo<dynamic> f21 = () =>
{
return 10;
}
;
try
{
result++;
dynamic f22 = (Foo<C>)f21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic f31 = (Foo<dynamic>)(() =>
{
return 10;
}
);
try
{
result++;
dynamic f32 = (Foo<C>)f31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecontravar4.integeregererfacecontravar4
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecontravar4.integeregererfacecontravar4;
// <Area>variance</Area>
// <Title> Basic error contravariance on interfaces</Title>
// <Description> basic error contravariance on interfaces - wrong type assignments </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<string>();
try
{
result++;
iVariance<dynamic> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<string>", "iVariance<object>");
if (ret)
{
result--;
}
}
Variance<string> v21 = new Variance<string>();
try
{
result++;
dynamic v22 = (iVariance<dynamic>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
Variance<string> v31 = new Variance<string>();
try
{
result++;
dynamic v32 = (iVariance<dynamic>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfaceconvar3.integeregererfaceconvar3
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfaceconvar3.integeregererfaceconvar3;
// <Area>variance</Area>
// <Title> Basic contravariance on interfaces</Title>
// <Description> basic contravariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success> </Expects>
// <Code>
public interface iVariance<in T>
{
void Boo(T t);
}
public class Variance<T> : iVariance<T>
{
public void Boo(T t)
{
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic v11 = new Variance<dynamic>();
iVariance<string> v12 = v11;
v12.Boo(string.Empty);
Variance<dynamic> v21 = new Variance<dynamic>();
dynamic v22 = (iVariance<string>)v21;
v22.Boo(null);
Variance<dynamic> v31 = new Variance<dynamic>();
dynamic v32 = (iVariance<string>)v31;
v32.Boo("ABC");
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar4.integeregererfacecovar4
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar4.integeregererfacecovar4;
// <Area>variance</Area>
// <Title> Basic error covariance on interfaces</Title>
// <Description> basic error coavariance on interfaces - type mismatch</Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
int result = 0;
dynamic v11 = new Variance<object>();
try
{
result++;
iVariance<C> v12 = v11;
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex)
{
bool ret = ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, ex.Message, "Variance<object>", "iVariance<C>");
if (ret)
{
result--;
}
}
Variance<object> v21 = new Variance<object>();
try
{
result++;
dynamic v22 = (iVariance<C>)v21;
}
catch (System.InvalidCastException)
{
result--;
}
dynamic v31 = new Variance<object>();
try
{
result++;
dynamic v32 = (iVariance<C>)v31;
}
catch (System.InvalidCastException)
{
result--;
}
return result;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar3.integeregererfacecovar3
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.Variance.basic.integeregererfacecovar3.integeregererfacecovar3;
// <Area>variance</Area>
// <Title> Basic covariance on interfaces</Title>
// <Description> basic coavariance on interfaces </Description>
// <RelatedBugs></RelatedBugs>
// <Expects status=success></Expects>
// <Code>
public interface iVariance<out T>
{
T Boo();
}
public class Variance<T> : iVariance<T> where T : new()
{
public T Boo()
{
return new T();
}
}
public class C
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Variance<C> v11 = new Variance<C>();
iVariance<dynamic> v12 = v11;
var x1 = v12.Boo();
dynamic v21 = new Variance<C>();
iVariance<dynamic> v22 = v21;
var x2 = v22.Boo();
dynamic v31 = new Variance<C>();
dynamic v32 = (iVariance<dynamic>)v31;
var x3 = v32.Boo();
return 0;
}
}
//</Code>
}
| |
using System;
using System.Diagnostics;
using SharpFlame.Collections;
using SharpFlame.Core.Extensions;
using SharpFlame.FileIO;
using SharpFlame.Core;
using SharpFlame.Core.Collections;
using SharpFlame.Core.Domain;
using SharpFlame.Core.Parsers.Ini;
using SharpFlame.Domain;
using SharpFlame.Maths;
using SharpFlame.Util;
namespace SharpFlame.Mapping.Objects
{
public class Unit : IEquatable<Unit>
{
public double Health = 1.0D;
public UInt32 ID;
public ConnectedListItem<Unit, Map> MapLink;
public ConnectedListItem<Unit, Map> MapSelectedUnitLink;
public WorldPos Pos;
public bool PreferPartsOutput = false;
public int Rotation;
public int SavePriority;
public ConnectedList<UnitSectorConnection, Unit> Sectors;
public UnitTypeBase TypeBase;
public clsUnitGroup UnitGroup;
private string label;
public Unit()
{
MapLink = new ConnectedListItem<Unit, Map>(this);
MapSelectedUnitLink = new ConnectedListItem<Unit, Map>(this);
Sectors = new ConnectedList<UnitSectorConnection, Unit>(this);
}
public Unit(Unit unitToCopy, Map targetMap)
{
MapLink = new ConnectedListItem<Unit, Map>(this);
MapSelectedUnitLink = new ConnectedListItem<Unit, Map>(this);
Sectors = new ConnectedList<UnitSectorConnection, Unit>(this);
var IsDesign = default(bool);
if ( unitToCopy.TypeBase.Type == UnitType.PlayerDroid )
{
IsDesign = !((DroidDesign)unitToCopy.TypeBase).IsTemplate;
}
else
{
IsDesign = false;
}
if ( IsDesign )
{
var DroidDesign = new DroidDesign();
TypeBase = DroidDesign;
DroidDesign.CopyDesign((DroidDesign)unitToCopy.TypeBase);
DroidDesign.UpdateAttachments();
}
else
{
TypeBase = unitToCopy.TypeBase;
}
Pos = unitToCopy.Pos;
Rotation = unitToCopy.Rotation;
var otherUnitGroup = default(clsUnitGroup);
otherUnitGroup = unitToCopy.UnitGroup;
if ( otherUnitGroup.WZ_StartPos < 0 )
{
UnitGroup = targetMap.ScavengerUnitGroup;
}
else
{
UnitGroup = targetMap.UnitGroups[otherUnitGroup.WZ_StartPos];
}
SavePriority = unitToCopy.SavePriority;
Health = unitToCopy.Health;
PreferPartsOutput = unitToCopy.PreferPartsOutput;
}
public string Label
{
get { return label; }
}
public bool Equals(Unit other)
{
if ( other == null )
return false;
return (ID.Equals(other.ID));
}
public string GetINIPosition()
{
return Pos.Horizontal.X.ToStringInvariant() + ", " + Pos.Horizontal.Y.ToStringInvariant() + ", 0";
}
public string GetINIRotation()
{
var rotation16 = 0;
rotation16 = (Rotation * Constants.IniRotationMax / 360.0D).ToInt();
if ( rotation16 >= Constants.IniRotationMax )
{
rotation16 -= Constants.IniRotationMax;
}
else if ( rotation16 < 0 )
{
Debugger.Break();
rotation16 += Constants.IniRotationMax;
}
return string.Format("{0}, 0, 0", rotation16);
}
public string GetINIHealthPercent()
{
return string.Format("{0}%", MathUtil.ClampDbl(Health * 100.0D, 1.0D, 100.0D).ToInt());
}
public string GetPosText()
{
return Pos.Horizontal.X.ToStringInvariant() + ", " + Pos.Horizontal.Y.ToStringInvariant();
}
public SimpleResult SetLabel(string Text)
{
var Result = new SimpleResult();
if ( TypeBase.Type == UnitType.PlayerStructure )
{
var structureTypeBase = (StructureTypeBase)TypeBase;
var StructureTypeType = structureTypeBase.StructureType;
if ( StructureTypeType == StructureType.FactoryModule
| StructureTypeType == StructureType.PowerModule
| StructureTypeType == StructureType.ResearchModule )
{
Result.Problem = "Error: Trying to assign label to structure module.";
return Result;
}
}
if ( !MapLink.IsConnected )
{
Debugger.Break();
Result.Problem = "Error: Unit not on a map.";
return Result;
}
if ( Text == null )
{
label = null;
Result.Success = true;
Result.Problem = "";
return Result;
}
Result = MapLink.Owner.ScriptLabelIsValid(Text);
if ( Result.Success )
{
label = Text;
}
return Result;
}
public void WriteWZLabel(IniWriter File, int PlayerCount)
{
if ( label != null )
{
var TypeNum = 0;
switch ( TypeBase.Type )
{
case UnitType.PlayerDroid:
TypeNum = 0;
break;
case UnitType.PlayerStructure:
TypeNum = 1;
break;
case UnitType.Feature:
TypeNum = 2;
break;
default:
return;
}
File.AddSection("object_" + MapLink.Position.ToStringInvariant());
File.AddProperty("id", ID.ToStringInvariant());
if ( PlayerCount >= 0 ) //not an FMap
{
File.AddProperty("type", TypeNum.ToStringInvariant());
File.AddProperty("player", UnitGroup.GetPlayerNum(PlayerCount).ToStringInvariant());
}
File.AddProperty("label", label);
}
}
public UInt32 GetBJOMultiplayerPlayerNum(int PlayerCount)
{
var PlayerNum = 0;
if ( UnitGroup == MapLink.Owner.ScavengerUnitGroup || UnitGroup.WZ_StartPos < 0 )
{
PlayerNum = Math.Max(PlayerCount, 7);
}
else
{
PlayerNum = UnitGroup.WZ_StartPos;
}
return (uint)PlayerNum;
}
public UInt32 GetBJOCampaignPlayerNum()
{
var PlayerNum = 0;
if ( UnitGroup == MapLink.Owner.ScavengerUnitGroup || UnitGroup.WZ_StartPos < 0 )
{
PlayerNum = 7;
}
else
{
PlayerNum = UnitGroup.WZ_StartPos;
}
return (uint)PlayerNum;
}
public void MapSelect()
{
if ( MapSelectedUnitLink.IsConnected )
{
Debugger.Break();
return;
}
MapSelectedUnitLink.Connect(MapLink.Owner.SelectedUnits);
}
public void MapDeselect()
{
if ( !MapSelectedUnitLink.IsConnected )
{
Debugger.Break();
return;
}
MapSelectedUnitLink.Disconnect();
}
public void DisconnectFromMap()
{
if ( MapLink.IsConnected )
{
MapLink.Disconnect();
}
if ( MapSelectedUnitLink.IsConnected )
{
MapSelectedUnitLink.Disconnect();
}
Sectors.Clear();
}
public void Deallocate()
{
MapLink.Deallocate();
MapSelectedUnitLink.Deallocate();
Sectors.Deallocate();
}
public override bool Equals(object obj)
{
if ( obj == null )
return false;
var objAsUnit = obj as Unit;
if ( objAsUnit == null )
return false;
return Equals(objAsUnit);
}
public override int GetHashCode()
{
return (int)ID;
}
}
}
| |
using System;
using System.IO;
using System.Windows.Forms;
using Dullware.Plotter;
public class ContinInterface100
{
static object lockThis = new object();
string errormessage;
public string ErrorMessage
{
get { return errormessage; }
}
public string RunContin(ContinInput ci, ContinOutput co)
{
//WriteContinInputToFile(ci);
lock (lockThis) //Er mag maar een contin tegelijk lopen, waarschijnlijk omdat ze allemaal dezelfde stdin en stdout gebruiken
{
try
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = Application.StartupPath + @"\Continpk.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
WriteContinInput(proc.StandardInput, ci);
ReadContinOutput(proc.StandardOutput, co);
proc.WaitForExit();
proc.Close();
proc.Dispose();
}
catch (Exception e)
{
return e.Message;
}
}
return null;
}
void WriteContinInputToFile(ContinInput ci)
{
StreamWriter SW = new StreamWriter("contin.inp", false, System.Text.Encoding.ASCII);
WriteContinInput(SW, ci);
SW.Close();
}
public bool WriteContinInput(StreamWriter SW, ContinInput ci)
{
int lowerindex = ci.Correlations.LowerBound;//Set in AngleTabPage.AddDataFile();
int upperindex = ci.Correlations.UpperBound;//idem
int pksdelta = 6;
//SW.WriteLine("{0,-23}: Theta={1,6:f2} Temp={2,6:f2} Visc={3,6:f4} n={4,8:f6} {5,5:f1}", "StandardInput", ang, temp - 273.15, visc, indx, wave);
SW.WriteLine("AfterALV input file");
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "last", 0, 1);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "gmnmx", 1, 1.0 / ci.Correlations.X[upperindex - pksdelta - 1] / 3.0);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "gmnmx", 2, 2.0 / ci.Correlations.X[lowerindex - 1]);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "iwt", 0, 5);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "nerfit", 0, 0);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "nintt", 0, -1);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "nlinf", 0, 0);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "mpkmom", 0, 5);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "ng", 0, ci.GridSize);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:#.000000E+00}", "iquad", 0, 3);
SW.WriteLine(" {0,-78}", "iformt");
SW.WriteLine(" {0,-78}", "(5e14.6)");
SW.WriteLine(" {0,-78}", "iformy");
SW.WriteLine(" {0,-78}", "(5e14.6)");
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "dousnq", 0, 1);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "nonneg", 0, 1);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "iuser", 10, 2);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "ruser", 16, 0);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "ruser", 11, 10);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "ruser", 10, -1);
SW.WriteLine(" {0,-6}{1,5:D}{2,15:f6}", "iunit", 9, 9);
SW.WriteLine(" {0,-6}", "end");
SW.WriteLine(" {0,-6}{1,5:D}", "ny", upperindex - lowerindex + 1);
int i = lowerindex;
while (i <= upperindex)
{
for (int j = 0; j < 5 && i <= upperindex; j++) SW.Write("{0,14:#.000000E+00}", ci.Correlations.X[i++]);
SW.WriteLine();
}
i = lowerindex;
while (i <= upperindex)
{
for (int j = 0; j < 5 && i <= upperindex; j++) SW.Write("{0,14:#.000000E+00}", ci.Correlations.Y[i++]);
SW.WriteLine();
}
return true;
}
private bool ReadContinOutput(StreamReader SR, ContinOutput co)
{
string s = null;
try
{
////Zoek eerst naar ng. Dit is het aantal rooster punten (grid points).
//while ((s = SR.ReadLine()) != null && !s.StartsWith(" ng ")) ;
//ngrid = int.Parse(s.Substring(9));
////Zoek dat naar ny. Dit is het aantal data punten (input).
//while ((s = SR.ReadLine()) != null && !s.StartsWith(" ny ")) ;
//ndata = int.Parse(s.Substring(9));
//Zoek dan naar de tweede 1CONTIN
for (int i = 0; i < 2; i++) while ((s = SR.ReadLine()) != null && !s.StartsWith("1CONTIN")) ;
//Dan naar 0PLOT
while ((s = SR.ReadLine()) != null && !s.StartsWith("0PLOT OF DATA")) ;
//Dan naar ordinate abscissa
while ((s = SR.ReadLine()) != null && !s.StartsWith(" ordinate abscissa")) ;
//Nu zijn we bij de fit data
for (int i = 0; i < co.Correlations.Length; i++)
{
s = SR.ReadLine();
//de X-waarden s.Substring(12, 10)) zijn onnauwkeuriger dan de waarden in de DAT file.
// in de file staat g1, maak hier g1^2 van.
co.Correlations.Y[i] = Math.Pow(double.Parse(s.Substring(1, 11)), 2);
}
//Zoek vervolgens naar de derde 1CONTIN
while ((s = SR.ReadLine()) != null && !s.StartsWith("1CONTIN")) ;
//Dan naar ordinate error abscissa
while ((s = SR.ReadLine()) != null && !s.StartsWith(" ordinate error abscissa")) ;
//Nu zijn we bij de inverse-Laplace-getransformeerde
for (int i = 0; i < co.Transform.Length; i++)
{
s = SR.ReadLine();
co.Transform.X[i] = double.Parse(s.Substring(21, 10));
co.Transform.Y[i] = double.Parse(s.Substring(1, 11));
}
co.Peaks.Clear();
while ((s = SR.ReadLine()) != null)
{
if (s.StartsWith("0peak"))
{
ContinPeak p = new ContinPeak();
co.Peaks.Add(p);
if ((s = SR.ReadLine()) == null) break; // -1ste moment
if ((s = SR.ReadLine()) == null) break; // 0de moment
p.Area = double.Parse(s.Substring(49, 7)) * Math.Pow(10, double.Parse(s.Substring(64, 4)));
if ((s = SR.ReadLine()) == null) break; // 1ste moment
p.Position = double.Parse(s.Substring(95, 11));
}
else if (s.StartsWith(" moments of entire solution"))
{
double area;
if ((s = SR.ReadLine()) == null) break; // -1ste moment
area = double.Parse(s.Substring(49, 7)) * Math.Pow(10, double.Parse(s.Substring(64, 4)));
for (int i = 0; i < co.Transform.Length; i++)
co.Transform.Y[i] /= area;
}
}
}
catch (Exception e)
{
errormessage = "Fatal error in contin output.\n\nCheck your boundaries.\n\n" + e.Message;
return false;
}
//Multiply the transform by gamma
Hocuspocus(co);
return true;
}
void Hocuspocus(ContinOutput co)
{
double x1, x2, dx, xx;
double y1, y2, dy, yh;
for (int i = 1; i < co.Transform.Length; i++)
{
x2 = co.Transform.X[i];
x1 = co.Transform.X[i - 1];
y2 = co.Transform.Y[i];
y1 = co.Transform.Y[i - 1];
dx = x2 - x1;
dy = y2 - y1;
xx = x2 / x1;
yh = (y2 + y1) / 2;
co.Transform.X[i - 1] = (x2 + x1) / 2;
co.Transform.Y[i - 1] = yh * dx / Math.Log10(xx);
}
// laatste punt wordt niet meer gebruikt
co.Transform.UpperBound--;
}
}
| |
/*++
File: FixedSOMSemanticBox.cs
Copyright (C) 2005 Microsoft Corporation. All rights reserved.
Description:
This class is the abstract base class for all the objects in SOM. It consists of a bounding rectangle, and
implements IComparable interface to figure out content ordering on the page
History:
05/17/2005: agurcan - Created
--*/
namespace System.Windows.Documents
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Media;
using System.Windows.Markup;
internal abstract class FixedSOMSemanticBox : IComparable
{
//--------------------------------------------------------------------
//
// Constructors
//
//---------------------------------------------------------------------
#region Constructors
public FixedSOMSemanticBox()
{
_boundingRect = Rect.Empty;
}
public FixedSOMSemanticBox(Rect boundingRect)
{
_boundingRect = boundingRect;
}
#endregion Constructors
//--------------------------------------------------------------------
//
// Public Properties
//
//---------------------------------------------------------------------
#region Public Properties
public Rect BoundingRect
{
get
{
return _boundingRect;
}
set
{
_boundingRect = value;
}
}
#endregion Public Properties
//--------------------------------------------------------------------
//
// Public Methods
//
//---------------------------------------------------------------------
#region Public Methods
#if DEBUG
//For visualization purposes
public abstract void Render(DrawingContext dc, string label, DrawDebugVisual debugVisuals) ;
public void RenderLabel(DrawingContext dc, string label)
{
FormattedText ft = new FormattedText(label,
System.Windows.Markup.TypeConverterHelper.InvariantEnglishUS,
FlowDirection.LeftToRight,
new Typeface("Arial"),
10,
Brushes.White);
Point labelLocation = new Point(_boundingRect.Left-25, (_boundingRect.Bottom + _boundingRect.Top)/2 - 10);
Geometry geom = ft.BuildHighlightGeometry(labelLocation);
Pen backgroundPen = new Pen(Brushes.Black,1);
dc.DrawGeometry(Brushes.Black, backgroundPen, geom);
dc.DrawText(ft, labelLocation);
}
#endif
public virtual void SetRTFProperties(FixedElement element)
{
}
public int CompareTo(object o)
{
Debug.Assert(o != null);
if (!(o is FixedSOMSemanticBox))
{
throw new ArgumentException(SR.Get(SRID.UnexpectedParameterType, o.GetType(), typeof(FixedSOMSemanticBox)), "o");
}
SpatialComparison compareHor = _CompareHorizontal(o as FixedSOMSemanticBox, false);
SpatialComparison compareVer = _CompareVertical(o as FixedSOMSemanticBox);
Debug.Assert(compareHor != SpatialComparison.None && compareVer != SpatialComparison.None);
int result;
if (compareHor == SpatialComparison.Equal && compareVer == SpatialComparison.Equal)
{
result = 0;
}
else if (compareHor == SpatialComparison.Equal)
{
if (compareVer == SpatialComparison.Before || compareVer == SpatialComparison.OverlapBefore)
{
result = -1;
}
else
{
result = 1;
}
}
else if (compareVer == SpatialComparison.Equal)
{
if (compareHor == SpatialComparison.Before || compareHor == SpatialComparison.OverlapBefore)
{
result = -1;
}
else
{
result = 1;
}
}
else if (compareHor == SpatialComparison.Before)
{
result = -1;
}
else if (compareHor == SpatialComparison.After)
{
result = 1;
}
else
{
//Objects overlap
if (compareVer == SpatialComparison.Before)
{
result = -1;
}
else if (compareVer == SpatialComparison.After)
{
result = 1;
}
//These objects intersect.
else if (compareHor == SpatialComparison.OverlapBefore)
{
result = -1;
}
else
{
result = 1;
}
}
return result;
}
#endregion Abstract Methods
//--------------------------------------------------------------------
//
// IComparable
//
//---------------------------------------------------------------------
#region IComparable Methods
int IComparable.CompareTo(object o)
{
return this.CompareTo(o);
}
#endregion IComparable Methods
//--------------------------------------------------------------------
//
// Protected Methods
//
//---------------------------------------------------------------------
#region Private Methods
//Method that compares horizontally according to specific reading order
protected SpatialComparison _CompareHorizontal(FixedSOMSemanticBox otherBox, bool RTL)
{
SpatialComparison result = SpatialComparison.None;
Rect thisRect = this.BoundingRect;
Rect otherRect = otherBox.BoundingRect;
double thisRectRefX = RTL ? thisRect.Right : thisRect.Left;
double otherRectRefX = RTL ? otherRect.Right : otherRect.Left;
if (thisRectRefX == otherRectRefX)
{
result = SpatialComparison.Equal;
}
//Easiest way: calculate as if it's LTR and invert the result if RTL
else if (thisRect.Right < otherRect.Left)
{
//Clearly before the other object
result = SpatialComparison.Before;
}
else if (otherRect.Right < thisRect.Left)
{
//Clearly after the other object
result = SpatialComparison.After;
}
else
{
double overlap = Math.Abs(thisRectRefX - otherRectRefX);
double longerWidth = thisRect.Width > otherRect.Width ? thisRect.Width : otherRect.Width;
if (overlap/longerWidth < 0.1)
{
//If less than 10% overlap then assume these are equal in horizontal comparison
result = SpatialComparison.Equal;
}
//Objects overlap
else if (thisRect.Left < otherRect.Left)
{
result = SpatialComparison.OverlapBefore;
}
else
{
result = SpatialComparison.OverlapAfter;
}
}
if (RTL && result != SpatialComparison.Equal)
{
result = _InvertSpatialComparison(result);
}
return result;
}
//Method that compares horizontally according to specific reading order
//In the future we should take into account the document language and plug it into this algorithm
protected SpatialComparison _CompareVertical(FixedSOMSemanticBox otherBox)
{
SpatialComparison result = SpatialComparison.None;
Rect thisRect = this.BoundingRect;
Rect otherRect = otherBox.BoundingRect;
if (thisRect.Top == otherRect.Top)
{
result = SpatialComparison.Equal;
}
else if (thisRect.Bottom <= otherRect.Top)
{
//Clearly before the other object
result = SpatialComparison.Before;
}
else if (otherRect.Bottom <= thisRect.Top)
{
//Clearly after the other object
result = SpatialComparison.After;
}
else
{
//Objects overlap
if (thisRect.Top < otherRect.Top)
{
result = SpatialComparison.OverlapBefore;
}
else
{
result = SpatialComparison.OverlapAfter;
}
}
return result;
}
protected int _SpatialToAbsoluteComparison(SpatialComparison comparison)
{
int result=0;
switch (comparison)
{
case SpatialComparison.Before:
case SpatialComparison.OverlapBefore:
result = -1;
break;
case SpatialComparison.After:
case SpatialComparison.OverlapAfter:
result = 1;
break;
case SpatialComparison.Equal:
result = 0;
break;
default:
Debug.Assert(false);
break;
}
return result;
}
protected SpatialComparison _InvertSpatialComparison(SpatialComparison comparison)
{
SpatialComparison result = comparison;
switch (comparison)
{
case SpatialComparison.Before:
result = SpatialComparison.After;
break;
case SpatialComparison.After:
result = SpatialComparison.Before;
break;
case SpatialComparison.OverlapBefore:
result = SpatialComparison.OverlapAfter;
break;
case SpatialComparison.OverlapAfter:
result = SpatialComparison.OverlapBefore;
break;
default:
break;
}
return result;
}
#endregion Protected Methods
#region enums
protected enum SpatialComparison
{
None =0,
Before,
OverlapBefore,
Equal,
OverlapAfter,
After
};
#endregion enums
//--------------------------------------------------------------------
//
// Protected Fields
//
//---------------------------------------------------------------------
#region Protected Fields
protected Rect _boundingRect;
#endregion Protected Fields
}
}
| |
//
// PodcastActions.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Widgets;
using Migo.Syndication;
using Banshee.Base;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.ServiceStack;
using Banshee.Widgets;
using Banshee.Gui.Dialogs;
using Banshee.Gui.Widgets;
using Banshee.Gui;
using Banshee.Podcasting;
using Banshee.Podcasting.Data;
namespace Banshee.Podcasting.Gui
{
public class PodcastActions : BansheeActionGroup
{
private uint actions_id;
private DatabaseSource last_source;
private PodcastSource podcast_source;
public PodcastActions (PodcastSource source) : base (ServiceManager.Get<InterfaceActionService> (), "Podcast")
{
this.podcast_source = source;
AddImportant (
new ActionEntry (
"PodcastUpdateAllAction", Stock.Refresh,
Catalog.GetString ("Refresh"), null,//"<control><shift>U",
Catalog.GetString ("Check all podcasts for new episodes"),
OnPodcastUpdateAll
),
new ActionEntry (
"PodcastAddAction", Stock.Add,
Catalog.GetString ("Add Podcast..."),"<control><shift>F",
Catalog.GetString ("Subscribe to a new podcast"),
OnPodcastAdd
)
);
Add (
new ActionEntry("PodcastFeedPopupAction", null,
String.Empty, null, null, OnFeedPopup),
new ActionEntry (
"PodcastDeleteAction", Stock.Delete,
Catalog.GetString ("Unsubscribe and Delete"),
null, String.Empty,
OnPodcastDelete
),
new ActionEntry (
"PodcastUpdateFeedAction", Stock.Refresh,
Catalog.GetString ("Check for New Episodes"),
null, String.Empty,
OnPodcastUpdate
),
new ActionEntry (
"PodcastDownloadAllAction", Stock.Save,
Catalog.GetString ("Download All Episodes"),
null, String.Empty,
OnPodcastDownloadAllEpisodes
),
new ActionEntry (
"PodcastHomepageAction", Stock.JumpTo,
Catalog.GetString ("Visit Podcast Homepage"),
null, String.Empty,
OnPodcastHomepage
),
new ActionEntry (
"PodcastPropertiesAction", Stock.Properties,
Catalog.GetString ("Properties"),
null, String.Empty,
OnPodcastProperties
),
new ActionEntry (
"PodcastItemMarkNewAction", null,
Catalog.GetString ("Mark as New"),
null, String.Empty,
OnPodcastItemMarkNew
),
new ActionEntry (
"PodcastItemMarkOldAction", null,
Catalog.GetString ("Mark as Old"), "y", String.Empty,
OnPodcastItemMarkOld
),
new ActionEntry (
"PodcastItemDownloadAction", Stock.Save,
/* Translators: this is a verb used as a button name, not a noun*/
Catalog.GetString ("Download Podcast(s)"),
"<control><shift>D", String.Empty,
OnPodcastItemDownload
),
new ActionEntry (
"PodcastItemCancelAction", Stock.Cancel,
Catalog.GetString ("Cancel Download"),
"<control><shift>C", String.Empty,
OnPodcastItemCancel
),
new ActionEntry (
"PodcastItemDeleteFileAction", Stock.Remove,
Catalog.GetString ("Remove Downloaded File(s)"),
null, String.Empty,
OnPodcastItemDeleteFile
),
new ActionEntry (
"PodcastItemLinkAction", Stock.JumpTo,
Catalog.GetString ("Visit Website"),
null, String.Empty,
OnPodcastItemLink
),
new ActionEntry (
"PodcastItemPropertiesAction", Stock.Properties,
Catalog.GetString ("Properties"),
null, String.Empty,
OnPodcastItemProperties
)
);
this["PodcastAddAction"].ShortLabel = Catalog.GetString ("Add Podcast");
actions_id = Actions.UIManager.AddUiFromResource ("GlobalUI.xml");
Actions.AddActionGroup (this);
ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
OnSelectionChanged (null, null);
}
public override void Dispose ()
{
ServiceManager.SourceManager.ActiveSourceChanged -= HandleActiveSourceChanged;
Actions.UIManager.RemoveUi (actions_id);
Actions.RemoveActionGroup (this);
base.Dispose ();
}
#region State Event Handlers
private void HandleActiveSourceChanged (SourceEventArgs args)
{
if (last_source != null) {
foreach (IFilterListModel filter in last_source.AvailableFilters) {
filter.Selection.Changed -= OnSelectionChanged;
}
last_source.TrackModel.Selection.Changed -= OnSelectionChanged;
last_source = null;
}
last_source = args.Source as DatabaseSource;
if (IsPodcastSource) {
if (last_source != null) {
foreach (IFilterListModel filter in last_source.AvailableFilters) {
filter.Selection.Changed += OnSelectionChanged;
}
last_source.TrackModel.Selection.Changed += OnSelectionChanged;
}
} else {
last_source = null;
}
OnSelectionChanged (null, null);
}
private void OnSelectionChanged (object o, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
UpdateFeedActions ();
UpdateItemActions ();
});
}
#endregion
#region Utility Methods
private DatabaseSource ActiveDbSource {
get { return last_source; }
}
private bool IsPodcastSource {
get {
return ActiveDbSource != null && (ActiveDbSource is PodcastSource || ActiveDbSource.Parent is PodcastSource);
}
}
public PodcastFeedModel ActiveFeedModel {
get {
if (ActiveDbSource == null) {
return null;
} else if (ActiveDbSource is PodcastSource) {
return (ActiveDbSource as PodcastSource).FeedModel;
} else {
foreach (IFilterListModel filter in ActiveDbSource.AvailableFilters) {
if (filter is PodcastFeedModel) {
return filter as PodcastFeedModel;
}
}
return null;
}
}
}
private void UpdateItemActions ()
{
if (IsPodcastSource) {
bool has_single_selection = ActiveDbSource.TrackModel.Selection.Count == 1;
UpdateActions (true, has_single_selection,
"PodcastItemLinkAction"
);
}
}
private void UpdateFeedActions ()
{
if (IsPodcastSource) {
bool has_single_selection = ActiveFeedModel.Selection.Count == 1;
bool all_selected = ActiveFeedModel.Selection.AllSelected;
UpdateActions (true, has_single_selection && !all_selected,
"PodcastHomepageAction",
"PodcastPropertiesAction"
);
UpdateActions (true, ActiveFeedModel.Selection.Count > 0 && !all_selected,
"PodcastDeleteAction",
"PodcastUpdateFeedAction",
"PodcastDownloadAllAction"
);
}
}
private void SubscribeToPodcast (Uri uri, FeedAutoDownload syncPreference)
{
FeedsManager.Instance.FeedManager.CreateFeed (uri.ToString (), syncPreference);
}
private IEnumerable<TrackInfo> GetSelectedItems ()
{
return new List<TrackInfo> (ActiveDbSource.TrackModel.SelectedItems);
}
#endregion
#region Action Handlers
private void OnFeedPopup (object o, EventArgs args)
{
if (ActiveFeedModel.Selection.AllSelected) {
ShowContextMenu ("/PodcastAllFeedsContextMenu");
} else {
ShowContextMenu ("/PodcastFeedPopup");
}
}
private void RunSubscribeDialog ()
{
Uri feedUri = null;
FeedAutoDownload syncPreference;
string url = null;
PodcastSubscribeDialog subscribeDialog = new PodcastSubscribeDialog ();
ResponseType response = (ResponseType) subscribeDialog.Run ();
syncPreference = subscribeDialog.SyncPreference;
if (response == ResponseType.Ok) {
url = subscribeDialog.Url.Trim ().Trim ('/');
}
subscribeDialog.Destroy ();
if (String.IsNullOrEmpty (url)) {
return;
}
if (!TryParseUrl (url, out feedUri)) {
HigMessageDialog.RunHigMessageDialog (
null,
DialogFlags.Modal,
MessageType.Warning,
ButtonsType.Ok,
Catalog.GetString ("Invalid URL"),
Catalog.GetString ("Podcast URL is invalid.")
);
} else {
SubscribeToPodcast (feedUri, syncPreference);
}
}
/*private void RunConfirmDeleteDialog (bool feed,
int selCount,
out bool delete,
out bool deleteFiles)
{
delete = false;
deleteFiles = false;
string header = null;
int plural = (feed | (selCount > 1)) ? 2 : 1;
if (feed) {
header = Catalog.GetPluralString ("Delete Podcast?","Delete Podcasts?", selCount);
} else {
header = Catalog.GetPluralString ("Delete episode?", "Delete episodes?", selCount);
}
HigMessageDialog md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ("GtkElementsService").PrimaryWindow,
DialogFlags.DestroyWithParent,
MessageType.Question,
ButtonsType.None, header,
Catalog.GetPluralString (
"Would you like to delete the associated file?",
"Would you like to delete the associated files?", plural
)
);
md.AddButton (Stock.Cancel, ResponseType.Cancel, true);
md.AddButton (
Catalog.GetPluralString (
"Keep File", "Keep Files", plural
), ResponseType.No, false
);
md.AddButton (Stock.Delete, ResponseType.Yes, false);
try {
switch ((ResponseType)md.Run ()) {
case ResponseType.Yes:
deleteFiles = true;
goto case ResponseType.No;
case ResponseType.No:
delete = true;
break;
}
} finally {
md.Destroy ();
}
}*/
private bool TryParseUrl (string url, out Uri uri)
{
uri = null;
bool ret = false;
try {
uri = new Uri (url);
if (uri.Scheme == Uri.UriSchemeHttp ||
uri.Scheme == Uri.UriSchemeHttps) {
ret = true;
}
} catch {}
return ret;
}
/*private void OnFeedSelectionChangedHandler (object sender, EventArgs e)
{
lock (sync) {
if (!disposed || disposing) {
if (source.FeedModel.SelectedItems.Count == 0) {
source.FeedModel.Selection.Select (0);
}
if (source.FeedModel.Selection.Contains (0)) {
itemModel.FilterOnFeed (Feed.All);
} else {
itemModel.FilterOnFeeds (source.FeedModel.CopySelectedItems ());
}
itemModel.Selection.Clear ();
}
}
}
private void OnPodcastItemRowActivatedHandler (object sender,
RowActivatedArgs<PodcastItem> e)
{
lock (sync) {
if (!disposed || disposing) {
if (e.RowValue.Enclosure != null) {
e.RowValue.New = false;
ServiceManager.PlayerEngine.OpenPlay (e.RowValue);
}
}
}
}*/
private void OnPodcastAdd (object sender, EventArgs e)
{
RunSubscribeDialog ();
}
private void OnPodcastUpdate (object sender, EventArgs e)
{
foreach (Feed feed in ActiveFeedModel.SelectedItems) {
feed.Update ();
}
}
private void OnPodcastUpdateAll (object sender, EventArgs e)
{
foreach (Feed feed in Feed.Provider.FetchAll ()) {
if (feed.IsSubscribed) {
feed.Update ();
}
}
}
private void OnPodcastDelete (object sender, EventArgs e)
{
foreach (Feed feed in ActiveFeedModel.SelectedItems) {
if (feed != null) {
feed.Delete (true);
}
}
}
private void OnPodcastDownloadAllEpisodes (object sender, EventArgs e)
{
foreach (Feed feed in ActiveFeedModel.SelectedItems) {
if (feed != null) {
foreach (FeedItem item in feed.Items) {
item.Enclosure.AsyncDownload ();
}
}
}
}
private void OnPodcastItemDeleteFile (object sender, EventArgs e)
{
foreach (PodcastTrackInfo pi in PodcastTrackInfo.From (GetSelectedItems ())) {
if (pi.Enclosure.LocalPath != null)
pi.Enclosure.DeleteFile ();
}
}
private void OnPodcastHomepage (object sender, EventArgs e)
{
Feed feed = ActiveFeedModel.FocusedItem;
if (feed != null && !String.IsNullOrEmpty (feed.Link)) {
Banshee.Web.Browser.Open (feed.Link);
}
}
private void OnPodcastProperties (object sender, EventArgs e)
{
Feed feed = ActiveFeedModel.FocusedItem;
if (feed != null) {
new PodcastFeedPropertiesDialog (podcast_source, feed).Run ();
}
}
private void OnPodcastItemProperties (object sender, EventArgs e)
{
/*ReadOnlyCollection<PodcastItem> items = itemModel.CopySelectedItems ();
if (items != null && items.Count == 1) {
new PodcastPropertiesDialog (items[0]).Run ();
} */
}
private void OnPodcastItemMarkNew (object sender, EventArgs e)
{
MarkPodcastItemSelection (false);
}
private void OnPodcastItemMarkOld (object sender, EventArgs e)
{
MarkPodcastItemSelection (true);
}
private void MarkPodcastItemSelection (bool markRead)
{
TrackInfo new_selection_track = ActiveDbSource.TrackModel [ActiveDbSource.TrackModel.Selection.LastIndex + 1];
PodcastService.IgnoreItemChanges = true;
bool any = false;
foreach (PodcastTrackInfo track in PodcastTrackInfo.From (GetSelectedItems ())) {
if (track.Item.IsRead != markRead) {
track.Item.IsRead = markRead;
track.Item.Save ();
if (track.Item.IsRead ^ track.Track.PlayCount > 0) {
track.Track.PlayCount = track.Item.IsRead ? 1 : 0;
track.Track.Save (false);
}
any = true;
}
}
PodcastService.IgnoreItemChanges = false;
if (any) {
ActiveDbSource.Reload ();
// If we just removed all of the selected items from our view, we should select the
// item after the last removed item
if (ActiveDbSource.TrackModel.Selection.Count == 0 && new_selection_track != null) {
int new_i = ActiveDbSource.TrackModel.IndexOf (new_selection_track);
if (new_i != -1) {
ActiveDbSource.TrackModel.Selection.Clear (false);
ActiveDbSource.TrackModel.Selection.FocusedIndex = new_i;
ActiveDbSource.TrackModel.Selection.Select (new_i);
}
}
}
}
private void OnPodcastItemCancel (object sender, EventArgs e)
{
/*
if (!disposed || disposing) {
ReadOnlyCollection<PodcastItem> items = itemModel.CopySelectedItems ();
if (items != null) {
foreach (PodcastItem pi in items) {
pi.Enclosure.CancelAsyncDownload ();
}
}
}*/
}
private void OnPodcastItemDownload (object sender, EventArgs e)
{
foreach (PodcastTrackInfo pi in PodcastTrackInfo.From (GetSelectedItems ())) {
pi.Enclosure.AsyncDownload ();
}
}
private void OnPodcastItemLink (object sender, EventArgs e)
{
PodcastTrackInfo track = PodcastTrackInfo.From (ActiveDbSource.TrackModel.FocusedItem);
if (track != null && !String.IsNullOrEmpty (track.Item.Link)) {
Banshee.Web.Browser.Open (track.Item.Link);
}
}
#endregion
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.Spatial
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Spatial;
/// <summary>
/// Builder for Geography types
/// </summary>
internal class GeographyBuilderImplementation : GeographyPipeline, IGeographyProvider
{
/// <summary>
/// The tree builder
/// </summary>
private readonly SpatialTreeBuilder<Geography> builder;
/// <summary>
/// Constructor
/// </summary>
/// <param name="creator">The implementation that created this instance.</param>
public GeographyBuilderImplementation(SpatialImplementation creator)
{
this.builder = new GeographyTreeBuilder(creator);
}
/// <summary>
/// Fires when the provider constructs a geography object.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Not following the event-handler pattern")]
public event Action<Geography> ProduceGeography
{
add { this.builder.ProduceInstance += value; }
remove { this.builder.ProduceInstance -= value; }
}
/// <summary>
/// Constructed Geography
/// </summary>
public Geography ConstructedGeography
{
get { return this.builder.ConstructedInstance; }
}
/// <summary>
/// Draw a point in the specified coordinate
/// </summary>
/// <param name="position">Next position</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "ForwardingSegment does the validation")]
public override void LineTo(GeographyPosition position)
{
Debug.Assert(position != null, "ForwardingSegment should have validated nullness");
this.builder.LineTo(position.Latitude, position.Longitude, position.Z, position.M);
}
/// <summary>
/// Begin drawing a figure
/// </summary>
/// <param name="position">Next position</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "ForwardingSegment does the validation")]
public override void BeginFigure(GeographyPosition position)
{
Debug.Assert(position != null, "ForwardingSegment should have validated nullness");
this.builder.BeginFigure(position.Latitude, position.Longitude, position.Z, position.M);
}
/// <summary>
/// Begin drawing a spatial object
/// </summary>
/// <param name="type">The spatial type of the object</param>
public override void BeginGeography(SpatialType type)
{
this.builder.BeginGeo(type);
}
/// <summary>
/// Ends the current figure
/// </summary>
public override void EndFigure()
{
this.builder.EndFigure();
}
/// <summary>
/// Ends the current spatial object
/// </summary>
public override void EndGeography()
{
this.builder.EndGeo();
}
/// <summary>
/// Setup the pipeline for reuse
/// </summary>
public override void Reset()
{
this.builder.Reset();
}
/// <summary>
/// Set the coordinate system
/// </summary>
/// <param name="coordinateSystem">The CoordinateSystem</param>
public override void SetCoordinateSystem(CoordinateSystem coordinateSystem)
{
Util.CheckArgumentNull(coordinateSystem, "coordinateSystem");
this.builder.SetCoordinateSystem(coordinateSystem.EpsgId);
}
/// <summary>
/// Geography Tree Builder
/// </summary>
private class GeographyTreeBuilder : SpatialTreeBuilder<Geography>
{
/// <summary>
/// The implementation that created this instance.
/// </summary>
private readonly SpatialImplementation creator;
/// <summary>
/// CoordinateSystem for the building geography
/// </summary>
private CoordinateSystem currentCoordinateSystem;
/// <summary>
/// Initializes a new instance of the <see cref="GeographyTreeBuilder"/> class.
/// </summary>
/// <param name="creator">The implementation that created this instance.</param>
public GeographyTreeBuilder(SpatialImplementation creator)
{
Util.CheckArgumentNull(creator, "creator");
this.creator = creator;
}
/// <summary>
/// Set the coordinate system based on the given ID
/// </summary>
/// <param name="epsgId">The coordinate system ID to set. Null indicates the default should be used</param>
internal override void SetCoordinateSystem(int? epsgId)
{
this.currentCoordinateSystem = CoordinateSystem.Geography(epsgId);
}
/// <summary>
/// Create a new instance of Point
/// </summary>
/// <param name="isEmpty">Whether the point is empty</param>
/// <param name="x">X</param>
/// <param name="y">Y</param>
/// <param name="z">Z</param>
/// <param name="m">M</param>
/// <returns>A new instance of point</returns>
protected override Geography CreatePoint(bool isEmpty, double x, double y, double? z, double? m)
{
return isEmpty ? new GeographyPointImplementation(this.currentCoordinateSystem, this.creator) : new GeographyPointImplementation(this.currentCoordinateSystem, this.creator, x, y, z, m);
}
/// <summary>
/// Create a new instance of T
/// </summary>
/// <param name="type">The spatial type to create</param>
/// <param name="spatialData">The arguments</param>
/// <returns>A new instance of T</returns>
protected override Geography CreateShapeInstance(SpatialType type, IEnumerable<Geography> spatialData)
{
switch (type)
{
case SpatialType.LineString:
return new GeographyLineStringImplementation(this.currentCoordinateSystem, this.creator, spatialData.Cast<GeographyPoint>().ToArray());
case SpatialType.Polygon:
return new GeographyPolygonImplementation(this.currentCoordinateSystem, this.creator, spatialData.Cast<GeographyLineString>().ToArray());
case SpatialType.MultiPoint:
return new GeographyMultiPointImplementation(this.currentCoordinateSystem, this.creator, spatialData.Cast<GeographyPoint>().ToArray());
case SpatialType.MultiLineString:
return new GeographyMultiLineStringImplementation(this.currentCoordinateSystem, this.creator, spatialData.Cast<GeographyLineString>().ToArray());
case SpatialType.MultiPolygon:
return new GeographyMultiPolygonImplementation(this.currentCoordinateSystem, this.creator, spatialData.Cast<GeographyPolygon>().ToArray());
case SpatialType.Collection:
return new GeographyCollectionImplementation(this.currentCoordinateSystem, this.creator, spatialData.ToArray());
case SpatialType.FullGlobe:
return new GeographyFullGlobeImplementation(this.currentCoordinateSystem, this.creator);
default:
Debug.Assert(false, "Point type should not call CreateShapeInstance, use CreatePoint instead.");
return null;
}
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// LogResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Serverless.V1.Service.Environment
{
public class LogResource : Resource
{
public sealed class LevelEnum : StringEnum
{
private LevelEnum(string value) : base(value) {}
public LevelEnum() {}
public static implicit operator LevelEnum(string value)
{
return new LevelEnum(value);
}
public static readonly LevelEnum Info = new LevelEnum("info");
public static readonly LevelEnum Warn = new LevelEnum("warn");
public static readonly LevelEnum Error = new LevelEnum("error");
}
private static Request BuildReadRequest(ReadLogOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Serverless,
"/v1/Services/" + options.PathServiceSid + "/Environments/" + options.PathEnvironmentSid + "/Logs",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all logs.
/// </summary>
/// <param name="options"> Read Log parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Log </returns>
public static ResourceSet<LogResource> Read(ReadLogOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<LogResource>.FromJson("logs", response.Content);
return new ResourceSet<LogResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all logs.
/// </summary>
/// <param name="options"> Read Log parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Log </returns>
public static async System.Threading.Tasks.Task<ResourceSet<LogResource>> ReadAsync(ReadLogOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<LogResource>.FromJson("logs", response.Content);
return new ResourceSet<LogResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all logs.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the Log resource from </param>
/// <param name="pathEnvironmentSid"> The SID of the environment with the Log resources to read </param>
/// <param name="functionSid"> The SID of the function whose invocation produced the Log resources to read </param>
/// <param name="startDate"> The date and time after which the Log resources must have been created. </param>
/// <param name="endDate"> The date and time before which the Log resource must have been created. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Log </returns>
public static ResourceSet<LogResource> Read(string pathServiceSid,
string pathEnvironmentSid,
string functionSid = null,
DateTime? startDate = null,
DateTime? endDate = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadLogOptions(pathServiceSid, pathEnvironmentSid){FunctionSid = functionSid, StartDate = startDate, EndDate = endDate, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all logs.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to read the Log resource from </param>
/// <param name="pathEnvironmentSid"> The SID of the environment with the Log resources to read </param>
/// <param name="functionSid"> The SID of the function whose invocation produced the Log resources to read </param>
/// <param name="startDate"> The date and time after which the Log resources must have been created. </param>
/// <param name="endDate"> The date and time before which the Log resource must have been created. </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Log </returns>
public static async System.Threading.Tasks.Task<ResourceSet<LogResource>> ReadAsync(string pathServiceSid,
string pathEnvironmentSid,
string functionSid = null,
DateTime? startDate = null,
DateTime? endDate = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadLogOptions(pathServiceSid, pathEnvironmentSid){FunctionSid = functionSid, StartDate = startDate, EndDate = endDate, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<LogResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<LogResource>.FromJson("logs", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<LogResource> NextPage(Page<LogResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Serverless)
);
var response = client.Request(request);
return Page<LogResource>.FromJson("logs", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<LogResource> PreviousPage(Page<LogResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Serverless)
);
var response = client.Request(request);
return Page<LogResource>.FromJson("logs", response.Content);
}
private static Request BuildFetchRequest(FetchLogOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Serverless,
"/v1/Services/" + options.PathServiceSid + "/Environments/" + options.PathEnvironmentSid + "/Logs/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a specific log.
/// </summary>
/// <param name="options"> Fetch Log parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Log </returns>
public static LogResource Fetch(FetchLogOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Retrieve a specific log.
/// </summary>
/// <param name="options"> Fetch Log parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Log </returns>
public static async System.Threading.Tasks.Task<LogResource> FetchAsync(FetchLogOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Retrieve a specific log.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the Log resource from </param>
/// <param name="pathEnvironmentSid"> The SID of the environment with the Log resource to fetch </param>
/// <param name="pathSid"> The SID that identifies the Log resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Log </returns>
public static LogResource Fetch(string pathServiceSid,
string pathEnvironmentSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchLogOptions(pathServiceSid, pathEnvironmentSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a specific log.
/// </summary>
/// <param name="pathServiceSid"> The SID of the Service to fetch the Log resource from </param>
/// <param name="pathEnvironmentSid"> The SID of the environment with the Log resource to fetch </param>
/// <param name="pathSid"> The SID that identifies the Log resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Log </returns>
public static async System.Threading.Tasks.Task<LogResource> FetchAsync(string pathServiceSid,
string pathEnvironmentSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchLogOptions(pathServiceSid, pathEnvironmentSid, pathSid);
return await FetchAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a LogResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> LogResource object represented by the provided JSON </returns>
public static LogResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<LogResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the Log resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the Log resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The SID of the Service that the Log resource is associated with
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// The SID of the environment in which the log occurred
/// </summary>
[JsonProperty("environment_sid")]
public string EnvironmentSid { get; private set; }
/// <summary>
/// The SID of the build that corresponds to the log
/// </summary>
[JsonProperty("build_sid")]
public string BuildSid { get; private set; }
/// <summary>
/// The SID of the deployment that corresponds to the log
/// </summary>
[JsonProperty("deployment_sid")]
public string DeploymentSid { get; private set; }
/// <summary>
/// The SID of the function whose invocation produced the log
/// </summary>
[JsonProperty("function_sid")]
public string FunctionSid { get; private set; }
/// <summary>
/// The SID of the request associated with the log
/// </summary>
[JsonProperty("request_sid")]
public string RequestSid { get; private set; }
/// <summary>
/// The log level
/// </summary>
[JsonProperty("level")]
[JsonConverter(typeof(StringEnumConverter))]
public LogResource.LevelEnum Level { get; private set; }
/// <summary>
/// The log message
/// </summary>
[JsonProperty("message")]
public string Message { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the Log resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The absolute URL of the Log resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private LogResource()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using Internal.Cryptography;
using Microsoft.Win32.SafeHandles;
namespace System.Security.Cryptography
{
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
internal static partial class ECDsaImplementation
{
#endif
public sealed partial class ECDsaOpenSsl : ECDsa
{
private ECOpenSsl _key;
/// <summary>
/// Create an ECDsaOpenSsl algorithm with a named curve.
/// </summary>
/// <param name="curve">The <see cref="ECCurve"/> representing the curve.</param>
/// <exception cref="ArgumentNullException">if <paramref name="curve" /> is null.</exception>
public ECDsaOpenSsl(ECCurve curve)
{
_key = new ECOpenSsl(curve);
ForceSetKeySize(_key.KeySize);
}
/// <summary>
/// Create an ECDsaOpenSsl algorithm with a random 521 bit key pair.
/// </summary>
public ECDsaOpenSsl()
: this(521)
{
}
/// <summary>
/// Creates a new ECDsaOpenSsl object that will use a randomly generated key of the specified size.
/// </summary>
/// <param name="keySize">Size of the key to generate, in bits.</param>
public ECDsaOpenSsl(int keySize)
{
// Use the base setter to get the validation and field assignment without the
// side effect of dereferencing _key.
base.KeySize = keySize;
_key = new ECOpenSsl(this);
}
/// <summary>
/// Set the KeySize without validating against LegalKeySizes.
/// </summary>
/// <param name="newKeySize">The value to set the KeySize to.</param>
private void ForceSetKeySize(int newKeySize)
{
// In the event that a key was loaded via ImportParameters, curve name, or an IntPtr/SafeHandle
// it could be outside of the bounds that we currently represent as "legal key sizes".
// Since that is our view into the underlying component it can be detached from the
// component's understanding. If it said it has opened a key, and this is the size, trust it.
KeySizeValue = newKeySize;
}
public override KeySizes[] LegalKeySizes
{
get
{
// Return the three sizes that can be explicitly set (for backwards compatibility)
return new[] {
new KeySizes(minSize: 256, maxSize: 384, skipSize: 128),
new KeySizes(minSize: 521, maxSize: 521, skipSize: 0),
};
}
}
public override byte[] SignHash(byte[] hash)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
ThrowIfDisposed();
SafeEcKeyHandle key = _key.Value;
int signatureLength = Interop.Crypto.EcDsaSize(key);
byte[] signature = new byte[signatureLength];
if (!Interop.Crypto.EcDsaSign(hash, signature, ref signatureLength, key))
throw Interop.Crypto.CreateOpenSslCryptographicException();
byte[] converted = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(signature, 0, signatureLength, KeySize);
return converted;
}
public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, out int bytesWritten)
{
ThrowIfDisposed();
SafeEcKeyHandle key = _key.Value;
byte[] converted;
int signatureLength = Interop.Crypto.EcDsaSize(key);
byte[] signature = CryptoPool.Rent(signatureLength);
try
{
if (!Interop.Crypto.EcDsaSign(hash, new Span<byte>(signature, 0, signatureLength), ref signatureLength, key))
{
throw Interop.Crypto.CreateOpenSslCryptographicException();
}
converted = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(signature, 0, signatureLength, KeySize);
}
finally
{
CryptoPool.Return(signature, signatureLength);
}
if (converted.Length <= destination.Length)
{
new ReadOnlySpan<byte>(converted).CopyTo(destination);
bytesWritten = converted.Length;
return true;
}
else
{
bytesWritten = 0;
return false;
}
}
public override bool VerifyHash(byte[] hash, byte[] signature)
{
if (hash == null)
throw new ArgumentNullException(nameof(hash));
if (signature == null)
throw new ArgumentNullException(nameof(signature));
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature);
}
public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature)
{
ThrowIfDisposed();
// The signature format for .NET is r.Concat(s). Each of r and s are of length BitsToBytes(KeySize), even
// when they would have leading zeroes. If it's the correct size, then we need to encode it from
// r.Concat(s) to SEQUENCE(INTEGER(r), INTEGER(s)), because that's the format that OpenSSL expects.
int expectedBytes = 2 * AsymmetricAlgorithmHelpers.BitsToBytes(KeySize);
if (signature.Length != expectedBytes)
{
// The input isn't of the right length, so we can't sensibly re-encode it.
return false;
}
byte[] openSslFormat = AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature);
SafeEcKeyHandle key = _key.Value;
int verifyResult = Interop.Crypto.EcDsaVerify(hash, openSslFormat, key);
return verifyResult == 1;
}
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten);
protected override void Dispose(bool disposing)
{
if (disposing)
{
_key?.Dispose();
_key = null;
}
base.Dispose(disposing);
}
public override int KeySize
{
get
{
return base.KeySize;
}
set
{
if (KeySize == value)
return;
// Set the KeySize before FreeKey so that an invalid value doesn't throw away the key
base.KeySize = value;
ThrowIfDisposed();
_key.Dispose();
_key = new ECOpenSsl(this);
}
}
public override void GenerateKey(ECCurve curve)
{
ThrowIfDisposed();
_key.GenerateKey(curve);
// Use ForceSet instead of the property setter to ensure that LegalKeySizes doesn't interfere
// with the already loaded key.
ForceSetKeySize(_key.KeySize);
}
public override void ImportParameters(ECParameters parameters)
{
ThrowIfDisposed();
_key.ImportParameters(parameters);
ForceSetKeySize(_key.KeySize);
}
public override ECParameters ExportExplicitParameters(bool includePrivateParameters)
{
ThrowIfDisposed();
return ECOpenSsl.ExportExplicitParameters(_key.Value, includePrivateParameters);
}
public override ECParameters ExportParameters(bool includePrivateParameters)
{
ThrowIfDisposed();
return ECOpenSsl.ExportParameters(_key.Value, includePrivateParameters);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
ThrowIfDisposed();
base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
private void ThrowIfDisposed()
{
if (_key == null)
{
throw new ObjectDisposedException(
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
nameof(ECDsa)
#else
nameof(ECDsaOpenSsl)
#endif
);
}
}
}
#if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS
}
#endif
}
| |
using FluentAssertions;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading.Tasks;
using Microsoft.Reactive.Testing;
using Toggl.Core.Models.Interfaces;
using Toggl.Core.Tests.Generators;
using Toggl.Core.Tests.TestExtensions;
using Toggl.Core.UI.Navigation;
using Toggl.Core.UI.ViewModels;
using Toggl.Core.UI.ViewModels.Calendar;
using Toggl.Shared;
using Toggl.Shared.Extensions;
using Xunit;
using Toggl.Core.UI.Helper;
using System.Globalization;
using Toggl.Core.Analytics;
using Toggl.Core.Tests.Mocks;
using Toggl.Core.UI.Parameters;
using static Toggl.Core.Helper.Constants;
namespace Toggl.Core.Tests.UI.ViewModels
{
public sealed class CalendarViewModelTests
{
public abstract class CalendarViewModelTest : BaseViewModelTests<CalendarViewModel>
{
protected override CalendarViewModel CreateViewModel()
=> new CalendarViewModel(
DataSource,
TimeService,
RxActionFactory,
UserPreferences,
AnalyticsService,
BackgroundService,
InteractorFactory,
SchedulerProvider,
OnboardingStorage,
PermissionsChecker,
SyncManager,
NavigationService
);
public static IEnumerable<object[]> BeginningOfWeekTestData
=> new[]
{
new object[] { BeginningOfWeek.Monday },
new object[] { BeginningOfWeek.Tuesday },
new object[] { BeginningOfWeek.Wednesday },
new object[] { BeginningOfWeek.Thursday },
new object[] { BeginningOfWeek.Friday },
new object[] { BeginningOfWeek.Saturday },
new object[] { BeginningOfWeek.Sunday },
};
protected IThreadSafeUser UserWith(BeginningOfWeek beginningOfWeek)
{
var user = Substitute.For<IThreadSafeUser>();
user.BeginningOfWeek.Returns(beginningOfWeek);
return user;
}
protected void SetupBeginningOfWeek(BeginningOfWeek beginningOfWeek)
{
var user = UserWith(beginningOfWeek);
DataSource.User.Current.Returns(Observable.Return(user));
}
}
public sealed class TheConstructor : CalendarViewModelTest
{
[Theory, LogIfTooSlow]
[ConstructorData]
public void ThrowsIfAnyOfTheArgumentsIsNull(
bool useDataSource,
bool useTimeService,
bool useUserPreferences,
bool useAnalyticsService,
bool useBackgroundService,
bool useInteractorFactory,
bool useSchedulerProvider,
bool useOnboardingStorage,
bool useNavigationService,
bool useRxActionFactory,
bool useSyncManager)
{
var dataSource = useDataSource ? DataSource : null;
var timeService = useTimeService ? TimeService : null;
var userPreferences = useUserPreferences ? UserPreferences : null;
var rxActionFactory = useRxActionFactory ? RxActionFactory : null;
var analyticsService = useAnalyticsService ? AnalyticsService : null;
var backgroundService = useBackgroundService ? BackgroundService : null;
var interactorFactory = useInteractorFactory ? InteractorFactory : null;
var schedulerProvider = useSchedulerProvider ? SchedulerProvider : null;
var onboardingStorage = useOnboardingStorage ? OnboardingStorage : null;
var navigationService = useNavigationService ? NavigationService : null;
var syncManager = useSyncManager ? SyncManager : null;
Action tryingToConstructWithEmptyParameters =
() => new CalendarViewModel(
dataSource,
timeService,
rxActionFactory,
userPreferences,
analyticsService,
backgroundService,
interactorFactory,
schedulerProvider,
onboardingStorage,
PermissionsChecker,
syncManager,
navigationService);
tryingToConstructWithEmptyParameters.Should().Throw<ArgumentNullException>();
}
}
public sealed class TheCurrentlyShownDateStringObservable : CalendarViewModelTest
{
private static readonly DateTimeOffset now = new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero).Date;
public TheCurrentlyShownDateStringObservable()
{
DateFormatCultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
TimeService.CurrentDateTime.Returns(now);
}
[Fact, LogIfTooSlow, DiscardCultureChanges]
public async Task StartsWithTheCurrentDate()
{
var preferences = Substitute.For<IThreadSafePreferences>();
preferences.DateFormat.Returns(DateFormat.ValidDateFormats[0]);
DataSource.Preferences.Current.Returns(Observable.Return(preferences));
var expectedResult = "Thursday, Jan 2";
var observer = TestScheduler.CreateObserver<string>();
var viewModel = CreateViewModel();
viewModel.CurrentlyShownDateString.Subscribe(observer);
TestScheduler.Start();
observer.Values().Should().BeEquivalentTo(new[] { expectedResult });
}
[Theory, LogIfTooSlow, DiscardCultureChanges]
[InlineData(-1, "Wednesday, Jan 1")]
[InlineData(-2, "Tuesday, Dec 31")]
[InlineData(-7, "Thursday, Dec 26")]
[InlineData(-14, "Thursday, Dec 19")]
public void EmitsNewDateWhenCurrentlyVisiblePageChanges(int pageIndex, string expectedDate)
{
var expectedResults = new[]
{
"Thursday, Jan 2",
expectedDate
};
var observer = TestScheduler.CreateObserver<string>();
var viewModel = CreateViewModel();
var date = viewModel.IndexToDate(pageIndex);
viewModel.CurrentlyShownDateString.Subscribe(observer);
viewModel.CurrentlyShownDate.Accept(date);
TestScheduler.Start();
observer.Values().Should().BeEquivalentTo(expectedResults);
}
[Theory, LogIfTooSlow, DiscardCultureChanges]
[InlineData(4, 5, 2020, "Monday, May 4")]
[InlineData(30, 9, 1995, "Saturday, Sep 30")]
public void EmitsNewDateWhenAnItemInWeekViewIsTapped(int day, int month, int year, string expectedDateString)
{
var preferences = Substitute.For<IThreadSafePreferences>();
preferences.DateFormat.Returns(DateFormat.ValidDateFormats[0]);
DataSource.Preferences.Current.Returns(Observable.Return(preferences));
var expectedResults = new[]
{
"Thursday, Jan 2",
expectedDateString
};
var observer = TestScheduler.CreateObserver<string>();
var viewModel = CreateViewModel();
viewModel.CurrentlyShownDateString.Subscribe(observer);
var date = new DateTime(year, month, day);
var tappedWeekViewDayViewModel = new CalendarWeeklyViewDayViewModel(date, false, true);
viewModel.SelectDayFromWeekView.Execute(tappedWeekViewDayViewModel);
TestScheduler.Start();
observer.Values().Should().BeEquivalentTo(expectedResults);
}
}
public sealed class TheCurrentlyShownDateProperty : CalendarViewModelTest
{
private static readonly DateTimeOffset now = new DateTimeOffset(2020, 1, 2, 3, 4, 5, TimeSpan.Zero).ToLocalTime().Date;
public TheCurrentlyShownDateProperty()
{
TimeService.CurrentDateTime.Returns(now);
}
[Theory, LogIfTooSlow]
[InlineData(4, 5, 2020)]
[InlineData(30, 9, 1995)]
public void EmitsNewDateWhenAnItemInWeekViewIsSelected(int day, int month, int year)
{
var selectedDate = new DateTime(year, month, day);
var selectedDayViewModel = new CalendarWeeklyViewDayViewModel(selectedDate, false, true);
var preferences = Substitute.For<IThreadSafePreferences>();
preferences.DateFormat.Returns(DateFormat.ValidDateFormats[0]);
DataSource.Preferences.Current.Returns(Observable.Return(preferences));
var expectedResults = new[]
{
now.LocalDateTime,
selectedDate
};
var observer = TestScheduler.CreateObserver<DateTime>();
var viewModel = CreateViewModel();
viewModel.CurrentlyShownDate.Subscribe(observer);
viewModel.SelectDayFromWeekView.Execute(selectedDayViewModel);
TestScheduler.Start();
observer.Values().Should().BeEquivalentTo(expectedResults);
}
[Fact, LogIfTooSlow]
public void StartsWithTheCurrentDate()
{
var preferences = Substitute.For<IThreadSafePreferences>();
preferences.DateFormat.Returns(DateFormat.ValidDateFormats[0]);
DataSource.Preferences.Current.Returns(Observable.Return(preferences));
var expectedResults = new[]
{
now.Date
};
var observer = TestScheduler.CreateObserver<DateTime>();
var viewModel = CreateViewModel();
viewModel.CurrentlyShownDate.Subscribe(observer);
TestScheduler.Start();
observer.Values().Should().BeEquivalentTo(expectedResults);
}
}
public sealed class TheWeekViewDaysProperty : CalendarViewModelTest
{
private DateTimeOffset now = new DateTimeOffset(2017, 4, 3, 1, 2, 3, TimeSpan.Zero).ToLocalTime();
public TheWeekViewDaysProperty()
{
TimeService.CurrentDateTime.Returns(now);
TimeService.MidnightObservable.Returns(Observable.Never<DateTimeOffset>());
}
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void StartsWithTheSelectedBeginningOfWeek(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
TestScheduler.Start();
observer.Values().Should().HaveCount(1);
assertCollectionStartsWithCorrectBeginningOfWeek(observer.Values().First(), beginningOfWeek);
}
[Theory, LogIfTooSlow]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
public void EmitsNewCollectionWhenBeginningOfWeekSettingChanges(int updateCount)
{
setupBeginningOfWeekUpdates();
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
TestScheduler.Start();
var observedValues = observer.Values().ToArray();
observedValues.Should().HaveCount(updateCount + 1);
for (int i = 0; i <= updateCount; i++)
{
var weekDays = observedValues[i];
var expectedBeginningOfWeek = (BeginningOfWeek)i;
weekDays.First().Should().Match<CalendarWeeklyViewDayViewModel>(
firstDay => firstDay.Date.DayOfWeek == expectedBeginningOfWeek.ToDayOfWeekEnum()
);
}
void setupBeginningOfWeekUpdates()
{
var observableMessages = new List<Recorded<Notification<IThreadSafeUser>>>();
observableMessages.Add(OnNext(0, UserWith(BeginningOfWeek.Sunday)));
for (int i = 1; i <= updateCount; i++)
{
var beginningOfWeek = (BeginningOfWeek)i;
var user = UserWith(beginningOfWeek);
observableMessages.Add(OnNext(i, user));
}
var observable = TestScheduler.CreateColdObservable(observableMessages.ToArray());
DataSource.User.Current.Returns(observable);
}
}
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void ContainsOneDayThatIsMarkedAsToday(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
TestScheduler.Start();
var today = observer.Values().First().Single(date => date.Date == now.Date);
today.IsToday.Should().BeTrue();
}
[Fact, LogIfTooSlow]
public void EmitsNewCollectionAfterMidnight()
{
var midnightSubject = new Subject<DateTimeOffset>();
SetupBeginningOfWeek(BeginningOfWeek.Monday);
TimeService.MidnightObservable.Returns(midnightSubject);
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
midnightSubject.OnNext(now.AddDays(1));
TestScheduler.Start();
observer.Values().Should().HaveCount(2);
}
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void TheCountOfItemsIsDivisibleBy7(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
TestScheduler.Start();
(observer.Values().Single().Count % 7).Should().Be(0);
}
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void AllDaysAfterTheLastViewableDayAreMarkedAsUnviewable(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
TestScheduler.Start();
var daysAfterLastViewableDate = observer.Values().Single().Where(day => day.Date > now.Date.BeginningOfWeek(beginningOfWeek).AddDays(CalendarMaxPastDays).Date);
if (daysAfterLastViewableDate.None()) return;
daysAfterLastViewableDate.Should().OnlyContain(day => !day.Enabled);
}
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void AllDaysMoreThan2WeeksAgoAreMarkedAsUnviewable(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var observer = TestScheduler.CreateObserver<IImmutableList<CalendarWeeklyViewDayViewModel>>();
var viewModel = CreateViewModel();
viewModel.WeekViewDays.Subscribe(observer);
TestScheduler.Start();
var weeksAgo = now.Date.AddDays(-CalendarMaxPastDays);
var daysBeforeTwoWeeks = observer.Values().Single().Where(day => day.Date < weeksAgo);
if (daysBeforeTwoWeeks.None()) return;
daysBeforeTwoWeeks.Should().OnlyContain(day => !day.Enabled);
}
private void assertCollectionStartsWithCorrectBeginningOfWeek(
IImmutableList<CalendarWeeklyViewDayViewModel> collection,
BeginningOfWeek beginningOfWeek)
{
collection.First().Should().Match<CalendarWeeklyViewDayViewModel>(
weekViewDay => weekViewDay.Date.DayOfWeek == beginningOfWeek.ToDayOfWeekEnum());
}
}
public sealed class WeekViewHeadersProperty : CalendarViewModelTest
{
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void ContainsAllDaysOfWeek(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var viewModel = CreateViewModel();
var observer = TestScheduler.CreateObserver<IImmutableList<DayOfWeek>>();
viewModel.WeekViewHeaders.Subscribe(observer);
TestScheduler.Start();
observer.Values().Single().Should().OnlyHaveUniqueItems().And.HaveCount(7);
}
[Theory, LogIfTooSlow]
[MemberData(nameof(BeginningOfWeekTestData))]
public void StartsWithTheBeginningOfWeekSelectedInSettings(BeginningOfWeek beginningOfWeek)
{
SetupBeginningOfWeek(beginningOfWeek);
var viewModel = CreateViewModel();
var observer = TestScheduler.CreateObserver<IImmutableList<DayOfWeek>>();
viewModel.WeekViewHeaders.Subscribe(observer);
TestScheduler.Start();
observer.Values().Single().First().Should().Be(beginningOfWeek.ToDayOfWeekEnum());
}
[Theory, LogIfTooSlow]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
public void EmitsNewCollectionWhenBeginningOfWeekSettingChanges(int updateCount)
{
setupBeginningOfWeekUpdates();
var observer = TestScheduler.CreateObserver<IImmutableList<DayOfWeek>>();
var viewModel = CreateViewModel();
viewModel.WeekViewHeaders.Subscribe(observer);
TestScheduler.Start();
var observedValues = observer.Values().ToArray();
observedValues.Should().HaveCount(updateCount + 1);
for (int i = 0; i <= updateCount; i++)
{
var dayHeaders = observedValues[i];
var expectedBeginningOfWeek = (BeginningOfWeek)i;
dayHeaders.First().Should().Match<DayOfWeek>(
firstHeader => firstHeader == expectedBeginningOfWeek.ToDayOfWeekEnum()
);
}
void setupBeginningOfWeekUpdates()
{
var observableMessages = new List<Recorded<Notification<IThreadSafeUser>>>();
observableMessages.Add(OnNext(0, UserWith(BeginningOfWeek.Sunday)));
for (int i = 1; i <= updateCount; i++)
{
var beginningOfWeek = (BeginningOfWeek)i;
var user = UserWith(beginningOfWeek);
observableMessages.Add(OnNext(i, user));
}
var observable = TestScheduler.CreateColdObservable(observableMessages.ToArray());
DataSource.User.Current.Returns(observable);
}
}
}
public sealed class TheSelectDayFromWeekViewAction : CalendarViewModelTest
{
private readonly DateTimeOffset now = new DateTimeOffset(2020, 4, 5, 9, 2, 1, TimeSpan.Zero);
public TheSelectDayFromWeekViewAction()
{
TimeService.CurrentDateTime.Returns(now);
TimeService.MidnightObservable.Returns(Observable.Never<DateTimeOffset>());
}
[Fact, LogIfTooSlow]
public void NewCurrentlySelectedDateIsEmittedAfterExecutingTheAction()
{
var observer = TestScheduler.CreateObserver<DateTime>();
ViewModel.CurrentlyShownDate.Subscribe(observer);
var dayToSelect = new CalendarWeeklyViewDayViewModel(now.AddDays(-3).Date, false, true);
ViewModel.SelectDayFromWeekView.Execute(dayToSelect);
TestScheduler.Start();
observer.Values().Last().Should().Be(dayToSelect.Date);
}
[Fact, LogIfTooSlow]
public void TracksCalendarWeeklyDatePickerSelectionChangedEvent()
{
var daysSinceToday = 3;
var dayToSelect = new CalendarWeeklyViewDayViewModel(now.AddDays(-daysSinceToday).Date, false, true);
ViewModel.SelectDayFromWeekView.Execute(dayToSelect);
TestScheduler.Start();
AnalyticsService.CalendarWeeklyDatePickerSelectionChanged.Received().Track(daysSinceToday, dayToSelect.Date.DayOfWeek.ToString());
}
}
public sealed class TheOpenSettingsAction : CalendarViewModelTest
{
[Fact, LogIfTooSlow]
public void NavigatesToTheSettingsViewModel()
{
ViewModel.OpenSettings.Execute();
NavigationService.Received().Navigate<SettingsViewModel>(View);
}
}
public sealed class TheStartTimeEntryAction : CalendarViewModelTest
{
private readonly ISubject<IThreadSafeTimeEntry> runningTimeEntry = new Subject<IThreadSafeTimeEntry>();
public TheStartTimeEntryAction()
{
DataSource.TimeEntries.CurrentlyRunningTimeEntry.Returns(runningTimeEntry);
TimeService.CurrentDateTime.Returns(DateTimeOffset.Now);
ViewModel.Initialize().GetAwaiter().GetResult();
runningTimeEntry.OnNext(null);
TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(50).Ticks);
}
[Theory, LogIfTooSlow]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task NavigatesToTheStartTimeEntryViewModel(bool isInManualMode, bool useDefaultMode)
{
runningTimeEntry.OnNext(null);
UserPreferences.IsManualModeEnabled.Returns(isInManualMode);
ViewModel.StartTimeEntry.Execute(useDefaultMode);
TestScheduler.Start();
await NavigationService.Received()
.Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(Arg.Any<StartTimeEntryParameters>(), ViewModel.View);
}
[Theory, LogIfTooSlow]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task PassesTheAppropriatePlaceholderToTheStartTimeEntryViewModel(bool isInManualMode, bool useDefaultMode)
{
UserPreferences.IsManualModeEnabled.Returns(isInManualMode);
ViewModel.StartTimeEntry.Execute(useDefaultMode);
TestScheduler.Start();
var expected = isInManualMode == useDefaultMode
? Resources.ManualTimeEntryPlaceholder
: Resources.StartTimeEntryPlaceholder;
await NavigationService.Received().Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(
Arg.Is<StartTimeEntryParameters>(parameter => parameter.PlaceholderText == expected),
ViewModel.View
);
}
[Theory, LogIfTooSlow]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task PassesTheAppropriateDurationToTheStartTimeEntryViewModel(bool isInManualMode, bool useDefaultMode)
{
UserPreferences.IsManualModeEnabled.Returns(isInManualMode);
ViewModel.StartTimeEntry.Execute(useDefaultMode);
TestScheduler.Start();
var expected = isInManualMode == useDefaultMode
? TimeSpan.FromMinutes(DefaultTimeEntryDurationForManualModeInMinutes)
: (TimeSpan?)null;
await NavigationService.Received().Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(
Arg.Is<StartTimeEntryParameters>(parameter => parameter.Duration == expected),
ViewModel.View
);
}
[Theory, LogIfTooSlow]
[InlineData(true, true)]
[InlineData(true, false)]
[InlineData(false, true)]
[InlineData(false, false)]
public async Task PassesTheAppropriateStartTimeToTheStartTimeEntryViewModel(bool isInManualMode, bool useDefaultMode)
{
var date = DateTimeOffset.Now;
TimeService.CurrentDateTime.Returns(date);
UserPreferences.IsManualModeEnabled.Returns(isInManualMode);
ViewModel.StartTimeEntry.Execute(useDefaultMode);
TestScheduler.Start();
var expected = isInManualMode == useDefaultMode
? date.Subtract(TimeSpan.FromMinutes(DefaultTimeEntryDurationForManualModeInMinutes))
: date;
await NavigationService.Received().Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(
Arg.Is<StartTimeEntryParameters>(parameter => parameter.StartTime == expected),
ViewModel.View
);
}
[Theory, LogIfTooSlow]
[InlineData(true)]
[InlineData(false)]
public void CannotBeExecutedWhenThereIsARunningTimeEntry(bool useDefaultMode)
{
var timeEntry = new MockTimeEntry();
runningTimeEntry.OnNext(timeEntry);
TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(50).Ticks);
var errors = TestScheduler.CreateObserver<Exception>();
ViewModel.StartTimeEntry.Errors.Subscribe(errors);
ViewModel.StartTimeEntry.Execute(useDefaultMode);
TestScheduler.Start();
errors.Messages.Count.Should().Be(1);
errors.LastEmittedValue().Should().BeEquivalentTo(new RxActionNotEnabledException());
}
}
public class TheStopTimeEntryAction : CalendarViewModelTest
{
private ISubject<IThreadSafeTimeEntry> runningTimeEntry;
public TheStopTimeEntryAction()
{
var timeEntry = Substitute.For<IThreadSafeTimeEntry>();
runningTimeEntry = new BehaviorSubject<IThreadSafeTimeEntry>(timeEntry);
DataSource.TimeEntries.CurrentlyRunningTimeEntry.Returns(runningTimeEntry);
ViewModel.Initialize().Wait();
TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(50).Ticks);
}
[Fact, LogIfTooSlow]
public async Task CallsTheStopMethodOnTheDataSource()
{
var date = DateTimeOffset.UtcNow;
TimeService.CurrentDateTime.Returns(date);
ViewModel.StopTimeEntry.Execute();
TestScheduler.Start();
await InteractorFactory.Received().StopTimeEntry(date, TimeEntryStopOrigin.Manual).Execute();
}
[Fact, LogIfTooSlow]
public async Task InitiatesPushSync()
{
ViewModel.StopTimeEntry.Execute();
TestScheduler.Start();
SyncManager.Received().PushSync();
}
[Fact, LogIfTooSlow]
public async Task DoesNotInitiatePushSyncWhenSavingFails()
{
InteractorFactory
.StopTimeEntry(Arg.Any<DateTimeOffset>(), Arg.Any<TimeEntryStopOrigin>())
.Execute()
.Returns(Task.FromException<IThreadSafeTimeEntry>(new Exception()));
var errors = TestScheduler.CreateObserver<Exception>();
ViewModel.StopTimeEntry.Errors.Subscribe(errors);
ViewModel.StopTimeEntry.Execute();
TestScheduler.Start();
errors.Messages.Count().Should().Be(1);
SyncManager.DidNotReceive().PushSync();
}
[Fact, LogIfTooSlow]
public async Task CannotBeExecutedWhenNoTimeEntryIsRunning()
{
runningTimeEntry.OnNext(null);
TestScheduler.AdvanceBy(TimeSpan.FromMilliseconds(50).Ticks);
var errors = TestScheduler.CreateObserver<Exception>();
ViewModel.StopTimeEntry.Errors.Subscribe(errors);
ViewModel.StopTimeEntry.Execute();
TestScheduler.Start();
errors.Messages.Count.Should().Be(1);
errors.LastEmittedValue().Should().BeEquivalentTo(new RxActionNotEnabledException());
await InteractorFactory.DidNotReceive().StopTimeEntry(Arg.Any<DateTimeOffset>(), Arg.Any<TimeEntryStopOrigin>()).Execute();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class UsingDebugInfoTests : ExpressionCompilerTestBase
{
#region Grouped import strings
[Fact]
public void SimplestCase()
{
var source = @"
using System;
class C
{
void M()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var importStrings = GetGroupedImportStrings(comp, "M");
Assert.Equal("USystem", importStrings.Single().Single());
}
[Fact]
public void NestedNamespaces()
{
var source = @"
using System;
namespace A
{
using System.IO;
using System.Text;
class C
{
void M()
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var importStrings = GetGroupedImportStrings(comp, "M");
Assert.Equal(2, importStrings.Length);
AssertEx.Equal(importStrings[0], new[] { "USystem.IO", "USystem.Text" });
AssertEx.Equal(importStrings[1], new[] { "USystem" });
}
[Fact]
public void Forward()
{
var source = @"
using System;
namespace A
{
using System.IO;
using System.Text;
class C
{
// One of these methods will forward to the other since they're adjacent.
void M1() { }
void M2() { }
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var importStrings1 = GetGroupedImportStrings(comp, "M1");
Assert.Equal(2, importStrings1.Length);
AssertEx.Equal(importStrings1[0], new[] { "USystem.IO", "USystem.Text" });
AssertEx.Equal(importStrings1[1], new[] { "USystem" });
var importStrings2 = GetGroupedImportStrings(comp, "M2");
Assert.Equal(2, importStrings2.Length);
AssertEx.Equal(importStrings2[0], importStrings1[0]);
AssertEx.Equal(importStrings2[1], importStrings1[1]);
}
[Fact]
public void ImportKinds()
{
var source = @"
extern alias A;
using S = System;
namespace B
{
using F = S.IO.File;
using System.Text;
class C
{
void M()
{
}
}
}
";
var aliasedRef = new CSharpCompilationReference(CreateCompilation("", assemblyName: "Lib"), aliases: ImmutableArray.Create("A"));
var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
ImmutableArray<string> externAliasStrings;
var importStrings = GetGroupedImportStrings(comp, "M", out externAliasStrings);
Assert.Equal(2, importStrings.Length);
AssertEx.Equal(importStrings[0], new[] { "USystem.Text", "AF TSystem.IO.File, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" });
AssertEx.Equal(importStrings[1], new[] { "XA", "AS USystem" });
Assert.Equal("ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", externAliasStrings.Single());
}
[WorkItem(1084059)]
[Fact]
public void ImportKinds_StaticType()
{
var libSource = @"
namespace N
{
public static class Static
{
}
}
";
var source = @"
extern alias A;
using static System.Math;
namespace B
{
using static A::N.Static;
class C
{
void M()
{
}
}
}
";
var aliasedRef = new CSharpCompilationReference(CreateCompilation(libSource, assemblyName: "Lib"), aliases: ImmutableArray.Create("A"));
var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
ImmutableArray<string> externAliasStrings;
var importStrings = GetGroupedImportStrings(comp, "M", out externAliasStrings);
Assert.Equal(2, importStrings.Length);
AssertEx.Equal(importStrings[0], new[] { "TN.Static, Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" });
AssertEx.Equal(importStrings[1], new[] { "XA", "TSystem.Math, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" });
Assert.Equal("ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", externAliasStrings.Single());
}
[Fact]
public void ForwardToModule()
{
var source = @"
extern alias A;
namespace B
{
using System;
class C
{
void M1()
{
}
}
}
namespace D
{
using System.Text; // Different using to prevent normal forwarding.
class E
{
void M2()
{
}
}
}
";
var aliasedRef = new CSharpCompilationReference(CreateCompilation("", assemblyName: "Lib"), aliases: ImmutableArray.Create("A"));
var comp = CreateCompilationWithMscorlib(source, new[] { aliasedRef });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
ImmutableArray<string> externAliasStrings1;
var importStrings1 = GetGroupedImportStrings(comp, "M1", out externAliasStrings1);
Assert.Equal(2, importStrings1.Length);
AssertEx.Equal("USystem", importStrings1[0].Single());
AssertEx.Equal("XA", importStrings1[1].Single());
Assert.Equal("ZA Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", externAliasStrings1.Single());
ImmutableArray<string> externAliasStrings2;
var importStrings2 = GetGroupedImportStrings(comp, "M2", out externAliasStrings2);
Assert.Equal(2, importStrings2.Length);
AssertEx.Equal("USystem.Text", importStrings2[0].Single());
AssertEx.Equal(importStrings1[1].Single(), importStrings2[1].Single());
Assert.Equal(externAliasStrings1.Single(), externAliasStrings2.Single());
}
private static ImmutableArray<ImmutableArray<string>> GetGroupedImportStrings(Compilation compilation, string methodName)
{
ImmutableArray<string> externAliasStrings;
ImmutableArray<ImmutableArray<string>> result = GetGroupedImportStrings(compilation, methodName, out externAliasStrings);
Assert.Equal(0, externAliasStrings.Length);
return result;
}
private static ImmutableArray<ImmutableArray<string>> GetGroupedImportStrings(Compilation compilation, string methodName, out ImmutableArray<string> externAliasStrings)
{
Assert.NotNull(compilation);
Assert.NotNull(methodName);
using (var exebits = new MemoryStream())
{
using (var pdbbits = new MemoryStream())
{
compilation.Emit(exebits, pdbbits);
exebits.Position = 0;
using (var module = new PEModule(new PEReader(exebits, PEStreamOptions.LeaveOpen), metadataOpt: IntPtr.Zero, metadataSizeOpt: 0))
{
var metadataReader = module.MetadataReader;
MethodDefinitionHandle methodHandle = metadataReader.MethodDefinitions.Single(mh => metadataReader.GetString(metadataReader.GetMethodDefinition(mh).Name) == methodName);
int methodToken = metadataReader.GetToken(methodHandle);
// Create a SymReader, rather than a raw COM object, because
// SymReader implements ISymUnmanagedReader3 and the COM object
// might not.
pdbbits.Position = 0;
using (var reader = new SymReader(pdbbits.ToArray()))
{
return reader.GetCSharpGroupedImportStrings(methodToken, methodVersion: 1, externAliasStrings: out externAliasStrings);
}
}
}
}
}
#endregion Grouped import strings
#region Invalid PDBs
[Fact]
public void BadPdb_ForwardChain()
{
const int methodVersion = 1;
const int methodToken1 = 0x600057a; // Forwards to 2
const int methodToken2 = 0x600055d; // Forwards to 3
const int methodToken3 = 0x6000540; // Has a using
const string importString = "USystem";
ISymUnmanagedReader reader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build() },
{ methodToken2, new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build() },
{ methodToken3, new MethodDebugInfoBytes.Builder(new [] { new [] { importString } }).Build() },
}.ToImmutableDictionary());
ImmutableArray<string> externAliasStrings;
var importStrings = reader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings);
Assert.True(importStrings.IsDefault);
Assert.True(externAliasStrings.IsDefault);
importStrings = reader.GetCSharpGroupedImportStrings(methodToken2, methodVersion, out externAliasStrings);
Assert.Equal(importString, importStrings.Single().Single());
Assert.Equal(0, externAliasStrings.Length);
importStrings = reader.GetCSharpGroupedImportStrings(methodToken2, methodVersion, out externAliasStrings);
Assert.Equal(importString, importStrings.Single().Single());
Assert.Equal(0, externAliasStrings.Length);
}
[Fact]
public void BadPdb_Cycle()
{
const int methodVersion = 1;
const int methodToken1 = 0x600057a; // Forwards to itself
ISymUnmanagedReader reader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken1, new MethodDebugInfoBytes.Builder().AddForward(methodToken1).Build() },
}.ToImmutableDictionary());
ImmutableArray<string> externAliasStrings;
var importStrings = reader.GetCSharpGroupedImportStrings(methodToken1, methodVersion, out externAliasStrings);
Assert.True(importStrings.IsDefault);
Assert.True(externAliasStrings.IsDefault);
}
[WorkItem(999086)]
[Fact]
public void BadPdb_InvalidAliasSyntax()
{
var source = @"
public class C
{
public static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports(
exeBytes,
"Main",
"USystem", // Valid.
"UACultureInfo TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped.
"ASI USystem.IO"); // Valid.
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw.
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString());
Assert.Equal("SI", imports.UsingAliases.Keys.Single());
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(999086)]
[Fact]
public void BadPdb_DotInAlias()
{
var source = @"
public class C
{
public static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports(
exeBytes,
"Main",
"USystem", // Valid.
"AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped.
"ASI USystem.IO"); // Valid.
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); // Used to throw.
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString());
Assert.Equal("SI", imports.UsingAliases.Keys.Single());
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(1007917)]
[Fact]
public void BadPdb_NestingLevel_TooMany()
{
var source = @"
public class C
{
public static void Main()
{
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
ISymUnmanagedReader symReader;
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main"));
var methodToken = metadataReader.GetToken(methodHandle);
symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem", "USystem.IO" } }, suppressUsingInfo: true).AddUsingInfo(1, 1).Build() },
}.ToImmutableDictionary());
}
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System.IO", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved.
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(1007917)]
[Fact]
public void BadPdb_NestingLevel_TooFew()
{
var source = @"
namespace N
{
public class C
{
public static void Main()
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
ISymUnmanagedReader symReader;
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main"));
var methodToken = metadataReader.GetToken(methodHandle);
symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() },
}.ToImmutableDictionary());
}
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "N.C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved.
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
}
[WorkItem(1084059)]
[Fact]
public void BadPdb_NonStaticTypeImport()
{
var source = @"
namespace N
{
public class C
{
public static void Main()
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
byte[] exeBytes;
byte[] unusedPdbBytes;
ImmutableArray<MetadataReference> references;
var result = comp.EmitAndGetReferences(out exeBytes, out unusedPdbBytes, out references);
Assert.True(result);
ISymUnmanagedReader symReader;
using (var peReader = new PEReader(ImmutableArray.Create(exeBytes)))
{
var metadataReader = peReader.GetMetadataReader();
var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main"));
var methodToken = metadataReader.GetToken(methodHandle);
symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes>
{
{ methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "TSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() },
}.ToImmutableDictionary());
}
var runtime = CreateRuntimeInstance("assemblyName", references, exeBytes, symReader);
var evalContext = CreateMethodContext(runtime, "N.C.Main");
var compContext = evalContext.CreateCompilationContext(SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression));
var imports = compContext.NamespaceBinder.ImportChain.Single();
Assert.Equal(0, imports.Usings.Length); // Note: the import is dropped
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
}
#endregion Invalid PDBs
#region Binder chain
[Fact]
public void ImportsForSimpleUsing()
{
var source = @"
using System;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var actualNamespace = imports.Usings.Single().NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind);
Assert.Equal("System", actualNamespace.ToTestDisplayString());
}
[Fact]
public void ImportsForMultipleUsings()
{
var source = @"
using System;
using System.IO;
using System.Text;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var usings = imports.Usings.Select(u => u.NamespaceOrType).ToArray();
Assert.Equal(3, usings.Length);
var expectedNames = new[] { "System", "System.IO", "System.Text" };
for (int i = 0; i < usings.Length; i++)
{
var actualNamespace = usings[i];
Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind);
Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString());
}
}
[Fact]
public void ImportsForNestedNamespaces()
{
var source = @"
using System;
namespace A
{
using System.IO;
class C
{
int M()
{
return 1;
}
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "A.C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single()).AsEnumerable().ToArray();
Assert.Equal(2, importsList.Length);
var expectedNames = new[] { "System.IO", "System" }; // Innermost-to-outermost
for (int i = 0; i < importsList.Length; i++)
{
var imports = importsList[i];
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var actualNamespace = imports.Usings.Single().NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind);
Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString());
}
}
[Fact]
public void ImportsForNamespaceAlias()
{
var source = @"
using S = System;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(1, usingAliases.Count);
Assert.Equal("S", usingAliases.Keys.Single());
var aliasSymbol = usingAliases.Values.Single().Alias;
Assert.Equal("S", aliasSymbol.Name);
var namespaceSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.Namespace, namespaceSymbol.Kind);
Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)namespaceSymbol).Extent.Kind);
Assert.Equal("System", namespaceSymbol.ToTestDisplayString());
}
[WorkItem(1084059)]
[Fact]
public void ImportsForStaticType()
{
var source = @"
using static System.Math;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.UsingAliases.Count);
Assert.Equal(0, imports.ExternAliases.Length);
var actualType = imports.Usings.Single().NamespaceOrType;
Assert.Equal(SymbolKind.NamedType, actualType.Kind);
Assert.Equal("System.Math", actualType.ToTestDisplayString());
}
[Fact]
public void ImportsForTypeAlias()
{
var source = @"
using I = System.Int32;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(1, usingAliases.Count);
Assert.Equal("I", usingAliases.Keys.Single());
var aliasSymbol = usingAliases.Values.Single().Alias;
Assert.Equal("I", aliasSymbol.Name);
var typeSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind);
Assert.Equal(SpecialType.System_Int32, ((NamedTypeSymbol)typeSymbol).SpecialType);
}
[Fact]
public void ImportsForVerbatimIdentifiers()
{
var source = @"
using @namespace;
using @object = @namespace;
using @string = @namespace.@class<@namespace.@interface>.@struct;
namespace @namespace
{
public class @class<T>
{
public struct @struct
{
}
}
public interface @interface
{
}
}
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.ExternAliases.Length);
var @using = imports.Usings.Single();
var importedNamespace = @using.NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind);
Assert.Equal("namespace", importedNamespace.Name);
var usingAliases = imports.UsingAliases;
const string keyword1 = "object";
const string keyword2 = "string";
AssertEx.SetEqual(usingAliases.Keys, keyword1, keyword2);
var namespaceAlias = usingAliases[keyword1];
var typeAlias = usingAliases[keyword2];
Assert.Equal(keyword1, namespaceAlias.Alias.Name);
var aliasedNamespace = namespaceAlias.Alias.Target;
Assert.Equal(SymbolKind.Namespace, aliasedNamespace.Kind);
Assert.Equal("@namespace", aliasedNamespace.ToTestDisplayString());
Assert.Equal(keyword2, typeAlias.Alias.Name);
var aliasedType = typeAlias.Alias.Target;
Assert.Equal(SymbolKind.NamedType, aliasedType.Kind);
Assert.Equal("@namespace.@class<@namespace.@interface>.@struct", aliasedType.ToTestDisplayString());
}
[Fact]
public void ImportsForGenericTypeAlias()
{
var source = @"
using I = System.Collections.Generic.IEnumerable<string>;
class C
{
int M()
{
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source);
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(1, usingAliases.Count);
Assert.Equal("I", usingAliases.Keys.Single());
var aliasSymbol = usingAliases.Values.Single().Alias;
Assert.Equal("I", aliasSymbol.Name);
var typeSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind);
Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", typeSymbol.ToTestDisplayString());
}
[Fact]
public void ImportsForExternAlias()
{
var source = @"
extern alias X;
class C
{
int M()
{
X::System.Xml.Linq.LoadOptions.None.ToString();
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) });
comp.VerifyDiagnostics();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(0, imports.UsingAliases.Count);
var externAliases = imports.ExternAliases;
Assert.Equal(1, externAliases.Length);
var aliasSymbol = externAliases.Single().Alias;
Assert.Equal("X", aliasSymbol.Name);
var targetSymbol = aliasSymbol.Target;
Assert.Equal(SymbolKind.Namespace, targetSymbol.Kind);
Assert.True(((NamespaceSymbol)targetSymbol).IsGlobalNamespace);
Assert.Equal("System.Xml.Linq", targetSymbol.ContainingAssembly.Name);
var moduleInstance = runtime.Modules.Single(m => m.ModuleMetadata.Name.StartsWith("System.Xml.Linq", StringComparison.OrdinalIgnoreCase));
AssertEx.SetEqual(moduleInstance.MetadataReference.Properties.Aliases, "X");
}
[Fact]
public void ImportsForUsingsConsumingExternAlias()
{
var source = @"
extern alias X;
using SXL = X::System.Xml.Linq;
using LO = X::System.Xml.Linq.LoadOptions;
using X::System.Xml;
class C
{
int M()
{
X::System.Xml.Linq.LoadOptions.None.ToString();
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(1, imports.ExternAliases.Length);
var @using = imports.Usings.Single();
var importedNamespace = @using.NamespaceOrType;
Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind);
Assert.Equal("System.Xml", importedNamespace.ToTestDisplayString());
var usingAliases = imports.UsingAliases;
Assert.Equal(2, usingAliases.Count);
AssertEx.SetEqual(usingAliases.Keys, "SXL", "LO");
var typeAlias = usingAliases["SXL"].Alias;
Assert.Equal("SXL", typeAlias.Name);
Assert.Equal("System.Xml.Linq", typeAlias.Target.ToTestDisplayString());
var namespaceAlias = usingAliases["LO"].Alias;
Assert.Equal("LO", namespaceAlias.Name);
Assert.Equal("System.Xml.Linq.LoadOptions", namespaceAlias.Target.ToTestDisplayString());
}
[Fact]
public void ImportsForUsingsConsumingExternAliasAndGlobal()
{
var source = @"
extern alias X;
using A = X::System.Xml.Linq;
using B = global::System.Xml.Linq;
class C
{
int M()
{
A.LoadOptions.None.ToString();
B.LoadOptions.None.ToString();
return 1;
}
}
";
var comp = CreateCompilationWithMscorlib(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) });
comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify();
var runtime = CreateRuntimeInstance(comp, includeSymbols: true);
var importsList = GetImports(runtime, "C.M", comp.SyntaxTrees.Single().GetRoot().DescendantNodes().OfType<Syntax.LiteralExpressionSyntax>().Single());
var imports = importsList.Single();
Assert.Equal(0, imports.Usings.Length);
Assert.Equal(1, imports.ExternAliases.Length);
var usingAliases = imports.UsingAliases;
Assert.Equal(2, usingAliases.Count);
AssertEx.SetEqual(usingAliases.Keys, "A", "B");
var aliasA = usingAliases["A"].Alias;
Assert.Equal("A", aliasA.Name);
Assert.Equal("System.Xml.Linq", aliasA.Target.ToTestDisplayString());
var aliasB = usingAliases["B"].Alias;
Assert.Equal("B", aliasB.Name);
Assert.Equal(aliasA.Target, aliasB.Target);
}
private static ImportChain GetImports(RuntimeInstance runtime, string methodName, Syntax.ExpressionSyntax syntax)
{
var evalContext = CreateMethodContext(
runtime,
methodName: methodName);
var compContext = evalContext.CreateCompilationContext(syntax);
return compContext.NamespaceBinder.ImportChain;
}
#endregion Binder chain
[Fact]
public void NoSymbols()
{
var source =
@"using N;
class A
{
static void M() { }
}
namespace N
{
class B
{
static void M() { }
}
}";
ResultProperties resultProperties;
string error;
// With symbols, type reference without namespace qualifier.
var testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "A.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: true);
Assert.Null(error);
// Without symbols, type reference without namespace qualifier.
testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "A.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: false);
Assert.Equal(error, "error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)");
// With symbols, type reference inside namespace.
testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "N.B.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: true);
Assert.Null(error);
// Without symbols, type reference inside namespace.
testData = Evaluate(
source,
OutputKind.DynamicallyLinkedLibrary,
methodName: "N.B.M",
expr: "typeof(B)",
resultProperties: out resultProperties,
error: out error,
includeSymbols: false);
Assert.Null(error);
}
[WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")]
[Fact]
public void AssemblyQualifiedNameResolutionWithUnification()
{
var source1 = @"
using SI = System.Int32;
public class C1
{
void M()
{
}
}
";
var source2 = @"
public class C2 : C1
{
}
";
ImmutableArray<MetadataReference> unused;
var comp1 = CreateCompilation(source1, new[] { MscorlibRef_v20}, TestOptions.DebugDll, assemblyName: "A");
byte[] dllBytes1;
byte[] pdbBytes1;
comp1.EmitAndGetReferences(out dllBytes1, out pdbBytes1, out unused);
var ref1 = AssemblyMetadata.CreateFromImage(dllBytes1).GetReference(display: "A");
var comp2 = CreateCompilation(source2, new[] { MscorlibRef_v4_0_30316_17626, ref1 }, TestOptions.DebugDll, assemblyName: "B");
byte[] dllBytes2;
byte[] pdbBytes2;
comp2.EmitAndGetReferences(out dllBytes2, out pdbBytes2, out unused);
var ref2 = AssemblyMetadata.CreateFromImage(dllBytes2).GetReference(display: "B");
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
modulesBuilder.Add(ref1.ToModuleInstance(dllBytes1, new SymReader(pdbBytes1, dllBytes1)));
modulesBuilder.Add(ref2.ToModuleInstance(dllBytes2, new SymReader(pdbBytes2, dllBytes2)));
modulesBuilder.Add(MscorlibRef_v4_0_30316_17626.ToModuleInstance(fullImage: null, symReader: null));
modulesBuilder.Add(ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance(fullImage: null, symReader: null));
using (var runtime = new RuntimeInstance(modulesBuilder.ToImmutableAndFree()))
{
var context = CreateMethodContext(runtime, "C1.M");
string error;
var testData = new CompilationTestData();
context.CompileExpression("typeof(SI)", out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 11 (0xb)
.maxstack 1
IL_0000: ldtoken ""int""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ret
}
");
}
}
}
internal static class ImportChainExtensions
{
internal static Imports Single(this ImportChain importChain)
{
return importChain.AsEnumerable().Single();
}
internal static IEnumerable<Imports> AsEnumerable(this ImportChain importChain)
{
for (var chain = importChain; chain != null; chain = chain.ParentOpt)
{
yield return chain.Imports;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Achartengine.Renderer {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']"
[global::Android.Runtime.Register ("org/achartengine/renderer/XYSeriesRenderer", DoNotGenerateAcw=true)]
public partial class XYSeriesRenderer : global::Org.Achartengine.Renderer.SimpleSeriesRenderer {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']"
[global::Android.Runtime.Register ("org/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type", DoNotGenerateAcw=true)]
public sealed partial class Type : global::Java.Lang.Enum {
static IntPtr ABOVE_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/field[@name='ABOVE']"
[Register ("ABOVE")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type Above {
get {
if (ABOVE_jfieldId == IntPtr.Zero)
ABOVE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ABOVE", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ABOVE_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (ABOVE_jfieldId == IntPtr.Zero)
ABOVE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ABOVE", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, ABOVE_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr BELOW_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/field[@name='BELOW']"
[Register ("BELOW")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type Below {
get {
if (BELOW_jfieldId == IntPtr.Zero)
BELOW_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BELOW", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, BELOW_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (BELOW_jfieldId == IntPtr.Zero)
BELOW_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BELOW", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, BELOW_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr BOUNDS_ABOVE_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/field[@name='BOUNDS_ABOVE']"
[Register ("BOUNDS_ABOVE")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type BoundsAbove {
get {
if (BOUNDS_ABOVE_jfieldId == IntPtr.Zero)
BOUNDS_ABOVE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BOUNDS_ABOVE", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, BOUNDS_ABOVE_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (BOUNDS_ABOVE_jfieldId == IntPtr.Zero)
BOUNDS_ABOVE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BOUNDS_ABOVE", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, BOUNDS_ABOVE_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr BOUNDS_ALL_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/field[@name='BOUNDS_ALL']"
[Register ("BOUNDS_ALL")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type BoundsAll {
get {
if (BOUNDS_ALL_jfieldId == IntPtr.Zero)
BOUNDS_ALL_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BOUNDS_ALL", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, BOUNDS_ALL_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (BOUNDS_ALL_jfieldId == IntPtr.Zero)
BOUNDS_ALL_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BOUNDS_ALL", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, BOUNDS_ALL_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr BOUNDS_BELOW_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/field[@name='BOUNDS_BELOW']"
[Register ("BOUNDS_BELOW")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type BoundsBelow {
get {
if (BOUNDS_BELOW_jfieldId == IntPtr.Zero)
BOUNDS_BELOW_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BOUNDS_BELOW", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, BOUNDS_BELOW_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (BOUNDS_BELOW_jfieldId == IntPtr.Zero)
BOUNDS_BELOW_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "BOUNDS_BELOW", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, BOUNDS_BELOW_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
static IntPtr NONE_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/field[@name='NONE']"
[Register ("NONE")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type None {
get {
if (NONE_jfieldId == IntPtr.Zero)
NONE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "NONE", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, NONE_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (NONE_jfieldId == IntPtr.Zero)
NONE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "NONE", "Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_value = JNIEnv.ToLocalJniHandle (value);
JNIEnv.SetStaticField (class_ref, NONE_jfieldId, native_value);
JNIEnv.DeleteLocalRef (native_value);
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Type); }
}
internal Type (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_valueOf_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("valueOf", "(Ljava/lang/String;)Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;", "")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type ValueOf (string p0)
{
if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero)
id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
IntPtr native_p0 = JNIEnv.NewString (p0);
global::Org.Achartengine.Renderer.XYSeriesRenderer.Type __ret = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer.Type> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, new JValue (native_p0)), JniHandleOwnership.TransferLocalRef);
JNIEnv.DeleteLocalRef (native_p0);
return __ret;
}
static IntPtr id_values;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer.FillOutsideLine.Type']/method[@name='values' and count(parameter)=0]"
[Register ("values", "()[Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;", "")]
public static global::Org.Achartengine.Renderer.XYSeriesRenderer.Type[] Values ()
{
if (id_values == IntPtr.Zero)
id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/achartengine/renderer/XYSeriesRenderer$FillOutsideLine$Type;");
return (global::Org.Achartengine.Renderer.XYSeriesRenderer.Type[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Achartengine.Renderer.XYSeriesRenderer.Type));
}
}
internal static new IntPtr java_class_handle;
internal static new IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/renderer/XYSeriesRenderer", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (XYSeriesRenderer); }
}
protected XYSeriesRenderer (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/constructor[@name='XYSeriesRenderer' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public XYSeriesRenderer () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (XYSeriesRenderer)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor);
}
static Delegate cb_isFillBelowLine;
#pragma warning disable 0169
static Delegate GetIsFillBelowLineHandler ()
{
if (cb_isFillBelowLine == null)
cb_isFillBelowLine = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsFillBelowLine);
return cb_isFillBelowLine;
}
static bool n_IsFillBelowLine (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.FillBelowLine;
}
#pragma warning restore 0169
static Delegate cb_setFillBelowLine_Z;
#pragma warning disable 0169
static Delegate GetSetFillBelowLine_ZHandler ()
{
if (cb_setFillBelowLine_Z == null)
cb_setFillBelowLine_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetFillBelowLine_Z);
return cb_setFillBelowLine_Z;
}
static void n_SetFillBelowLine_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.FillBelowLine = p0;
}
#pragma warning restore 0169
static IntPtr id_isFillBelowLine;
static IntPtr id_setFillBelowLine_Z;
[Obsolete (@"deprecated")]
public virtual bool FillBelowLine {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='isFillBelowLine' and count(parameter)=0]"
[Register ("isFillBelowLine", "()Z", "GetIsFillBelowLineHandler")]
get {
if (id_isFillBelowLine == IntPtr.Zero)
id_isFillBelowLine = JNIEnv.GetMethodID (class_ref, "isFillBelowLine", "()Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isFillBelowLine);
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_isFillBelowLine);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='setFillBelowLine' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("setFillBelowLine", "(Z)V", "GetSetFillBelowLine_ZHandler")]
set {
if (id_setFillBelowLine_Z == IntPtr.Zero)
id_setFillBelowLine_Z = JNIEnv.GetMethodID (class_ref, "setFillBelowLine", "(Z)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setFillBelowLine_Z, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setFillBelowLine_Z, new JValue (value));
}
}
static Delegate cb_isFillPoints;
#pragma warning disable 0169
static Delegate GetIsFillPointsHandler ()
{
if (cb_isFillPoints == null)
cb_isFillPoints = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_IsFillPoints);
return cb_isFillPoints;
}
static bool n_IsFillPoints (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.FillPoints;
}
#pragma warning restore 0169
static Delegate cb_setFillPoints_Z;
#pragma warning disable 0169
static Delegate GetSetFillPoints_ZHandler ()
{
if (cb_setFillPoints_Z == null)
cb_setFillPoints_Z = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, bool>) n_SetFillPoints_Z);
return cb_setFillPoints_Z;
}
static void n_SetFillPoints_Z (IntPtr jnienv, IntPtr native__this, bool p0)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.FillPoints = p0;
}
#pragma warning restore 0169
static IntPtr id_isFillPoints;
static IntPtr id_setFillPoints_Z;
public virtual bool FillPoints {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='isFillPoints' and count(parameter)=0]"
[Register ("isFillPoints", "()Z", "GetIsFillPointsHandler")]
get {
if (id_isFillPoints == IntPtr.Zero)
id_isFillPoints = JNIEnv.GetMethodID (class_ref, "isFillPoints", "()Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isFillPoints);
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, id_isFillPoints);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='setFillPoints' and count(parameter)=1 and parameter[1][@type='boolean']]"
[Register ("setFillPoints", "(Z)V", "GetSetFillPoints_ZHandler")]
set {
if (id_setFillPoints_Z == IntPtr.Zero)
id_setFillPoints_Z = JNIEnv.GetMethodID (class_ref, "setFillPoints", "(Z)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setFillPoints_Z, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setFillPoints_Z, new JValue (value));
}
}
static Delegate cb_getLineWidth;
#pragma warning disable 0169
static Delegate GetGetLineWidthHandler ()
{
if (cb_getLineWidth == null)
cb_getLineWidth = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetLineWidth);
return cb_getLineWidth;
}
static float n_GetLineWidth (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.LineWidth;
}
#pragma warning restore 0169
static Delegate cb_setLineWidth_F;
#pragma warning disable 0169
static Delegate GetSetLineWidth_FHandler ()
{
if (cb_setLineWidth_F == null)
cb_setLineWidth_F = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, float>) n_SetLineWidth_F);
return cb_setLineWidth_F;
}
static void n_SetLineWidth_F (IntPtr jnienv, IntPtr native__this, float p0)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.LineWidth = p0;
}
#pragma warning restore 0169
static IntPtr id_getLineWidth;
static IntPtr id_setLineWidth_F;
public virtual float LineWidth {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='getLineWidth' and count(parameter)=0]"
[Register ("getLineWidth", "()F", "GetGetLineWidthHandler")]
get {
if (id_getLineWidth == IntPtr.Zero)
id_getLineWidth = JNIEnv.GetMethodID (class_ref, "getLineWidth", "()F");
if (GetType () == ThresholdType)
return JNIEnv.CallFloatMethod (Handle, id_getLineWidth);
else
return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, id_getLineWidth);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='setLineWidth' and count(parameter)=1 and parameter[1][@type='float']]"
[Register ("setLineWidth", "(F)V", "GetSetLineWidth_FHandler")]
set {
if (id_setLineWidth_F == IntPtr.Zero)
id_setLineWidth_F = JNIEnv.GetMethodID (class_ref, "setLineWidth", "(F)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setLineWidth_F, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setLineWidth_F, new JValue (value));
}
}
static Delegate cb_getPointStrokeWidth;
#pragma warning disable 0169
static Delegate GetGetPointStrokeWidthHandler ()
{
if (cb_getPointStrokeWidth == null)
cb_getPointStrokeWidth = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, float>) n_GetPointStrokeWidth);
return cb_getPointStrokeWidth;
}
static float n_GetPointStrokeWidth (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.PointStrokeWidth;
}
#pragma warning restore 0169
static Delegate cb_setPointStrokeWidth_F;
#pragma warning disable 0169
static Delegate GetSetPointStrokeWidth_FHandler ()
{
if (cb_setPointStrokeWidth_F == null)
cb_setPointStrokeWidth_F = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, float>) n_SetPointStrokeWidth_F);
return cb_setPointStrokeWidth_F;
}
static void n_SetPointStrokeWidth_F (IntPtr jnienv, IntPtr native__this, float p0)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.PointStrokeWidth = p0;
}
#pragma warning restore 0169
static IntPtr id_getPointStrokeWidth;
static IntPtr id_setPointStrokeWidth_F;
public virtual float PointStrokeWidth {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='getPointStrokeWidth' and count(parameter)=0]"
[Register ("getPointStrokeWidth", "()F", "GetGetPointStrokeWidthHandler")]
get {
if (id_getPointStrokeWidth == IntPtr.Zero)
id_getPointStrokeWidth = JNIEnv.GetMethodID (class_ref, "getPointStrokeWidth", "()F");
if (GetType () == ThresholdType)
return JNIEnv.CallFloatMethod (Handle, id_getPointStrokeWidth);
else
return JNIEnv.CallNonvirtualFloatMethod (Handle, ThresholdClass, id_getPointStrokeWidth);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='setPointStrokeWidth' and count(parameter)=1 and parameter[1][@type='float']]"
[Register ("setPointStrokeWidth", "(F)V", "GetSetPointStrokeWidth_FHandler")]
set {
if (id_setPointStrokeWidth_F == IntPtr.Zero)
id_setPointStrokeWidth_F = JNIEnv.GetMethodID (class_ref, "setPointStrokeWidth", "(F)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setPointStrokeWidth_F, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setPointStrokeWidth_F, new JValue (value));
}
}
static Delegate cb_getPointStyle;
#pragma warning disable 0169
static Delegate GetGetPointStyleHandler ()
{
if (cb_getPointStyle == null)
cb_getPointStyle = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetPointStyle);
return cb_getPointStyle;
}
static IntPtr n_GetPointStyle (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.PointStyle);
}
#pragma warning restore 0169
static Delegate cb_setPointStyle_Lorg_achartengine_chart_PointStyle_;
#pragma warning disable 0169
static Delegate GetSetPointStyle_Lorg_achartengine_chart_PointStyle_Handler ()
{
if (cb_setPointStyle_Lorg_achartengine_chart_PointStyle_ == null)
cb_setPointStyle_Lorg_achartengine_chart_PointStyle_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetPointStyle_Lorg_achartengine_chart_PointStyle_);
return cb_setPointStyle_Lorg_achartengine_chart_PointStyle_;
}
static void n_SetPointStyle_Lorg_achartengine_chart_PointStyle_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Org.Achartengine.Chart.PointStyle p0 = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PointStyle> (native_p0, JniHandleOwnership.DoNotTransfer);
__this.PointStyle = p0;
}
#pragma warning restore 0169
static IntPtr id_getPointStyle;
static IntPtr id_setPointStyle_Lorg_achartengine_chart_PointStyle_;
public virtual global::Org.Achartengine.Chart.PointStyle PointStyle {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='getPointStyle' and count(parameter)=0]"
[Register ("getPointStyle", "()Lorg/achartengine/chart/PointStyle;", "GetGetPointStyleHandler")]
get {
if (id_getPointStyle == IntPtr.Zero)
id_getPointStyle = JNIEnv.GetMethodID (class_ref, "getPointStyle", "()Lorg/achartengine/chart/PointStyle;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PointStyle> (JNIEnv.CallObjectMethod (Handle, id_getPointStyle), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.PointStyle> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getPointStyle), JniHandleOwnership.TransferLocalRef);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='setPointStyle' and count(parameter)=1 and parameter[1][@type='org.achartengine.chart.PointStyle']]"
[Register ("setPointStyle", "(Lorg/achartengine/chart/PointStyle;)V", "GetSetPointStyle_Lorg_achartengine_chart_PointStyle_Handler")]
set {
if (id_setPointStyle_Lorg_achartengine_chart_PointStyle_ == IntPtr.Zero)
id_setPointStyle_Lorg_achartengine_chart_PointStyle_ = JNIEnv.GetMethodID (class_ref, "setPointStyle", "(Lorg/achartengine/chart/PointStyle;)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setPointStyle_Lorg_achartengine_chart_PointStyle_, new JValue (value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setPointStyle_Lorg_achartengine_chart_PointStyle_, new JValue (value));
}
}
static Delegate cb_setFillBelowLineColor_I;
#pragma warning disable 0169
static Delegate GetSetFillBelowLineColor_IHandler ()
{
if (cb_setFillBelowLineColor_I == null)
cb_setFillBelowLineColor_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_SetFillBelowLineColor_I);
return cb_setFillBelowLineColor_I;
}
static void n_SetFillBelowLineColor_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Renderer.XYSeriesRenderer __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.XYSeriesRenderer> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.SetFillBelowLineColor (p0);
}
#pragma warning restore 0169
static IntPtr id_setFillBelowLineColor_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.renderer']/class[@name='XYSeriesRenderer']/method[@name='setFillBelowLineColor' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("setFillBelowLineColor", "(I)V", "GetSetFillBelowLineColor_IHandler")]
public virtual void SetFillBelowLineColor (int p0)
{
if (id_setFillBelowLineColor_I == IntPtr.Zero)
id_setFillBelowLineColor_I = JNIEnv.GetMethodID (class_ref, "setFillBelowLineColor", "(I)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setFillBelowLineColor_I, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setFillBelowLineColor_I, new JValue (p0));
}
}
}
| |
using System.Collections.Generic;
using GitTools.Testing;
using GitVersion;
using GitVersion.Extensions;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
using GitVersionCore.Tests.Helpers;
using LibGit2Sharp;
using NUnit.Framework;
namespace GitVersionCore.Tests.IntegrationTests
{
[TestFixture]
public class FeatureBranchScenarios : TestBase
{
[Test]
public void ShouldInheritIncrementCorrectlyWithMultiplePossibleParentsAndWeirdlyNamedDevelopBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
fixture.Repository.CreateBranch("development");
Commands.Checkout(fixture.Repository, "development");
//Create an initial feature branch
var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123");
Commands.Checkout(fixture.Repository, "feature/JIRA-123");
fixture.Repository.MakeCommits(1);
//Merge it
Commands.Checkout(fixture.Repository, "development");
fixture.Repository.Merge(feature123, Generate.SignatureNow());
//Create a second feature branch
fixture.Repository.CreateBranch("feature/JIRA-124");
Commands.Checkout(fixture.Repository, "feature/JIRA-124");
fixture.Repository.MakeCommits(1);
fixture.AssertFullSemver("1.1.0-JIRA-124.1+2");
}
[Test]
public void BranchCreatedAfterFastForwardMergeShouldInheritCorrectly()
{
var config = new Config
{
Branches =
{
{
"unstable",
new BranchConfig
{
Increment = IncrementStrategy.Minor,
Regex = "unstable",
SourceBranches = new HashSet<string>(),
IsSourceBranchFor = new HashSet<string> { "feature" }
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
fixture.Repository.CreateBranch("unstable");
Commands.Checkout(fixture.Repository, "unstable");
//Create an initial feature branch
var feature123 = fixture.Repository.CreateBranch("feature/JIRA-123");
Commands.Checkout(fixture.Repository, "feature/JIRA-123");
fixture.Repository.MakeCommits(1);
//Merge it
Commands.Checkout(fixture.Repository, "unstable");
fixture.Repository.Merge(feature123, Generate.SignatureNow());
//Create a second feature branch
fixture.Repository.CreateBranch("feature/JIRA-124");
Commands.Checkout(fixture.Repository, "feature/JIRA-124");
fixture.Repository.MakeCommits(1);
fixture.AssertFullSemver("1.1.0-JIRA-124.1+2", config);
}
[Test]
public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffDevelop()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
fixture.Repository.CreateBranch("develop");
Commands.Checkout(fixture.Repository, "develop");
fixture.Repository.CreateBranch("feature/JIRA-123");
Commands.Checkout(fixture.Repository, "feature/JIRA-123");
fixture.Repository.MakeCommits(5);
fixture.AssertFullSemver("1.1.0-JIRA-123.1+5");
}
[Test]
public void ShouldNotUseNumberInFeatureBranchAsPreReleaseNumberOffMaster()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
fixture.Repository.CreateBranch("feature/JIRA-123");
Commands.Checkout(fixture.Repository, "feature/JIRA-123");
fixture.Repository.MakeCommits(5);
fixture.AssertFullSemver("1.0.1-JIRA-123.1+5");
}
[Test]
public void TestFeatureBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
fixture.Repository.CreateBranch("feature-test");
Commands.Checkout(fixture.Repository, "feature-test");
fixture.Repository.MakeCommits(5);
fixture.AssertFullSemver("1.0.1-test.1+5");
}
[Test]
public void TestFeaturesBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
fixture.Repository.CreateBranch("features/test");
Commands.Checkout(fixture.Repository, "features/test");
fixture.Repository.MakeCommits(5);
fixture.AssertFullSemver("1.0.1-test.1+5");
}
[Test]
public void WhenTwoFeatureBranchPointToTheSameCommit()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
fixture.Repository.CreateBranch("develop");
Commands.Checkout(fixture.Repository, "develop");
fixture.Repository.CreateBranch("feature/feature1");
Commands.Checkout(fixture.Repository, "feature/feature1");
fixture.Repository.MakeACommit();
fixture.Repository.CreateBranch("feature/feature2");
Commands.Checkout(fixture.Repository, "feature/feature2");
fixture.AssertFullSemver("0.1.0-feature2.1+1");
}
[Test]
public void ShouldBePossibleToMergeDevelopForALongRunningBranchWhereDevelopAndMasterAreEqual()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("v1.0.0");
fixture.Repository.CreateBranch("develop");
Commands.Checkout(fixture.Repository, "develop");
fixture.Repository.CreateBranch("feature/longrunning");
Commands.Checkout(fixture.Repository, "feature/longrunning");
fixture.Repository.MakeACommit();
Commands.Checkout(fixture.Repository, "develop");
fixture.Repository.MakeACommit();
Commands.Checkout(fixture.Repository, "master");
fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow());
fixture.Repository.ApplyTag("v1.1.0");
Commands.Checkout(fixture.Repository, "feature/longrunning");
fixture.Repository.Merge(fixture.Repository.Branches["develop"], Generate.SignatureNow());
var configuration = new Config { VersioningMode = VersioningMode.ContinuousDeployment };
fixture.AssertFullSemver("1.2.0-longrunning.2", configuration);
}
[Test]
public void CanUseBranchNameOffAReleaseBranch()
{
var config = new Config
{
Branches =
{
{ "release", new BranchConfig { Tag = "build" } },
{ "feature", new BranchConfig { Tag = "useBranchName" } }
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("release/0.3.0");
fixture.MakeATaggedCommit("v0.3.0-build.1");
fixture.MakeACommit();
fixture.BranchTo("feature/PROJ-1");
fixture.MakeACommit();
fixture.AssertFullSemver("0.3.0-PROJ-1.1+2", config);
}
[TestCase("alpha", "JIRA-123", "alpha")]
[TestCase("useBranchName", "JIRA-123", "JIRA-123")]
[TestCase("alpha.{BranchName}", "JIRA-123", "alpha.JIRA-123")]
public void ShouldUseConfiguredTag(string tag, string featureName, string preReleaseTagName)
{
var config = new Config
{
Branches =
{
{ "feature", new BranchConfig { Tag = tag } }
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeATaggedCommit("1.0.0");
var featureBranchName = $"feature/{featureName}";
fixture.Repository.CreateBranch(featureBranchName);
Commands.Checkout(fixture.Repository, featureBranchName);
fixture.Repository.MakeCommits(5);
var expectedFullSemVer = $"1.0.1-{preReleaseTagName}.1+5";
fixture.AssertFullSemver(expectedFullSemVer, config);
}
[Test]
public void BranchCreatedAfterFinishReleaseShouldInheritAndIncrementFromLastMasterCommitTag()
{
using var fixture = new BaseGitFlowRepositoryFixture("0.1.0");
//validate current version
fixture.AssertFullSemver("0.2.0-alpha.1");
fixture.Repository.CreateBranch("release/0.2.0");
Commands.Checkout(fixture.Repository, "release/0.2.0");
//validate release version
fixture.AssertFullSemver("0.2.0-beta.1+0");
fixture.Checkout("master");
fixture.Repository.MergeNoFF("release/0.2.0");
fixture.Repository.ApplyTag("0.2.0");
//validate master branch version
fixture.AssertFullSemver("0.2.0");
fixture.Checkout("develop");
fixture.Repository.MergeNoFF("release/0.2.0");
fixture.Repository.Branches.Remove("release/2.0.0");
fixture.Repository.MakeACommit();
//validate develop branch version after merging release 0.2.0 to master and develop (finish release)
fixture.AssertFullSemver("0.3.0-alpha.1");
//create a feature branch from develop
fixture.BranchTo("feature/TEST-1");
fixture.Repository.MakeACommit();
//I'm not entirely sure what the + value should be but I know the semvar major/minor/patch should be 0.3.0
fixture.AssertFullSemver("0.3.0-TEST-1.1+2");
}
[Test]
public void ShouldPickUpVersionFromDevelopAfterReleaseBranchCreated()
{
using var fixture = new EmptyRepositoryFixture();
// Create develop and release branches
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
fixture.Checkout("develop");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-alpha.1");
// create a feature branch from develop and verify the version
fixture.BranchTo("feature/test");
fixture.AssertFullSemver("1.1.0-test.1+1");
}
[Test]
public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack()
{
using var fixture = new EmptyRepositoryFixture();
// Create develop and release branches
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
// merge release into develop
fixture.Checkout("develop");
fixture.MergeNoFF("release/1.0");
fixture.AssertFullSemver("1.1.0-alpha.2");
// create a feature branch from develop and verify the version
fixture.BranchTo("feature/test");
fixture.AssertFullSemver("1.1.0-test.1+2");
}
public class WhenMasterMarkedAsIsDevelop
{
[Test]
public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated()
{
var config = new Config
{
Branches = new Dictionary<string, BranchConfig>
{
{
"master", new BranchConfig
{
TracksReleaseBranches = true,
Regex = "master"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
// Create release branch
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.1+1", config);
// create a feature branch from master and verify the version
fixture.BranchTo("feature/test");
fixture.AssertFullSemver("1.0.1-test.1+1", config);
}
[Test]
public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack()
{
var config = new Config
{
Branches = new Dictionary<string, BranchConfig>
{
{
"master", new BranchConfig
{
TracksReleaseBranches = true,
Regex = "master"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
// Create release branch
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
// merge release into master
fixture.Checkout("master");
fixture.MergeNoFF("release/1.0");
fixture.AssertFullSemver("1.0.1+2", config);
// create a feature branch from master and verify the version
fixture.BranchTo("feature/test");
fixture.AssertFullSemver("1.0.1-test.1+2", config);
}
}
public class WhenFeatureBranchHasNoConfig
{
[Test]
public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated()
{
using var fixture = new EmptyRepositoryFixture();
// Create develop and release branches
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
fixture.Checkout("develop");
fixture.MakeACommit();
fixture.AssertFullSemver("1.1.0-alpha.1");
// create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version
fixture.BranchTo("misnamed");
fixture.AssertFullSemver("1.1.0-misnamed.1+1");
}
[Test]
public void ShouldPickUpVersionFromDevelopAfterReleaseBranchMergedBack()
{
using var fixture = new EmptyRepositoryFixture();
// Create develop and release branches
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
// merge release into develop
fixture.Checkout("develop");
fixture.MergeNoFF("release/1.0");
fixture.AssertFullSemver("1.1.0-alpha.2");
// create a misnamed feature branch (i.e. it uses the default config) from develop and verify the version
fixture.BranchTo("misnamed");
fixture.AssertFullSemver("1.1.0-misnamed.1+2");
}
// ReSharper disable once MemberHidesStaticFromOuterClass
public class WhenMasterMarkedAsIsDevelop
{
[Test]
public void ShouldPickUpVersionFromMasterAfterReleaseBranchCreated()
{
var config = new Config
{
Branches = new Dictionary<string, BranchConfig>
{
{
"master", new BranchConfig
{
TracksReleaseBranches = true,
Regex = "master"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
// Create release branch
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("1.0.1+1", config);
// create a misnamed feature branch (i.e. it uses the default config) from master and verify the version
fixture.BranchTo("misnamed");
fixture.AssertFullSemver("1.0.1-misnamed.1+1", config);
}
[Test]
public void ShouldPickUpVersionFromMasterAfterReleaseBranchMergedBack()
{
var config = new Config
{
Branches = new Dictionary<string, BranchConfig>
{
{
"master", new BranchConfig
{
TracksReleaseBranches = true,
Regex = "master"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
// Create release branch
fixture.MakeACommit();
fixture.BranchTo("release/1.0");
fixture.MakeACommit();
// merge release into master
fixture.Checkout("master");
fixture.MergeNoFF("release/1.0");
fixture.AssertFullSemver("1.0.1+2", config);
// create a misnamed feature branch (i.e. it uses the default config) from master and verify the version
fixture.BranchTo("misnamed");
fixture.AssertFullSemver("1.0.1-misnamed.1+2", config);
}
}
}
[Test]
public void PickUpVersionFromMasterMarkedWithIsTracksReleaseBranches()
{
var config = new Config
{
VersioningMode = VersioningMode.ContinuousDelivery,
Branches = new Dictionary<string, BranchConfig>
{
{
"master", new BranchConfig
{
Tag = "pre",
TracksReleaseBranches = true,
}
},
{
"release", new BranchConfig
{
IsReleaseBranch = true,
Tag = "rc",
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
// create a release branch and tag a release
fixture.BranchTo("release/0.10.0");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.AssertFullSemver("0.10.0-rc.1+2", config);
// switch to master and verify the version
fixture.Checkout("master");
fixture.MakeACommit();
fixture.AssertFullSemver("0.10.1-pre.1+1", config);
// create a feature branch from master and verify the version
fixture.BranchTo("MyFeatureD");
fixture.AssertFullSemver("0.10.1-MyFeatureD.1+1", config);
}
[Test]
public void ShouldHaveAGreaterSemVerAfterDevelopIsMergedIntoFeature()
{
var config = new Config
{
VersioningMode = VersioningMode.ContinuousDeployment,
AssemblyVersioningScheme = AssemblyVersioningScheme.Major,
AssemblyFileVersioningFormat = "{MajorMinorPatch}.{env:WeightedPreReleaseNumber ?? 0}",
LegacySemVerPadding = 4,
BuildMetaDataPadding = 4,
CommitsSinceVersionSourcePadding = 4,
CommitMessageIncrementing = CommitMessageIncrementMode.Disabled,
Branches = new Dictionary<string, BranchConfig>
{
{
"develop", new BranchConfig
{
PreventIncrementOfMergedBranchVersion = true
}
},
{
"feature", new BranchConfig
{
Tag = "feat-{BranchName}"
}
}
}
};
using var fixture = new EmptyRepositoryFixture();
fixture.MakeACommit();
fixture.BranchTo("develop");
fixture.MakeACommit();
fixture.ApplyTag("16.23.0");
fixture.MakeACommit();
fixture.BranchTo("feature/featX");
fixture.MakeACommit();
fixture.Checkout("develop");
fixture.MakeACommit();
fixture.Checkout("feature/featX");
fixture.MergeNoFF("develop");
fixture.AssertFullSemver("16.24.0-feat-featX.4", config);
}
}
}
| |
/**
* Copyright (c) 2015, GruntTheDivine All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT ,STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
**/
using System;
using Iodine.Compiler;
namespace Iodine.Runtime
{
public class IodineFloat : IodineObject
{
public static readonly IodineTypeDefinition TypeDefinition = new FloatTypeDef ();
public static readonly IodineFloat Epsilon = new IodineFloat (double.Epsilon);
class FloatTypeDef : IodineTypeDefinition
{
public FloatTypeDef ()
: base ("Float")
{
SetDocumentation ("A double precision floating point");
}
public override IodineObject Invoke (VirtualMachine vm, IodineObject[] args)
{
if (args.Length <= 0) {
vm.RaiseException (new IodineArgumentException (1));
}
return new IodineFloat (Double.Parse (args [0].ToString ()));
}
}
public readonly double Value;
public IodineFloat (double val)
: base (TypeDefinition)
{
Value = val;
}
public override bool Equals (IodineObject obj)
{
var floatVal = obj as IodineFloat;
if (floatVal != null) {
return Math.Abs (floatVal.Value - Value) < double.Epsilon;
}
return false;
}
public override IodineObject Add (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return new IodineFloat (Value + floatVal);
}
public override IodineObject Sub (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return new IodineFloat (Value - floatVal);
}
public override IodineObject Mul (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return new IodineFloat (Value * floatVal);
}
public override IodineObject Div (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return new IodineFloat (Value / floatVal);
}
public override IodineObject Mod (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return new IodineFloat (Value % floatVal);
}
public override IodineObject Equals (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"));
return null;
}
return IodineBool.Create (Math.Abs (Value - floatVal) < double.Epsilon);
}
public override IodineObject NotEquals (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"));
return null;
}
return IodineBool.Create (Math.Abs (Value - floatVal) > double.Epsilon);
}
public override IodineObject GreaterThan (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return IodineBool.Create (Value > floatVal);
}
public override IodineObject GreaterThanOrEqual (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return IodineBool.Create (Value >= floatVal);
}
public override IodineObject LessThan (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return IodineBool.Create (Value < floatVal);
}
public override IodineObject LessThanOrEqual (VirtualMachine vm, IodineObject right)
{
double floatVal;
if (!(TryConvertToFloat (right, out floatVal))) {
vm.RaiseException (new IodineTypeException (
"Right hand value expected to be of type Float"
));
return null;
}
return IodineBool.Create (Value <= floatVal);
}
public override IodineObject PerformUnaryOperation (VirtualMachine vm, UnaryOperation op)
{
switch (op) {
case UnaryOperation.Negate:
return new IodineFloat (-Value);
}
return null;
}
private bool TryConvertToFloat (IodineObject obj, out double result)
{
if (obj is IodineFloat) {
result = ((IodineFloat)obj).Value;
return true;
}
if (obj is IodineInteger) {
result = (double)((IodineInteger)obj).Value;
return true;
}
result = 0;
return false;
}
public override bool IsTrue ()
{
return Value > 0.0f;
}
public override string ToString ()
{
return Value.ToString ();
}
public override int GetHashCode ()
{
return Value.GetHashCode ();
}
}
}
| |
using System;
using Microsoft.SPOT.Presentation.Media;
using Skewworks.NETMF;
using Skewworks.NETMF.Controls;
namespace Skewworks.Tinkr.Controls
{
[Serializable]
public class SlidePanel : Container
{
#region Variables
private Color _bkg;
private string _title;
//private rect _Bounds;
protected internal bool BeingDisplayed { get; set; }
protected internal rect DispRect { get; set; }
// Auto Scroll
private int _maxX;
private int _maxY;
private int _minX;
private int _minY;
private bool _moving;
private bool _touch;
int _w, _h;
int _x, _y;
#endregion
#region Constructors
public SlidePanel(string name, string title)
{
Name = name;
_title = title;
_bkg = Colors.White;
}
// ReSharper disable once UnusedParameter.Local
public SlidePanel(string name, string title, Color background)
{
Name = name;
_title = title;
_bkg = Colors.White;
}
#endregion
#region Properties
/// <summary>
/// Gets/Sets background color
/// </summary>
public Color BackColor
{
get { return _bkg; }
set
{
if (value == _bkg)
return;
_bkg = value;
Invalidate();
}
}
public string Title
{
get { return _title; }
set
{
if (_title == value)
return;
_title = value;
Invalidate();
}
}
public override int Height
{
get { return _h; }
set { _h = value; }
}
public override int Width
{
get { return _w; }
set { _w = value; }
}
public override int X
{
get { return _x; }
set
{
if (_x == value)
return;
_x = value;
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
Children[i].UpdateOffsets();
}
}
}
public override int Y
{
get { return _y; }
set
{
if (_y == value)
return;
_y = value;
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
Children[i].UpdateOffsets();
}
}
}
#endregion
#region Button Methods
protected override void ButtonPressedMessage(int buttonId, ref bool handled)
{
if (Children != null)
{
if (ActiveChild != null)
ActiveChild.SendButtonEvent(buttonId, true);
else
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i].ScreenBounds.Contains(Core.MousePosition))
{
handled = true;
Children[i].SendButtonEvent(buttonId, true);
break;
}
}
}
}
}
protected override void ButtonReleasedMessage(int buttonId, ref bool handled)
{
if (Children != null)
{
if (ActiveChild != null)
ActiveChild.SendButtonEvent(buttonId, false);
else
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i].ScreenBounds.Contains(Core.MousePosition))
{
handled = true;
Children[i].SendButtonEvent(buttonId, false);
break;
}
}
}
}
}
#endregion
#region Keyboard Methods
protected override void KeyboardAltKeyMessage(int key, bool pressed, ref bool handled)
{
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendKeyboardAltKeyEvent(key, pressed);
}
base.KeyboardAltKeyMessage(key, pressed, ref handled);
}
protected override void KeyboardKeyMessage(char key, bool pressed, ref bool handled)
{
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendKeyboardKeyEvent(key, pressed);
}
base.KeyboardKeyMessage(key, pressed, ref handled);
}
#endregion
#region Touch Methods
protected override void TouchDownMessage(object sender, point point, ref bool handled)
{
// Check Controls
if (Children != null)
{
lock (Children)
{
for (int i = Children.Length - 1; i >= 0; i--)
{
if (Children[i].Visible && Children[i].HitTest(point))
{
ActiveChild = Children[i];
Children[i].SendTouchDown(this, point);
handled = true;
return;
}
}
}
}
if (ActiveChild != null)
{
ActiveChild.Blur();
Render(ActiveChild.ScreenBounds, true);
ActiveChild = null;
}
_touch = true;
}
protected override void TouchGestureMessage(object sender, TouchType type, float force, ref bool handled)
{
if (ActiveChild != null)
{
handled = true;
ActiveChild.SendTouchGesture(sender, type, force);
}
}
protected override void TouchMoveMessage(object sender, point point, ref bool handled)
{
if (_touch)
{
bool bUpdated = false;
int diffY = 0;
int diffX = 0;
// Scroll Y
if (_maxY > Height)
{
diffY = point.Y - LastTouch.Y;
if (diffY > 0 && _minY < Top)
{
diffY = Math.Min(diffY, _minY + Top);
bUpdated = true;
}
else if (diffY < 0 && _maxY > Height)
{
diffY = Math.Min(-diffY, _maxY - _minY - Height);
bUpdated = true;
}
else
{
diffY = 0;
}
_moving = true;
}
// Scroll X
if (_maxX > Width)
{
diffX = point.X - LastTouch.X;
if (diffX > 0 && _minX < Left)
{
diffX = Math.Min(diffX, _minX + Left);
bUpdated = true;
}
else if (diffX < 0 && _maxX > Width)
{
diffX = Math.Min(-diffX, _maxX - _minX - Width);
bUpdated = true;
}
else
{
diffX = 0;
}
_moving = true;
handled = true;
}
LastTouch = point;
if (bUpdated)
{
var ptOff = new point(diffX, diffY);
for (int i = 0; i < Children.Length; i++)
{
Children[i].UpdateOffsets(ptOff);
}
Render(true);
handled = true;
}
else if (_moving)
{
Render(true);
}
}
else
{
// Check Controls
if (ActiveChild != null && ActiveChild.Touching)
{
ActiveChild.SendTouchMove(this, point);
handled = true;
}
else if (Children != null)
{
for (int i = Children.Length - 1; i >= 0; i--)
{
if (Children[i].Touching || Children[i].HitTest(point))
Children[i].SendTouchMove(this, point);
}
}
}
base.TouchMoveMessage(sender, point, ref handled);
}
protected override void TouchUpMessage(object sender, point point, ref bool handled)
{
_touch = false;
if (_moving)
{
_moving = false;
Render(true);
}
else
{
// Check Controls
if (Children != null)
{
for (int i = Children.Length - 1; i >= 0; i--)
{
try
{
if (Children[i].HitTest(point) && !handled)
{
handled = true;
Children[i].SendTouchUp(this, point);
}
else if (Children[i].Touching)
Children[i].SendTouchUp(this, point);
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{
// This can happen if the user clears the Form during a tap
}
}
}
}
base.TouchUpMessage(sender, point, ref handled);
}
#endregion
#region GUI
protected override void OnRender(int x, int y, int width, int height)
{
var area = new rect(x, y, width, height);
_maxX = Width;
_maxY = Height;
Core.Screen.DrawRectangle(0, 0, Left, Top, Width, Height, 0, 0, _bkg, 0, 0, _bkg, 0, 0, 256);
// Render controls
if (Children != null)
{
for (int i = 0; i < Children.Length; i++)
{
if (Children[i] != null)
{
if (Children[i].ScreenBounds.Intersects(area))
Children[i].Render();
if (Children[i].Y < _minY)
_minY = Children[i].Y;
else if (Children[i].Y + Children[i].Height > _maxY)
_maxY = Children[i].Y + Children[i].Height;
if (Children[i].X < _minX)
_minX = Children[i].X;
else if (Children[i].X + Children[i].Width > _maxX)
_maxX = Children[i].X + Children[i].Width;
}
}
}
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Runtime.Serialization;
#if !CORECLR
using System.Security.Permissions;
#else
// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace System.Management.Automation
{
/// <summary>
/// The exception thrown if the specified value can not be bound parameter of a command.
/// </summary>
[Serializable]
public class ParameterBindingException : RuntimeException
{
#region Constructors
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingException.
/// </summary>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// <!--
/// InvocationInfo.MyCommand.Name == {0}
/// -->
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
/// If position is null, the one from the InvocationInfo is used.
/// <!--
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// -->
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
/// <!--
/// parameterName == {1}
/// -->
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
/// <!--
/// parameterType == {2}
/// -->
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
/// <!--
/// typeSpecified == {3}
/// -->
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
/// <!--
/// starts at {6}
/// -->
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
internal ParameterBindingException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(errorCategory, invocationInfo, errorPosition, errorId, null, null)
{
if (String.IsNullOrEmpty(resourceString))
{
throw PSTraceSource.NewArgumentException("resourceString");
}
if (String.IsNullOrEmpty(errorId))
{
throw PSTraceSource.NewArgumentException("errorId");
}
_invocationInfo = invocationInfo;
if (_invocationInfo != null)
{
_commandName = invocationInfo.MyCommand.Name;
}
_parameterName = parameterName;
_parameterType = parameterType;
_typeSpecified = typeSpecified;
if ((errorPosition == null) && (_invocationInfo != null))
{
errorPosition = invocationInfo.ScriptPosition;
}
if (errorPosition != null)
{
_line = errorPosition.StartLineNumber;
_offset = errorPosition.StartColumnNumber;
}
_resourceString = resourceString;
_errorId = errorId;
if (args != null)
{
_args = args;
}
}
/// <summary>
/// Constructs a ParameterBindingException
/// </summary>
///
/// <param name="innerException">
/// The inner exception.
/// </param>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
/// If position is null, the one from the InvocationInfo is used.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(errorCategory, invocationInfo, errorPosition, errorId, null, innerException)
{
if (invocationInfo == null)
{
throw PSTraceSource.NewArgumentNullException("invocationInfo");
}
if (String.IsNullOrEmpty(resourceString))
{
throw PSTraceSource.NewArgumentException("resourceString");
}
if (String.IsNullOrEmpty(errorId))
{
throw PSTraceSource.NewArgumentException("errorId");
}
_invocationInfo = invocationInfo;
_commandName = invocationInfo.MyCommand.Name;
_parameterName = parameterName;
_parameterType = parameterType;
_typeSpecified = typeSpecified;
if (errorPosition == null)
{
errorPosition = invocationInfo.ScriptPosition;
}
if (errorPosition != null)
{
_line = errorPosition.StartLineNumber;
_offset = errorPosition.StartColumnNumber;
}
_resourceString = resourceString;
_errorId = errorId;
if (args != null)
{
_args = args;
}
}
/// <summary>
///
/// </summary>
/// <param name="innerException"></param>
/// <param name="pbex"></param>
/// <param name="resourceString"></param>
/// <param name="args"></param>
internal ParameterBindingException(
Exception innerException,
ParameterBindingException pbex,
string resourceString,
params object[] args)
: base(String.Empty, innerException)
{
if (pbex == null)
{
throw PSTraceSource.NewArgumentNullException("pbex");
}
if (String.IsNullOrEmpty(resourceString))
{
throw PSTraceSource.NewArgumentException("resourceString");
}
_invocationInfo = pbex.CommandInvocation;
if (_invocationInfo != null)
{
_commandName = _invocationInfo.MyCommand.Name;
}
IScriptExtent errorPosition = null;
if (_invocationInfo != null)
{
errorPosition = _invocationInfo.ScriptPosition;
}
_line = pbex.Line;
_offset = pbex.Offset;
_parameterName = pbex.ParameterName;
_parameterType = pbex.ParameterType;
_typeSpecified = pbex.TypeSpecified;
_errorId = pbex.ErrorId;
_resourceString = resourceString;
if (args != null)
{
_args = args;
}
base.SetErrorCategory(pbex.ErrorRecord._category);
base.SetErrorId(_errorId);
if (_invocationInfo != null)
{
base.ErrorRecord.SetInvocationInfo(new InvocationInfo(_invocationInfo.MyCommand, errorPosition));
}
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructors a ParameterBindingException using serialized data.
/// </summary>
///
/// <param name="info">
/// serialization information
/// </param>
///
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_message = info.GetString("ParameterBindingException_Message");
_parameterName = info.GetString("ParameterName");
_line = info.GetInt64("Line");
_offset = info.GetInt64("Offset");
}
/// <summary>
/// Serializes the exception
/// </summary>
///
/// <param name="info">
/// serialization information
/// </param>
///
/// <param name="context">
/// streaming context
/// </param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException("info");
}
base.GetObjectData(info, context);
info.AddValue("ParameterBindingException_Message", this.Message);
info.AddValue("ParameterName", _parameterName);
info.AddValue("Line", _line);
info.AddValue("Offset", _offset);
}
#endregion serialization
#region Do Not Use
/// <summary>
/// Constructs a ParameterBindingException.
/// </summary>
///
/// <remarks>
/// DO NOT USE!!!
/// </remarks>
public ParameterBindingException() : base() {; }
/// <summary>
/// Constructors a ParameterBindingException
/// </summary>
///
/// <param name="message">
/// Message to be included in exception.
/// </param>
///
/// <remarks>
/// DO NOT USE!!!
/// </remarks>
public ParameterBindingException(string message) : base(message) { _message = message; }
/// <summary>
/// Constructs a ParameterBindingException
/// </summary>
///
/// <param name="message">
/// Message to be included in the exception.
/// </param>
///
/// <param name="innerException">
/// exception that led to this exception
/// </param>
///
/// <remarks>
/// DO NOT USE!!!
/// </remarks>
public ParameterBindingException(
string message,
Exception innerException)
: base(message, innerException)
{ _message = message; }
#endregion Do Not Use
#endregion Constructors
#region Properties
/// <summary>
/// Gets the message for the exception
/// </summary>
public override string Message
{
get { return _message ?? (_message = BuildMessage()); }
}
private string _message;
/// <summary>
/// Gets the name of the parameter that the parameter binding
/// error was encountered on.
/// </summary>
public string ParameterName
{
get
{
return _parameterName;
}
}
private string _parameterName = String.Empty;
/// <summary>
/// Gets the type the parameter is expecting.
/// </summary>
public Type ParameterType
{
get
{
return _parameterType;
}
}
private Type _parameterType;
/// <summary>
/// Gets the Type that was specified as the parameter value
/// </summary>
public Type TypeSpecified
{
get
{
return _typeSpecified;
}
}
private Type _typeSpecified;
/// <summary>
/// Gets the errorId of this ParameterBindingException
/// </summary>
public string ErrorId
{
get
{
return _errorId;
}
}
private string _errorId;
/// <summary>
/// Gets the line in the script at which the error occurred.
/// </summary>
public Int64 Line
{
get
{
return _line;
}
}
private Int64 _line = Int64.MinValue;
/// <summary>
/// Gets the offset on the line in the script at which the error occurred.
/// </summary>
public Int64 Offset
{
get
{
return _offset;
}
}
private Int64 _offset = Int64.MinValue;
/// <summary>
/// Gets the invocation information about the command.
/// </summary>
public InvocationInfo CommandInvocation
{
get
{
return _invocationInfo;
}
}
private InvocationInfo _invocationInfo;
#endregion Properties
#region private
private string _resourceString;
private object[] _args = new object[0];
private string _commandName;
private string BuildMessage()
{
object[] messageArgs = new object[0];
if (_args != null)
{
messageArgs = new object[_args.Length + 6];
messageArgs[0] = _commandName;
messageArgs[1] = _parameterName;
messageArgs[2] = _parameterType;
messageArgs[3] = _typeSpecified;
messageArgs[4] = _line;
messageArgs[5] = _offset;
_args.CopyTo(messageArgs, 6);
}
string result = String.Empty;
if (!String.IsNullOrEmpty(_resourceString))
{
result = StringUtil.Format(_resourceString, messageArgs);
}
return result;
}
#endregion Private
}
[Serializable]
internal class ParameterBindingValidationException : ParameterBindingException
{
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingValidationException
/// </summary>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingValidationException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
/// <summary>
/// Constructs a ParameterBindingValidationException
/// </summary>
///
/// <param name="innerException">
/// The inner exception.
/// </param>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceBaseName"/> or <paramref name="errorIdAndResourceId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingValidationException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
innerException,
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
ValidationMetadataException validationException = innerException as ValidationMetadataException;
if (validationException != null && validationException.SwallowException)
{
_swallowException = true;
}
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructs a ParameterBindingValidationException from serialized data
/// </summary>
///
/// <param name="info">
/// serialization information
/// </param>
///
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingValidationException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion serialization
#region Property
/// <summary>
/// Make the positional binding ignore this validation exception when it's set to true.
/// </summary>
///
/// <remarks>
/// This property is only used internally in the positional binding phase
/// </remarks>
internal bool SwallowException
{
get { return _swallowException; }
}
private readonly bool _swallowException = false;
#endregion Property
}
[Serializable]
internal class ParameterBindingArgumentTransformationException : ParameterBindingException
{
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingArgumentTransformationException
/// </summary>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingArgumentTransformationException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
/// <summary>
/// Constructs a ParameterBindingArgumentTransformationException
/// </summary>
///
/// <param name="innerException">
/// The inner exception.
/// </param>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingArgumentTransformationException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
innerException,
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructs a ParameterBindingArgumentTransformationException using serialized data
/// </summary>
///
/// <param name="info">
/// serialization information
/// </param>
///
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingArgumentTransformationException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion serialization
}
[Serializable]
internal class ParameterBindingParameterDefaultValueException : ParameterBindingException
{
#region Preferred constructors
/// <summary>
/// Constructs a ParameterBindingParameterDefaultValueException
/// </summary>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingParameterDefaultValueException(
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
/// <summary>
/// Constructs a ParameterBindingParameterDefaultValueException
/// </summary>
///
/// <param name="innerException">
/// The inner exception.
/// </param>
///
/// <param name="errorCategory">
/// The category for the error.
/// </param>
///
/// <param name="invocationInfo">
/// The information about the command that encountered the error.
///
/// InvocationInfo.MyCommand.Name == {0}
/// </param>
///
/// <param name="errorPosition">
/// The position for the command or parameter that caused the error.
///
/// token.LineNumber == {4}
/// token.OffsetInLine == {5}
/// </param>
///
/// <param name="parameterName">
/// The parameter on which binding caused the error.
///
/// parameterName == {1}
/// </param>
///
/// <param name="parameterType">
/// The Type the parameter was expecting.
///
/// parameterType == {2}
/// </param>
///
/// <param name="typeSpecified">
/// The Type that was attempted to be bound to the parameter.
///
/// typeSpecified == {3}
/// </param>
///
/// <param name="resourceString">
/// The format string for the exception message.
/// </param>
///
/// <param name="errorId">
/// The error ID.
/// </param>
///
/// <param name="args">
/// Additional arguments to pass to the format string.
///
/// starts at {6}
/// </param>
///
/// <exception cref="ArgumentNullException">
/// If <paramref name="invocationInfo"/> is null.
/// </exception>
///
/// <exception cref="ArgumentException">
/// If <paramref name="resourceString"/> or <paramref name="errorId"/>
/// is null or empty.
/// </exception>
///
internal ParameterBindingParameterDefaultValueException(
Exception innerException,
ErrorCategory errorCategory,
InvocationInfo invocationInfo,
IScriptExtent errorPosition,
string parameterName,
Type parameterType,
Type typeSpecified,
string resourceString,
string errorId,
params object[] args)
: base(
innerException,
errorCategory,
invocationInfo,
errorPosition,
parameterName,
parameterType,
typeSpecified,
resourceString,
errorId,
args)
{
}
#endregion Preferred constructors
#region serialization
/// <summary>
/// Constructs a ParameterBindingParameterDefaultValueException using serialized data
/// </summary>
///
/// <param name="info">
/// serialization information
/// </param>
///
/// <param name="context">
/// streaming context
/// </param>
protected ParameterBindingParameterDefaultValueException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion serialization
}
} // namespace System.Management.Automation
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Controls.dll
// Description: The Windows Forms user interface controls like the map, legend, toolbox, ribbon and others.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 4/4/2009 11:52:50 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Serialization;
using DotSpatial.Symbology;
namespace DotSpatial.Controls
{
public class MapGroup : Group, IMapGroup
{
/// <summary>
/// Overrides the base CreateGroup method to ensure that new groups are GeoGroups.
/// </summary>
protected override void OnCreateGroup()
{
new MapGroup(Layers, ParentMapFrame, ProgressHandler) {LegendText = "New Group"};
}
#region Nested type: MapLayerEnumerator
/// <summary>
/// Transforms an IMapLayer enumerator into an ILayer Enumerator
/// </summary>
private class MapLayerEnumerator : IEnumerator<ILayer>
{
private readonly IEnumerator<IMapLayer> _enumerator;
/// <summary>
/// Creates a new instance of the MapLayerEnumerator
/// </summary>
/// <param name="subEnumerator"></param>
public MapLayerEnumerator(IEnumerator<IMapLayer> subEnumerator)
{
_enumerator = subEnumerator;
}
#region IEnumerator<ILayer> Members
/// <inheritdoc />
public ILayer Current
{
get { return _enumerator.Current; }
}
/// <inheritdoc />
public void Dispose()
{
_enumerator.Dispose();
}
object IEnumerator.Current
{
get { return _enumerator.Current; }
}
/// <inheritdoc />
public bool MoveNext()
{
return _enumerator.MoveNext();
}
/// <inheritdoc />
public void Reset()
{
_enumerator.Reset();
}
#endregion
}
#endregion
#region Private Variables
private IMapLayerCollection _layers;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of GeoGroup
/// </summary>
public MapGroup()
{
Layers = new MapLayerCollection();
}
/// <summary>
/// Creates a new group for the specified map. This will place the group at the root level on the MapFrame.
/// </summary>
/// <param name="map">The map to add this group to.</param>
/// <param name="name">The name to appear in the legend text.</param>
public MapGroup(IMap map, string name)
: base(map.MapFrame, map.ProgressHandler)
{
Layers = new MapLayerCollection(map.MapFrame, this, map.ProgressHandler);
base.LegendText = name;
map.Layers.Add(this);
}
/// <summary>
/// Creates a group that sits in a layer list and uses the specified progress handler
/// </summary>
/// <param name="container">the layer list</param>
/// <param name="frame"></param>
/// <param name="progressHandler">the progress handler</param>
public MapGroup(ICollection<IMapLayer> container, IMapFrame frame, IProgressHandler progressHandler)
: base(frame, progressHandler)
{
Layers = new MapLayerCollection(frame, this, progressHandler);
container.Add(this);
}
#endregion
#region Methods
/// <inheritdoc />
public override int IndexOf(ILayer item)
{
IMapLayer ml = item as IMapLayer;
if (ml != null)
{
return _layers.IndexOf(ml);
}
return -1;
}
/// <inheritdoc />
public override void Add(ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
if (ml != null)
{
_layers.Add(ml);
}
}
/// <inheritdoc />
public override bool Remove(ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
return ml != null && _layers.Remove(ml);
}
/// <inheritdoc />
public override void RemoveAt(int index)
{
_layers.RemoveAt(index);
}
/// <inheritdoc />
public override void Insert(int index, ILayer layer)
{
IMapLayer ml = layer as IMapLayer;
if (ml != null)
{
_layers.Insert(index, ml);
}
}
/// <inheritdoc />
public override ILayer this[int index]
{
get
{
return _layers[index];
}
set
{
IMapLayer ml = value as IMapLayer;
_layers[index] = ml;
}
}
/// <inheritdoc />
public override void Clear()
{
_layers.Clear();
}
/// <inheritdoc />
public override bool Contains(ILayer item)
{
IMapLayer ml = item as IMapLayer;
return ml != null && _layers.Contains(ml);
}
/// <inheritdoc />
public override void CopyTo(ILayer[] array, int arrayIndex)
{
for (int i = 0; i < Layers.Count; i++)
{
array[i + arrayIndex] = _layers[i];
}
}
/// <inheritdoc />
public override int Count
{
get { return _layers.Count; }
}
/// <inheritdoc />
public override bool IsReadOnly
{
get { return _layers.IsReadOnly; }
}
/// <inheritdoc />
public override void SuspendEvents()
{
_layers.SuspendEvents();
}
/// <inheritdoc />
public override void ResumeEvents()
{
_layers.ResumeEvents();
}
/// <inheritdoc />
public override bool EventsSuspended
{
get { return _layers.EventsSuspended; }
}
/// <inheritdoc />
public override IEnumerator<ILayer> GetEnumerator()
{
return new MapLayerEnumerator(_layers.GetEnumerator());
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return _layers.GetEnumerator();
}
/// <summary>
/// This draws content from the specified geographic regions onto the specified graphics
/// object specified by MapArgs.
/// </summary>
public void DrawRegions(MapArgs args, List<Extent> regions)
{
if (Layers == null) return;
foreach (IMapLayer layer in Layers)
{
if (!layer.IsVisible) continue;
if (layer.UseDynamicVisibility)
{
if (layer.DynamicVisibilityMode == DynamicVisibilityMode.ZoomedIn)
{
if (MapFrame.ViewExtents.Width > layer.DynamicVisibilityWidth)
{
continue; // skip the geoLayer if we are zoomed out too far.
}
}
else
{
if (MapFrame.ViewExtents.Width < layer.DynamicVisibilityWidth)
{
continue; // skip the geoLayer if we are zoomed in too far.
}
}
}
layer.DrawRegions(args, regions);
}
}
#endregion
#region Properties
/// <summary>
/// Gets the collection of Geographic drawing layers.
/// </summary>
/// <summary>
/// Gets or sets the layers
/// </summary>
[Serialize("Layers")]
public new IMapLayerCollection Layers
{
get { return _layers; }
set
{
if (Layers != null)
{
Ignore_Layer_Events(_layers);
}
Handle_Layer_Events(value);
_layers = value;
//set the MapFrame property
if (ParentMapFrame != null)
{
_layers.MapFrame = ParentMapFrame;
}
}
}
/// <inheritdoc />
public override IFrame MapFrame
{
get { return base.MapFrame; }
set
{
base.MapFrame = value;
if (_layers != null)
{
IMapFrame newValue = value as IMapFrame;
if (newValue != null && _layers.MapFrame == null)
{
_layers.MapFrame = newValue;
}
}
}
}
/// <summary>
/// Gets the layers cast as ILayer without any information about the actual drawing methods.
/// This is useful for handling methods that my come from various types of maps.
/// </summary>
/// <returns>An enumerable collection of ILayer</returns>
public override IList<ILayer> GetLayers()
{
return _layers.Cast<ILayer>().ToList();
}
/// <summary>
/// Gets the MapFrame that this group ultimately belongs to. This may not
/// be the immediate parent of this group.
/// </summary>
public IMapFrame ParentMapFrame
{
get { return MapFrame as IMapFrame; }
set { MapFrame = value; }
}
/// <summary>
/// This is a different view of the layers cast as legend items. This allows
/// easier cycling in recursive legend code.
/// </summary>
public override IEnumerable<ILegendItem> LegendItems
{
get
{
// Keep cast for 3.5 framework
return _layers.Cast<ILegendItem>();
}
}
#endregion
}
}
| |
using Lucene.Net.Documents;
using Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Lucene.Net.Codecs.Lucene40
{
/*
* 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 AtomicReader = Lucene.Net.Index.AtomicReader;
using IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IIndexableField = Lucene.Net.Index.IIndexableField;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexOutput = Lucene.Net.Store.IndexOutput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using MergeState = Lucene.Net.Index.MergeState;
using SegmentReader = Lucene.Net.Index.SegmentReader;
/// <summary>
/// Class responsible for writing stored document fields.
/// <para/>
/// It uses <segment>.fdt and <segment>.fdx; files.
/// <para/>
/// @lucene.experimental
/// </summary>
/// <seealso cref="Lucene40StoredFieldsFormat"/>
public sealed class Lucene40StoredFieldsWriter : StoredFieldsWriter
{
// NOTE: bit 0 is free here! You can steal it!
internal static readonly int FIELD_IS_BINARY = 1 << 1;
// the old bit 1 << 2 was compressed, is now left out
private const int _NUMERIC_BIT_SHIFT = 3;
internal static readonly int FIELD_IS_NUMERIC_MASK = 0x07 << _NUMERIC_BIT_SHIFT;
internal const int FIELD_IS_NUMERIC_INT = 1 << _NUMERIC_BIT_SHIFT;
internal const int FIELD_IS_NUMERIC_LONG = 2 << _NUMERIC_BIT_SHIFT;
internal const int FIELD_IS_NUMERIC_FLOAT = 3 << _NUMERIC_BIT_SHIFT;
internal const int FIELD_IS_NUMERIC_DOUBLE = 4 << _NUMERIC_BIT_SHIFT;
// the next possible bits are: 1 << 6; 1 << 7
// currently unused: static final int FIELD_IS_NUMERIC_SHORT = 5 << _NUMERIC_BIT_SHIFT;
// currently unused: static final int FIELD_IS_NUMERIC_BYTE = 6 << _NUMERIC_BIT_SHIFT;
internal const string CODEC_NAME_IDX = "Lucene40StoredFieldsIndex";
internal const string CODEC_NAME_DAT = "Lucene40StoredFieldsData";
internal const int VERSION_START = 0;
internal const int VERSION_CURRENT = VERSION_START;
internal static readonly long HEADER_LENGTH_IDX = CodecUtil.HeaderLength(CODEC_NAME_IDX);
internal static readonly long HEADER_LENGTH_DAT = CodecUtil.HeaderLength(CODEC_NAME_DAT);
/// <summary>
/// Extension of stored fields file. </summary>
public const string FIELDS_EXTENSION = "fdt";
/// <summary>
/// Extension of stored fields index file. </summary>
public const string FIELDS_INDEX_EXTENSION = "fdx";
private readonly Directory directory;
private readonly string segment;
private IndexOutput fieldsStream;
private IndexOutput indexStream;
/// <summary>
/// Sole constructor. </summary>
public Lucene40StoredFieldsWriter(Directory directory, string segment, IOContext context)
{
Debug.Assert(directory != null);
this.directory = directory;
this.segment = segment;
bool success = false;
try
{
fieldsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", FIELDS_EXTENSION), context);
indexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", FIELDS_INDEX_EXTENSION), context);
CodecUtil.WriteHeader(fieldsStream, CODEC_NAME_DAT, VERSION_CURRENT);
CodecUtil.WriteHeader(indexStream, CODEC_NAME_IDX, VERSION_CURRENT);
Debug.Assert(HEADER_LENGTH_DAT == fieldsStream.GetFilePointer());
Debug.Assert(HEADER_LENGTH_IDX == indexStream.GetFilePointer());
success = true;
}
finally
{
if (!success)
{
Abort();
}
}
}
// Writes the contents of buffer into the fields stream
// and adds a new entry for this document into the index
// stream. this assumes the buffer was already written
// in the correct fields format.
public override void StartDocument(int numStoredFields)
{
indexStream.WriteInt64(fieldsStream.GetFilePointer());
fieldsStream.WriteVInt32(numStoredFields);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Dispose(fieldsStream, indexStream);
}
finally
{
fieldsStream = indexStream = null;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Abort()
{
try
{
Dispose();
}
catch (Exception)
{
}
IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, "", FIELDS_EXTENSION), IndexFileNames.SegmentFileName(segment, "", FIELDS_INDEX_EXTENSION));
}
public override void WriteField(FieldInfo info, IIndexableField field)
{
fieldsStream.WriteVInt32(info.Number);
int bits = 0;
BytesRef bytes;
string @string;
// TODO: maybe a field should serialize itself?
// this way we don't bake into indexer all these
// specific encodings for different fields? and apps
// can customize...
// LUCENENET specific - To avoid boxing/unboxing, we don't
// call GetNumericValue(). Instead, we check the field.NumericType and then
// call the appropriate conversion method.
if (field.NumericType != NumericFieldType.NONE)
{
switch (field.NumericType)
{
case NumericFieldType.BYTE:
case NumericFieldType.INT16:
case NumericFieldType.INT32:
bits |= FIELD_IS_NUMERIC_INT;
break;
case NumericFieldType.INT64:
bits |= FIELD_IS_NUMERIC_LONG;
break;
case NumericFieldType.SINGLE:
bits |= FIELD_IS_NUMERIC_FLOAT;
break;
case NumericFieldType.DOUBLE:
bits |= FIELD_IS_NUMERIC_DOUBLE;
break;
default:
throw new System.ArgumentException("cannot store numeric type " + field.NumericType);
}
@string = null;
bytes = null;
}
else
{
bytes = field.GetBinaryValue();
if (bytes != null)
{
bits |= FIELD_IS_BINARY;
@string = null;
}
else
{
@string = field.GetStringValue();
if (@string == null)
{
throw new System.ArgumentException("field " + field.Name + " is stored but does not have binaryValue, stringValue nor numericValue");
}
}
}
fieldsStream.WriteByte((byte)(sbyte)bits);
if (bytes != null)
{
fieldsStream.WriteVInt32(bytes.Length);
fieldsStream.WriteBytes(bytes.Bytes, bytes.Offset, bytes.Length);
}
else if (@string != null)
{
fieldsStream.WriteString(field.GetStringValue());
}
else
{
switch (field.NumericType)
{
case NumericFieldType.BYTE:
case NumericFieldType.INT16:
case NumericFieldType.INT32:
fieldsStream.WriteInt32(field.GetInt32Value().Value);
break;
case NumericFieldType.INT64:
fieldsStream.WriteInt64(field.GetInt64Value().Value);
break;
case NumericFieldType.SINGLE:
fieldsStream.WriteInt32(Number.SingleToInt32Bits(field.GetSingleValue().Value));
break;
case NumericFieldType.DOUBLE:
fieldsStream.WriteInt64(BitConverter.DoubleToInt64Bits(field.GetDoubleValue().Value));
break;
default:
throw new InvalidOperationException("Cannot get here");
}
}
}
/// <summary>
/// Bulk write a contiguous series of documents. The
/// <paramref name="lengths"/> array is the length (in bytes) of each raw
/// document. The <paramref name="stream"/> <see cref="IndexInput"/> is the
/// fieldsStream from which we should bulk-copy all
/// bytes.
/// </summary>
public void AddRawDocuments(IndexInput stream, int[] lengths, int numDocs)
{
long position = fieldsStream.GetFilePointer();
long start = position;
for (int i = 0; i < numDocs; i++)
{
indexStream.WriteInt64(position);
position += lengths[i];
}
fieldsStream.CopyBytes(stream, position - start);
Debug.Assert(fieldsStream.GetFilePointer() == position);
}
public override void Finish(FieldInfos fis, int numDocs)
{
if (HEADER_LENGTH_IDX + ((long)numDocs) * 8 != indexStream.GetFilePointer())
// this is most likely a bug in Sun JRE 1.6.0_04/_05;
// we detect that the bug has struck, here, and
// throw an exception to prevent the corruption from
// entering the index. See LUCENE-1282 for
// details.
{
throw new Exception("fdx size mismatch: docCount is " + numDocs + " but fdx file size is " + indexStream.GetFilePointer() + " file=" + indexStream.ToString() + "; now aborting this merge to prevent index corruption");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override int Merge(MergeState mergeState)
{
int docCount = 0;
// Used for bulk-reading raw bytes for stored fields
int[] rawDocLengths = new int[MAX_RAW_MERGE_DOCS];
int idx = 0;
foreach (AtomicReader reader in mergeState.Readers)
{
SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++];
Lucene40StoredFieldsReader matchingFieldsReader = null;
if (matchingSegmentReader != null)
{
StoredFieldsReader fieldsReader = matchingSegmentReader.FieldsReader;
// we can only bulk-copy if the matching reader is also a Lucene40FieldsReader
if (fieldsReader != null && fieldsReader is Lucene40StoredFieldsReader)
{
matchingFieldsReader = (Lucene40StoredFieldsReader)fieldsReader;
}
}
if (reader.LiveDocs != null)
{
docCount += CopyFieldsWithDeletions(mergeState, reader, matchingFieldsReader, rawDocLengths);
}
else
{
docCount += CopyFieldsNoDeletions(mergeState, reader, matchingFieldsReader, rawDocLengths);
}
}
Finish(mergeState.FieldInfos, docCount);
return docCount;
}
/// <summary>
/// Maximum number of contiguous documents to bulk-copy
/// when merging stored fields.
/// </summary>
private const int MAX_RAW_MERGE_DOCS = 4192;
private int CopyFieldsWithDeletions(MergeState mergeState, AtomicReader reader, Lucene40StoredFieldsReader matchingFieldsReader, int[] rawDocLengths)
{
int docCount = 0;
int maxDoc = reader.MaxDoc;
IBits liveDocs = reader.LiveDocs;
Debug.Assert(liveDocs != null);
if (matchingFieldsReader != null)
{
// We can bulk-copy because the fieldInfos are "congruent"
for (int j = 0; j < maxDoc; )
{
if (!liveDocs.Get(j))
{
// skip deleted docs
++j;
continue;
}
// We can optimize this case (doing a bulk byte copy) since the field
// numbers are identical
int start = j, numDocs = 0;
do
{
j++;
numDocs++;
if (j >= maxDoc)
{
break;
}
if (!liveDocs.Get(j))
{
j++;
break;
}
} while (numDocs < MAX_RAW_MERGE_DOCS);
IndexInput stream = matchingFieldsReader.RawDocs(rawDocLengths, start, numDocs);
AddRawDocuments(stream, rawDocLengths, numDocs);
docCount += numDocs;
mergeState.CheckAbort.Work(300 * numDocs);
}
}
else
{
for (int j = 0; j < maxDoc; j++)
{
if (!liveDocs.Get(j))
{
// skip deleted docs
continue;
}
// TODO: this could be more efficient using
// FieldVisitor instead of loading/writing entire
// doc; ie we just have to renumber the field number
// on the fly?
// NOTE: it's very important to first assign to doc then pass it to
// fieldsWriter.addDocument; see LUCENE-1282
Document doc = reader.Document(j);
AddDocument(doc, mergeState.FieldInfos);
docCount++;
mergeState.CheckAbort.Work(300);
}
}
return docCount;
}
private int CopyFieldsNoDeletions(MergeState mergeState, AtomicReader reader, Lucene40StoredFieldsReader matchingFieldsReader, int[] rawDocLengths)
{
int maxDoc = reader.MaxDoc;
int docCount = 0;
if (matchingFieldsReader != null)
{
// We can bulk-copy because the fieldInfos are "congruent"
while (docCount < maxDoc)
{
int len = Math.Min(MAX_RAW_MERGE_DOCS, maxDoc - docCount);
IndexInput stream = matchingFieldsReader.RawDocs(rawDocLengths, docCount, len);
AddRawDocuments(stream, rawDocLengths, len);
docCount += len;
mergeState.CheckAbort.Work(300 * len);
}
}
else
{
for (; docCount < maxDoc; docCount++)
{
// NOTE: it's very important to first assign to doc then pass it to
// fieldsWriter.addDocument; see LUCENE-1282
Document doc = reader.Document(docCount);
AddDocument(doc, mergeState.FieldInfos);
mergeState.CheckAbort.Work(300);
}
}
return docCount;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PDBLambdaTests : CSharpPDBTestBase
{
[WorkItem(539898, "DevDiv")]
[Fact]
public void SequencePoints_Body()
{
var source = @"
using System;
delegate void D();
class C
{
public static void Main()
{
D d = () => Console.Write(1);
d();
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""C"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""13"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""23"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""38"" document=""0"" />
<entry offset=""0x21"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""13"" document=""0"" />
<entry offset=""0x28"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x29"">
<namespace name=""System"" />
<local name=""d"" il_index=""0"" il_start=""0x0"" il_end=""0x29"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c"" name=""<Main>b__0_0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""8"" startColumn=""21"" endLine=""8"" endColumn=""37"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact, WorkItem(543479, "DevDiv")]
public void Nested()
{
var source = @"
using System;
class Test
{
public static int Main()
{
if (M(1) != 10)
return 1;
return 0;
}
static public int M(int p)
{
Func<int, int> f1 = delegate(int x)
{
int q = 2;
Func<int, int> f2 = (y) =>
{
return p + q + x + y;
};
return f2(3);
};
return f1(4);
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugExe);
c.VerifyPdb(@"
<symbols>
<entryPoint declaringType=""Test"" methodName=""Main"" />
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""12"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""10"" endLine=""7"" endColumn=""25"" document=""0"" />
<entry offset=""0xf"" hidden=""true"" document=""0"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""22"" document=""0"" />
<entry offset=""0x16"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""0"" />
<entry offset=""0x1a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Test"" name=""M"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""0"" offset=""26"" />
<slot kind=""temp"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""0"" />
<closure offset=""56"" />
<lambda offset=""56"" closure=""0"" />
<lambda offset=""136"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
<entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""22"" endColumn=""11"" document=""0"" />
<entry offset=""0x1a"" startLine=""23"" startColumn=""9"" endLine=""23"" endColumn=""22"" document=""0"" />
<entry offset=""0x24"" startLine=""24"" startColumn=""5"" endLine=""24"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x26"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
<local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c__DisplayClass1_0"" name=""<M>b__0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""56"" />
<slot kind=""0"" offset=""110"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" />
<entry offset=""0x14"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""23"" document=""0"" />
<entry offset=""0x1b"" startLine=""17"" startColumn=""13"" endLine=""20"" endColumn=""15"" document=""0"" />
<entry offset=""0x28"" startLine=""21"" startColumn=""13"" endLine=""21"" endColumn=""26"" document=""0"" />
<entry offset=""0x32"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x34"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x34"" attributes=""0"" />
<local name=""f2"" il_index=""1"" il_start=""0x0"" il_end=""0x34"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c__DisplayClass1_1"" name=""<M>b__1"" parameterNames=""y"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""14"" document=""0"" />
<entry offset=""0x1"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""38"" document=""0"" />
<entry offset=""0x1f"" startLine=""20"" startColumn=""13"" endLine=""20"" endColumn=""14"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact, WorkItem(543479, "DevDiv")]
public void InitialSequencePoints()
{
var source = @"
class Test
{
void Foo(int p)
{
System.Func<int> f1 = () => p;
f1();
}
}
";
// Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies.
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Foo"" parameterNames=""p"">
<customDebugInfo>
<using>
<namespace usingCount=""0"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""0"" offset=""28"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""39"" closure=""0"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""5"" startColumn=""5"" endLine=""5"" endColumn=""6"" document=""0"" />
<entry offset=""0xd"" startLine=""6"" startColumn=""9"" endLine=""6"" endColumn=""39"" document=""0"" />
<entry offset=""0x1a"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""14"" document=""0"" />
<entry offset=""0x21"" startLine=""8"" startColumn=""5"" endLine=""8"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x22"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
<local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c__DisplayClass0_0"" name=""<Foo>b__0"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Foo"" parameterNames=""p"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""37"" endLine=""6"" endColumn=""38"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact, WorkItem(543479, "DevDiv")]
public void Nested_InitialSequencePoints()
{
var source = @"
using System;
class Test
{
public static int Main()
{
if (M(1) != 10) // can't step into M() at all
return 1;
return 0;
}
static public int M(int p)
{
Func<int, int> f1 = delegate(int x)
{
int q = 2;
Func<int, int> f2 = (y) => { return p + q + x + y; };
return f2(3);
};
return f1(4);
}
}
";
// Specifically note the sequence points at 0x0 in Test.Main, Test.M, and the lambda bodies.
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""Test"" name=""Main"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""1"" offset=""11"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""7"" startColumn=""9"" endLine=""7"" endColumn=""24"" document=""0"" />
<entry offset=""0xf"" hidden=""true"" document=""0"" />
<entry offset=""0x12"" startLine=""8"" startColumn=""13"" endLine=""8"" endColumn=""22"" document=""0"" />
<entry offset=""0x16"" startLine=""9"" startColumn=""9"" endLine=""9"" endColumn=""18"" document=""0"" />
<entry offset=""0x1a"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x1c"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""Test"" name=""M"" parameterNames=""p"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""0"" offset=""26"" />
<slot kind=""temp"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""0"" />
<closure offset=""56"" />
<lambda offset=""56"" closure=""0"" />
<lambda offset=""122"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
<entry offset=""0xd"" startLine=""14"" startColumn=""9"" endLine=""19"" endColumn=""11"" document=""0"" />
<entry offset=""0x1a"" startLine=""20"" startColumn=""9"" endLine=""20"" endColumn=""22"" document=""0"" />
<entry offset=""0x24"" startLine=""21"" startColumn=""5"" endLine=""21"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x26"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
<local name=""f1"" il_index=""1"" il_start=""0x0"" il_end=""0x26"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c__DisplayClass1_0"" name=""<M>b__0"" parameterNames=""x"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""56"" />
<slot kind=""0"" offset=""110"" />
<slot kind=""temp"" />
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""10"" document=""0"" />
<entry offset=""0x14"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""23"" document=""0"" />
<entry offset=""0x1b"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""66"" document=""0"" />
<entry offset=""0x28"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""26"" document=""0"" />
<entry offset=""0x32"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x34"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x34"" attributes=""0"" />
<local name=""f2"" il_index=""1"" il_start=""0x0"" il_end=""0x34"" attributes=""0"" />
</scope>
</method>
<method containingType=""Test+<>c__DisplayClass1_1"" name=""<M>b__1"" parameterNames=""y"">
<customDebugInfo>
<forward declaringType=""Test"" methodName=""Main"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""40"" endLine=""17"" endColumn=""41"" document=""0"" />
<entry offset=""0x1"" startLine=""17"" startColumn=""42"" endLine=""17"" endColumn=""63"" document=""0"" />
<entry offset=""0x1f"" startLine=""17"" startColumn=""64"" endLine=""17"" endColumn=""65"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void FieldAndPropertyInitializers()
{
var source = @"
using System;
class B
{
public B(Func<int> f) { }
}
class C : B
{
Func<int> FI = () => 1;
static Func<int> FS = () => 2;
Func<int> P { get; } = () => FS();
public C() : base(() => 3) {}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""B"" name="".ctor"" parameterNames=""f"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""0"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""0"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name=""get_P"">
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""19"" endLine=""13"" endColumn=""23"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C"" name="".ctor"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
<encLambdaMap>
<methodOrdinal>5</methodOrdinal>
<lambda offset=""-2"" />
<lambda offset=""-28"" />
<lambda offset=""-19"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""28"" document=""0"" />
<entry offset=""0x25"" startLine=""13"" startColumn=""28"" endLine=""13"" endColumn=""38"" document=""0"" />
<entry offset=""0x4a"" startLine=""14"" startColumn=""18"" endLine=""14"" endColumn=""31"" document=""0"" />
<entry offset=""0x70"" startLine=""14"" startColumn=""32"" endLine=""14"" endColumn=""33"" document=""0"" />
<entry offset=""0x71"" startLine=""14"" startColumn=""33"" endLine=""14"" endColumn=""34"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C"" name="".cctor"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
<encLambdaMap>
<methodOrdinal>6</methodOrdinal>
<lambda offset=""-1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""35"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__5_0"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""14"" startColumn=""29"" endLine=""14"" endColumn=""30"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__5_1"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""26"" endLine=""11"" endColumn=""27"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.ctor>b__5_2"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""34"" endLine=""13"" endColumn=""38"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<.cctor>b__6_0"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""33"" endLine=""12"" endColumn=""34"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ClosuresInCtor()
{
var source = @"
using System;
class B
{
public B(Func<int> f) { }
}
class C : B
{
Func<int> f, g, h;
public C(int a, int b) : base(() => a)
{
int c = 1;
f = () => b;
g = () => f();
h = () => c;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""B"" name="".ctor"" parameterNames=""f"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""6"" startColumn=""5"" endLine=""6"" endColumn=""26"" document=""0"" />
<entry offset=""0x7"" startLine=""6"" startColumn=""27"" endLine=""6"" endColumn=""28"" document=""0"" />
<entry offset=""0x8"" startLine=""6"" startColumn=""29"" endLine=""6"" endColumn=""30"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9"">
<namespace name=""System"" />
</scope>
</method>
<method containingType=""C"" name="".ctor"" parameterNames=""a, b"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
<encLocalSlotMap>
<slot kind=""30"" offset=""-1"" />
<slot kind=""30"" offset=""0"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>3</methodOrdinal>
<closure offset=""-1"" />
<closure offset=""0"" />
<lambda offset=""-2"" closure=""0"" />
<lambda offset=""41"" closure=""0"" />
<lambda offset=""63"" closure=""this"" />
<lambda offset=""87"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""30"" endLine=""13"" endColumn=""43"" document=""0"" />
<entry offset=""0x27"" startLine=""14"" startColumn=""5"" endLine=""14"" endColumn=""6"" document=""0"" />
<entry offset=""0x2d"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""19"" document=""0"" />
<entry offset=""0x34"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""21"" document=""0"" />
<entry offset=""0x46"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""23"" document=""0"" />
<entry offset=""0x58"" startLine=""18"" startColumn=""9"" endLine=""18"" endColumn=""21"" document=""0"" />
<entry offset=""0x6a"" startLine=""19"" startColumn=""5"" endLine=""19"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x6b"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x6b"" attributes=""0"" />
<scope startOffset=""0x27"" endOffset=""0x6a"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x27"" il_end=""0x6a"" attributes=""0"" />
</scope>
</scope>
</method>
<method containingType=""C"" name=""<.ctor>b__3_2"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""17"" startColumn=""19"" endLine=""17"" endColumn=""22"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass3_0"" name=""<.ctor>b__0"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""13"" startColumn=""41"" endLine=""13"" endColumn=""42"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass3_0"" name=""<.ctor>b__1"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""16"" startColumn=""19"" endLine=""16"" endColumn=""20"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c__DisplayClass3_1"" name=""<.ctor>b__3"">
<customDebugInfo>
<forward declaringType=""B"" methodName="".ctor"" parameterNames=""f"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""18"" startColumn=""19"" endLine=""18"" endColumn=""20"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Queries1()
{
var source = @"
using System.Linq;
class C
{
public void M()
{
int c = 1;
var x = from a in new[] { 1, 2, 3 }
let b = a + c
where b > 10
select b * 10;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""0"" offset=""35"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<closure offset=""0"" />
<lambda offset=""92"" closure=""0"" />
<lambda offset=""121"" />
<lambda offset=""152"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x6"" startLine=""8"" startColumn=""9"" endLine=""8"" endColumn=""19"" document=""0"" />
<entry offset=""0xd"" startLine=""9"" startColumn=""9"" endLine=""12"" endColumn=""31"" document=""0"" />
<entry offset=""0x78"" startLine=""13"" startColumn=""5"" endLine=""13"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x79"">
<namespace name=""System.Linq"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x79"" attributes=""0"" />
<local name=""x"" il_index=""1"" il_start=""0x0"" il_end=""0x79"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c__DisplayClass0_0"" name=""<M>b__0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""17"" endLine=""10"" endColumn=""30"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<M>b__0_1"" parameterNames=""<>h__TransparentIdentifier0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""23"" endLine=""11"" endColumn=""29"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<M>b__0_2"" parameterNames=""<>h__TransparentIdentifier0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""M"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""12"" startColumn=""24"" endLine=""12"" endColumn=""30"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void Queries_GroupBy1()
{
var source = @"
using System.Linq;
class C
{
void F()
{
var result = from/*0*/ a in new[] { 1, 2, 3 }
join/*1*/ b in new[] { 5 } on a + 1 equals b - 1
group/*2*/ new { a, b = a + 5 } by new { c = a + 4 } into d
select/*3*/ d.Key;
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
c.VerifyPdb(@"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""0"" offset=""15"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>0</methodOrdinal>
<lambda offset=""109"" />
<lambda offset=""122"" />
<lambda offset=""79"" />
<lambda offset=""185"" />
<lambda offset=""161"" />
<lambda offset=""244"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""5"" endLine=""7"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""8"" startColumn=""9"" endLine=""11"" endColumn=""40"" document=""0"" />
<entry offset=""0xe6"" startLine=""12"" startColumn=""5"" endLine=""12"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0xe7"">
<namespace name=""System.Linq"" />
<local name=""result"" il_index=""0"" il_start=""0x0"" il_end=""0xe7"" attributes=""0"" />
</scope>
</method>
<method containingType=""C+<>c"" name=""<F>b__0_0"" parameterNames=""a"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""52"" endLine=""9"" endColumn=""57"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<F>b__0_1"" parameterNames=""b"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""65"" endLine=""9"" endColumn=""70"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<F>b__0_2"" parameterNames=""a, b"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""22"" endLine=""9"" endColumn=""70"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<F>b__0_3"" parameterNames=""<>h__TransparentIdentifier0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""57"" endLine=""10"" endColumn=""74"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<F>b__0_4"" parameterNames=""<>h__TransparentIdentifier0"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""33"" endLine=""10"" endColumn=""53"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C+<>c"" name=""<F>b__0_5"" parameterNames=""d"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""F"" />
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""34"" endLine=""11"" endColumn=""39"" document=""0"" />
</sequencePoints>
</method>
</methods>
</symbols>");
}
[Fact]
public void ForEachStatement_Array()
{
string source = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[] { 1 }) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
// note that the two closures have a different syntax offset
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""f"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""41"" />
<slot kind=""8"" offset=""41"" />
<slot kind=""30"" offset=""41"" />
<slot kind=""30"" offset=""108"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""41"" />
<closure offset=""108"" />
<lambda offset=""259"" closure=""0"" />
<lambda offset=""287"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""0"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""39"" document=""0"" />
<entry offset=""0xf"" hidden=""true"" document=""0"" />
<entry offset=""0x11"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x20"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
<entry offset=""0x26"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" />
<entry offset=""0x2d"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" />
<entry offset=""0x40"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x53"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
<entry offset=""0x54"" hidden=""true"" document=""0"" />
<entry offset=""0x58"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x5e"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x5f"">
<scope startOffset=""0x11"" endOffset=""0x54"">
<local name=""CS$<>8__locals0"" il_index=""2"" il_start=""0x11"" il_end=""0x54"" attributes=""0"" />
<scope startOffset=""0x20"" endOffset=""0x54"">
<local name=""CS$<>8__locals1"" il_index=""3"" il_start=""0x20"" il_end=""0x54"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForEachStatement_MultidimensionalArray()
{
string source = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new[,] { { 1 } }) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
// note that the two closures have a different syntax offset
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""f"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""41"" />
<slot kind=""7"" offset=""41"" />
<slot kind=""7"" offset=""41"" ordinal=""1"" />
<slot kind=""8"" offset=""41"" />
<slot kind=""8"" offset=""41"" ordinal=""1"" />
<slot kind=""30"" offset=""41"" />
<slot kind=""30"" offset=""113"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""41"" />
<closure offset=""113"" />
<lambda offset=""269"" closure=""0"" />
<lambda offset=""297"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""0"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""44"" document=""0"" />
<entry offset=""0x2b"" hidden=""true"" document=""0"" />
<entry offset=""0x36"" hidden=""true"" document=""0"" />
<entry offset=""0x38"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x4f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
<entry offset=""0x56"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" />
<entry offset=""0x5e"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" />
<entry offset=""0x72"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x86"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
<entry offset=""0x87"" hidden=""true"" document=""0"" />
<entry offset=""0x8d"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x92"" hidden=""true"" document=""0"" />
<entry offset=""0x96"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x9a"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x9b"">
<scope startOffset=""0x38"" endOffset=""0x87"">
<local name=""CS$<>8__locals0"" il_index=""5"" il_start=""0x38"" il_end=""0x87"" attributes=""0"" />
<scope startOffset=""0x4f"" endOffset=""0x87"">
<local name=""CS$<>8__locals1"" il_index=""6"" il_start=""0x4f"" il_end=""0x87"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForEachStatement_String()
{
string source = @"
using System;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in ""1"") // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
// note that the two closures have a different syntax offset
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""f"" />
<encLocalSlotMap>
<slot kind=""6"" offset=""41"" />
<slot kind=""8"" offset=""41"" />
<slot kind=""30"" offset=""41"" />
<slot kind=""30"" offset=""100"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""41"" />
<closure offset=""100"" />
<lambda offset=""245"" closure=""0"" />
<lambda offset=""273"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""16"" document=""0"" />
<entry offset=""0x2"" startLine=""10"" startColumn=""28"" endLine=""10"" endColumn=""31"" document=""0"" />
<entry offset=""0xa"" hidden=""true"" document=""0"" />
<entry offset=""0xc"" startLine=""10"" startColumn=""18"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0x1f"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
<entry offset=""0x25"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" />
<entry offset=""0x2c"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" />
<entry offset=""0x3f"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x52"" startLine=""16"" startColumn=""9"" endLine=""16"" endColumn=""10"" document=""0"" />
<entry offset=""0x53"" hidden=""true"" document=""0"" />
<entry offset=""0x57"" startLine=""10"" startColumn=""25"" endLine=""10"" endColumn=""27"" document=""0"" />
<entry offset=""0x60"" startLine=""17"" startColumn=""5"" endLine=""17"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x61"">
<scope startOffset=""0xc"" endOffset=""0x53"">
<local name=""CS$<>8__locals0"" il_index=""2"" il_start=""0xc"" il_end=""0x53"" attributes=""0"" />
<scope startOffset=""0x1f"" endOffset=""0x53"">
<local name=""CS$<>8__locals1"" il_index=""3"" il_start=""0x1f"" il_end=""0x53"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForEachStatement_Enumerable()
{
string source = @"
using System;
using System.Collections.Generic;
class C
{
void G(Func<int, int> f) {}
void F()
{
foreach (int x0 in new List<int>()) // Group #0
{ // Group #1
int x1 = 0;
G(a => x0);
G(a => x1);
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
// note that the two closures have a different syntax offset
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<forward declaringType=""C"" methodName=""G"" parameterNames=""f"" />
<encLocalSlotMap>
<slot kind=""5"" offset=""41"" />
<slot kind=""30"" offset=""41"" />
<slot kind=""30"" offset=""112"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""41"" />
<closure offset=""112"" />
<lambda offset=""268"" closure=""0"" />
<lambda offset=""296"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""10"" startColumn=""5"" endLine=""10"" endColumn=""6"" document=""0"" />
<entry offset=""0x1"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""16"" document=""0"" />
<entry offset=""0x2"" startLine=""11"" startColumn=""28"" endLine=""11"" endColumn=""43"" document=""0"" />
<entry offset=""0xd"" hidden=""true"" document=""0"" />
<entry offset=""0xf"" startLine=""11"" startColumn=""18"" endLine=""11"" endColumn=""24"" document=""0"" />
<entry offset=""0x22"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""10"" document=""0"" />
<entry offset=""0x28"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" />
<entry offset=""0x2f"" startLine=""15"" startColumn=""13"" endLine=""15"" endColumn=""24"" document=""0"" />
<entry offset=""0x42"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""24"" document=""0"" />
<entry offset=""0x55"" startLine=""17"" startColumn=""9"" endLine=""17"" endColumn=""10"" document=""0"" />
<entry offset=""0x56"" startLine=""11"" startColumn=""25"" endLine=""11"" endColumn=""27"" document=""0"" />
<entry offset=""0x61"" hidden=""true"" document=""0"" />
<entry offset=""0x70"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x71"">
<scope startOffset=""0xf"" endOffset=""0x56"">
<local name=""CS$<>8__locals0"" il_index=""1"" il_start=""0xf"" il_end=""0x56"" attributes=""0"" />
<scope startOffset=""0x22"" endOffset=""0x56"">
<local name=""CS$<>8__locals1"" il_index=""2"" il_start=""0x22"" il_end=""0x56"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void ForStatement1()
{
string source = @"
using System;
class C
{
bool G(Func<int, int> f) => true;
void F()
{
for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);)
{
int x2 = 0;
G(a => x2);
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
// note that the two closures have a different syntax offset
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""41"" />
<slot kind=""30"" offset=""102"" />
<slot kind=""1"" offset=""41"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>1</methodOrdinal>
<closure offset=""102"" />
<closure offset=""41"" />
<lambda offset=""149"" closure=""0"" />
<lambda offset=""73"" closure=""1"" />
<lambda offset=""87"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""0"" />
<entry offset=""0x7"" startLine=""10"" startColumn=""14"" endLine=""10"" endColumn=""24"" document=""0"" />
<entry offset=""0xe"" startLine=""10"" startColumn=""26"" endLine=""10"" endColumn=""32"" document=""0"" />
<entry offset=""0x15"" hidden=""true"" document=""0"" />
<entry offset=""0x17"" startLine=""11"" startColumn=""9"" endLine=""11"" endColumn=""10"" document=""0"" />
<entry offset=""0x1d"" startLine=""12"" startColumn=""13"" endLine=""12"" endColumn=""24"" document=""0"" />
<entry offset=""0x24"" startLine=""13"" startColumn=""13"" endLine=""13"" endColumn=""24"" document=""0"" />
<entry offset=""0x37"" startLine=""14"" startColumn=""9"" endLine=""14"" endColumn=""10"" document=""0"" />
<entry offset=""0x38"" startLine=""10"" startColumn=""34"" endLine=""10"" endColumn=""58"" document=""0"" />
<entry offset=""0x62"" hidden=""true"" document=""0"" />
<entry offset=""0x65"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x66"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x65"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x65"" attributes=""0"" />
<scope startOffset=""0x17"" endOffset=""0x38"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x17"" il_end=""0x38"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void SwitchStatement1()
{
var source = @"
using System;
class C
{
bool G(Func<int> f) => true;
int a = 1;
void F()
{
int x2 = 1;
G(() => x2);
switch (a)
{
case 1:
int x0 = 1;
G(() => x0);
break;
case 2:
int x1 = 1;
G(() => x1);
break;
}
}
}
";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""0"" />
<slot kind=""30"" offset=""86"" />
<slot kind=""1"" offset=""86"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>2</methodOrdinal>
<closure offset=""0"" />
<closure offset=""86"" />
<lambda offset=""48"" closure=""0"" />
<lambda offset=""183"" closure=""1"" />
<lambda offset=""289"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
<entry offset=""0x6"" startLine=""12"" startColumn=""9"" endLine=""12"" endColumn=""20"" document=""0"" />
<entry offset=""0xd"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""21"" document=""0"" />
<entry offset=""0x20"" startLine=""15"" startColumn=""9"" endLine=""15"" endColumn=""19"" document=""0"" />
<entry offset=""0x2d"" hidden=""true"" document=""0"" />
<entry offset=""0x39"" startLine=""18"" startColumn=""17"" endLine=""18"" endColumn=""28"" document=""0"" />
<entry offset=""0x40"" startLine=""19"" startColumn=""17"" endLine=""19"" endColumn=""29"" document=""0"" />
<entry offset=""0x53"" startLine=""20"" startColumn=""17"" endLine=""20"" endColumn=""23"" document=""0"" />
<entry offset=""0x55"" startLine=""23"" startColumn=""17"" endLine=""23"" endColumn=""28"" document=""0"" />
<entry offset=""0x5c"" startLine=""24"" startColumn=""17"" endLine=""24"" endColumn=""29"" document=""0"" />
<entry offset=""0x6f"" startLine=""25"" startColumn=""17"" endLine=""25"" endColumn=""23"" document=""0"" />
<entry offset=""0x71"" startLine=""27"" startColumn=""5"" endLine=""27"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x72"">
<namespace name=""System"" />
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x0"" il_end=""0x72"" attributes=""0"" />
<scope startOffset=""0x20"" endOffset=""0x71"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x20"" il_end=""0x71"" attributes=""0"" />
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[Fact]
public void UsingStatement1()
{
string source = @"
using System;
class C
{
static bool G<T>(Func<T> f) => true;
static int F(object a, object b) => 1;
static IDisposable D() => null;
static void F()
{
using (IDisposable x0 = D(), y0 = D())
{
int x1 = 1;
G(() => x0);
G(() => y0);
G(() => x1);
}
}
}";
var c = CreateCompilationWithMscorlibAndSystemCore(source, options: TestOptions.DebugDll);
c.VerifyDiagnostics();
// note that the two closures have a different syntax offset
c.VerifyPdb("C.F", @"
<symbols>
<methods>
<method containingType=""C"" name=""F"" parameterNames=""a, b"">
<sequencePoints>
<entry offset=""0x0"" startLine=""7"" startColumn=""41"" endLine=""7"" endColumn=""42"" document=""0"" />
</sequencePoints>
</method>
<method containingType=""C"" name=""F"">
<customDebugInfo>
<using>
<namespace usingCount=""1"" />
</using>
<encLocalSlotMap>
<slot kind=""30"" offset=""41"" />
<slot kind=""30"" offset=""89"" />
</encLocalSlotMap>
<encLambdaMap>
<methodOrdinal>3</methodOrdinal>
<closure offset=""41"" />
<closure offset=""89"" />
<lambda offset=""147"" closure=""0"" />
<lambda offset=""173"" closure=""0"" />
<lambda offset=""199"" closure=""1"" />
</encLambdaMap>
</customDebugInfo>
<sequencePoints>
<entry offset=""0x0"" startLine=""11"" startColumn=""5"" endLine=""11"" endColumn=""6"" document=""0"" />
<entry offset=""0x7"" startLine=""12"" startColumn=""16"" endLine=""12"" endColumn=""36"" document=""0"" />
<entry offset=""0x12"" startLine=""12"" startColumn=""38"" endLine=""12"" endColumn=""46"" document=""0"" />
<entry offset=""0x1d"" startLine=""13"" startColumn=""9"" endLine=""13"" endColumn=""10"" document=""0"" />
<entry offset=""0x23"" startLine=""14"" startColumn=""13"" endLine=""14"" endColumn=""24"" document=""0"" />
<entry offset=""0x2a"" startLine=""16"" startColumn=""13"" endLine=""16"" endColumn=""25"" document=""0"" />
<entry offset=""0x3c"" startLine=""17"" startColumn=""13"" endLine=""17"" endColumn=""25"" document=""0"" />
<entry offset=""0x4e"" startLine=""18"" startColumn=""13"" endLine=""18"" endColumn=""25"" document=""0"" />
<entry offset=""0x60"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""10"" document=""0"" />
<entry offset=""0x63"" hidden=""true"" document=""0"" />
<entry offset=""0x78"" hidden=""true"" document=""0"" />
<entry offset=""0x7a"" hidden=""true"" document=""0"" />
<entry offset=""0x8f"" startLine=""20"" startColumn=""5"" endLine=""20"" endColumn=""6"" document=""0"" />
</sequencePoints>
<scope startOffset=""0x0"" endOffset=""0x90"">
<namespace name=""System"" />
<scope startOffset=""0x1"" endOffset=""0x8f"">
<local name=""CS$<>8__locals0"" il_index=""0"" il_start=""0x1"" il_end=""0x8f"" attributes=""0"" />
<scope startOffset=""0x1d"" endOffset=""0x61"">
<local name=""CS$<>8__locals1"" il_index=""1"" il_start=""0x1d"" il_end=""0x61"" attributes=""0"" />
</scope>
</scope>
</scope>
</method>
</methods>
</symbols>
");
}
[WorkItem(749138, "DevDiv")]
[Fact]
public void SequencePoints_Delegate_Method()
{
var source = @"
using System;
class C
{
public static void Main()
{
Action a = null;
a = (Action)delegate { a = null; };
a();
}
}
";
// Verify the sequence point on the display class construction
var c = CompileAndVerify(source, options: TestOptions.DebugDll);
c.VerifyIL("C.Main", @"
{
// Code size 44 (0x2c)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
-IL_0000: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0005: stloc.0
-IL_0006: ldloc.0
IL_0007: ldnull
IL_0008: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_000d: ldloc.0
IL_000e: ldloc.0
IL_000f: ldftn ""void C.<>c__DisplayClass0_0.<Main>b__0()""
IL_0015: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001a: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_001f: ldloc.0
IL_0020: ldfld ""System.Action C.<>c__DisplayClass0_0.a""
IL_0025: callvirt ""void System.Action.Invoke()""
IL_002a: nop
-IL_002b: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(749138, "DevDiv")]
[Fact]
public void SequencePoints_Delegate_IfClause()
{
var source = @"
using System;
class C
{
public static void Main()
{
bool b = true;
if (b)
{
Action a = null;
a = (Action)delegate { a = null; };
a();
}
}
}
";
// Verify the sequence point on the display class construction
var c = CompileAndVerify(source, options: TestOptions.DebugDll);
c.VerifyIL("C.Main", @"
{
// Code size 53 (0x35)
.maxstack 3
.locals init (bool V_0, //b
bool V_1,
C.<>c__DisplayClass0_0 V_2) //CS$<>8__locals0
-IL_0000: nop
-IL_0001: ldc.i4.1
IL_0002: stloc.0
-IL_0003: ldloc.0
IL_0004: stloc.1
~IL_0005: ldloc.1
IL_0006: brfalse.s IL_0034
-IL_0008: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_000d: stloc.2
-IL_000e: ldloc.2
IL_000f: ldnull
IL_0010: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0015: ldloc.2
IL_0016: ldloc.2
IL_0017: ldftn ""void C.<>c__DisplayClass0_0.<Main>b__0()""
IL_001d: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_0022: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0027: ldloc.2
IL_0028: ldfld ""System.Action C.<>c__DisplayClass0_0.a""
IL_002d: callvirt ""void System.Action.Invoke()""
IL_0032: nop
-IL_0033: nop
-IL_0034: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(749138, "DevDiv")]
[Fact]
public void SequencePoints_Delegate_Block()
{
var source = @"
using System;
class C
{
public static void Main()
{
{
Action a = null;
a = (Action)delegate { a = null; };
a();
}
}
}
";
// Verify the sequence point on the display class construction
var c = CompileAndVerify(source, options: TestOptions.DebugDll);
c.VerifyIL("C.Main", @"
{
// Code size 46 (0x2e)
.maxstack 3
.locals init (C.<>c__DisplayClass0_0 V_0) //CS$<>8__locals0
-IL_0000: nop
-IL_0001: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_0006: stloc.0
-IL_0007: ldloc.0
IL_0008: ldnull
IL_0009: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_000e: ldloc.0
IL_000f: ldloc.0
IL_0010: ldftn ""void C.<>c__DisplayClass0_0.<Main>b__0()""
IL_0016: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001b: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0020: ldloc.0
IL_0021: ldfld ""System.Action C.<>c__DisplayClass0_0.a""
IL_0026: callvirt ""void System.Action.Invoke()""
IL_002b: nop
-IL_002c: nop
-IL_002d: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(749138, "DevDiv")]
[Fact]
public void SequencePoints_Delegate_For()
{
var source = @"
using System;
class C
{
public static void Main()
{
for (int x = 0; x < 10; x++)
{
Action a = null;
a = (Action)delegate { a = null; };
a();
}
}
}
";
// Verify the sequence point on the display class construction
var c = CompileAndVerify(source, options: TestOptions.DebugDll);
c.VerifyIL("C.Main", @"
{
// Code size 65 (0x41)
.maxstack 3
.locals init (int V_0, //x
C.<>c__DisplayClass0_0 V_1, //CS$<>8__locals0
int V_2,
bool V_3)
-IL_0000: nop
-IL_0001: ldc.i4.0
IL_0002: stloc.0
~IL_0003: br.s IL_0037
-IL_0005: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_000a: stloc.1
-IL_000b: ldloc.1
IL_000c: ldnull
IL_000d: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0012: ldloc.1
IL_0013: ldloc.1
IL_0014: ldftn ""void C.<>c__DisplayClass0_0.<Main>b__0()""
IL_001a: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_001f: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0024: ldloc.1
IL_0025: ldfld ""System.Action C.<>c__DisplayClass0_0.a""
IL_002a: callvirt ""void System.Action.Invoke()""
IL_002f: nop
-IL_0030: nop
-IL_0031: ldloc.0
IL_0032: stloc.2
IL_0033: ldloc.2
IL_0034: ldc.i4.1
IL_0035: add
IL_0036: stloc.0
-IL_0037: ldloc.0
IL_0038: ldc.i4.s 10
IL_003a: clt
IL_003c: stloc.3
~IL_003d: ldloc.3
IL_003e: brtrue.s IL_0005
-IL_0040: ret
}
", sequencePoints: "C.Main");
}
[WorkItem(749138, "DevDiv")]
[Fact]
public void SequencePoints_Delegate_ForEach()
{
var source = @"
using System;
class C
{
public static void Main()
{
foreach (int x in new[] { 1 })
{
Action a = null;
a = (Action)delegate { a = null; };
a();
}
}
}
";
// Verify the sequence point on the display class construction
var c = CompileAndVerify(source, options: TestOptions.DebugDll);
c.VerifyIL("C.Main", @"
{
// Code size 76 (0x4c)
.maxstack 4
.locals init (int[] V_0,
int V_1,
int V_2, //x
C.<>c__DisplayClass0_0 V_3) //CS$<>8__locals0
-IL_0000: nop
-IL_0001: nop
-IL_0002: ldc.i4.1
IL_0003: newarr ""int""
IL_0008: dup
IL_0009: ldc.i4.0
IL_000a: ldc.i4.1
IL_000b: stelem.i4
IL_000c: stloc.0
IL_000d: ldc.i4.0
IL_000e: stloc.1
~IL_000f: br.s IL_0045
-IL_0011: ldloc.0
IL_0012: ldloc.1
IL_0013: ldelem.i4
IL_0014: stloc.2
-IL_0015: newobj ""C.<>c__DisplayClass0_0..ctor()""
IL_001a: stloc.3
-IL_001b: ldloc.3
IL_001c: ldnull
IL_001d: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0022: ldloc.3
IL_0023: ldloc.3
IL_0024: ldftn ""void C.<>c__DisplayClass0_0.<Main>b__0()""
IL_002a: newobj ""System.Action..ctor(object, System.IntPtr)""
IL_002f: stfld ""System.Action C.<>c__DisplayClass0_0.a""
-IL_0034: ldloc.3
IL_0035: ldfld ""System.Action C.<>c__DisplayClass0_0.a""
IL_003a: callvirt ""void System.Action.Invoke()""
IL_003f: nop
-IL_0040: nop
~IL_0041: ldloc.1
IL_0042: ldc.i4.1
IL_0043: add
IL_0044: stloc.1
-IL_0045: ldloc.1
IL_0046: ldloc.0
IL_0047: ldlen
IL_0048: conv.i4
IL_0049: blt.s IL_0011
-IL_004b: ret
}
", sequencePoints: "C.Main");
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.Setup;
using QuantConnect.Lean.Engine.TransactionHandlers;
using QuantConnect.Orders;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Statistics;
namespace QuantConnect.Lean.Engine.Results
{
/// <summary>
/// Handle the results of the backtest: where should we send the profit, portfolio updates:
/// Backtester or the Live trading platform:
/// </summary>
[InheritedExport(typeof(IResultHandler))]
public interface IResultHandler
{
/// <summary>
/// Put messages to process into the queue so they are processed by this thread.
/// </summary>
ConcurrentQueue<Packet> Messages
{
get;
set;
}
/// <summary>
/// Charts collection for storing the master copy of user charting data.
/// </summary>
ConcurrentDictionary<string, Chart> Charts
{
get;
set;
}
/// <summary>
/// Sampling period for timespans between resamples of the charting equity.
/// </summary>
/// <remarks>Specifically critical for backtesting since with such long timeframes the sampled data can get extreme.</remarks>
TimeSpan ResamplePeriod
{
get;
}
/// <summary>
/// How frequently the backtests push messages to the browser.
/// </summary>
/// <remarks>Update frequency of notification packets</remarks>
TimeSpan NotificationPeriod
{
get;
}
/// <summary>
/// Boolean flag indicating the result hander thread is busy.
/// False means it has completely finished and ready to dispose.
/// </summary>
bool IsActive
{
get;
}
/// <summary>
/// Initialize the result handler with this result packet.
/// </summary>
/// <param name="job">Algorithm job packet for this result handler</param>
/// <param name="messagingHandler"></param>
/// <param name="api"></param>
/// <param name="dataFeed"></param>
/// <param name="setupHandler"></param>
/// <param name="transactionHandler"></param>
void Initialize(AlgorithmNodePacket job, IMessagingHandler messagingHandler, IApi api, IDataFeed dataFeed, ISetupHandler setupHandler, ITransactionHandler transactionHandler);
/// <summary>
/// Primary result thread entry point to process the result message queue and send it to whatever endpoint is set.
/// </summary>
void Run();
/// <summary>
/// Process debug messages with the preconfigured settings.
/// </summary>
/// <param name="message">String debug message</param>
void DebugMessage(string message);
/// <summary>
/// Process system debug messages with the preconfigured settings.
/// </summary>
/// <param name="message">String debug message</param>
void SystemDebugMessage(string message);
/// <summary>
/// Send a list of security types to the browser
/// </summary>
/// <param name="types">Security types list inside algorithm</param>
void SecurityType(List<SecurityType> types);
/// <summary>
/// Send a logging message to the log list for storage.
/// </summary>
/// <param name="message">Message we'd in the log.</param>
void LogMessage(string message);
/// <summary>
/// Send an error message back to the browser highlighted in red with a stacktrace.
/// </summary>
/// <param name="error">Error message we'd like shown in console.</param>
/// <param name="stacktrace">Stacktrace information string</param>
void ErrorMessage(string error, string stacktrace = "");
/// <summary>
/// Send a runtime error message back to the browser highlighted with in red
/// </summary>
/// <param name="message">Error message.</param>
/// <param name="stacktrace">Stacktrace information string</param>
void RuntimeError(string message, string stacktrace = "");
/// <summary>
/// Add a sample to the chart specified by the chartName, and seriesName.
/// </summary>
/// <param name="chartName">String chart name to place the sample.</param>
/// <param name="seriesName">Series name for the chart.</param>
/// <param name="seriesType">Series type for the chart.</param>
/// <param name="time">Time for the sample</param>
/// <param name="value">Value for the chart sample.</param>
/// <param name="unit">Unit for the sample chart</param>
/// <param name="seriesIndex">Index of the series we're sampling</param>
/// <remarks>Sample can be used to create new charts or sample equity - daily performance.</remarks>
void Sample(string chartName, string seriesName, int seriesIndex, SeriesType seriesType, DateTime time, decimal value, string unit = "$");
/// <summary>
/// Wrapper methond on sample to create the equity chart.
/// </summary>
/// <param name="time">Time of the sample.</param>
/// <param name="value">Equity value at this moment in time.</param>
/// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/>
void SampleEquity(DateTime time, decimal value);
/// <summary>
/// Sample the current daily performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current daily performance value.</param>
/// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/>
void SamplePerformance(DateTime time, decimal value);
/// <summary>
/// Sample the current benchmark performance directly with a time-value pair.
/// </summary>
/// <param name="time">Current backtest date.</param>
/// <param name="value">Current benchmark value.</param>
/// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/>
void SampleBenchmark(DateTime time, decimal value);
/// <summary>
/// Sample the asset prices to generate plots.
/// </summary>
/// <param name="symbol">Symbol we're sampling.</param>
/// <param name="time">Time of sample</param>
/// <param name="value">Value of the asset price</param>
/// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/>
void SampleAssetPrices(Symbol symbol, DateTime time, decimal value);
/// <summary>
/// Add a range of samples from the users algorithms to the end of our current list.
/// </summary>
/// <param name="samples">Chart updates since the last request.</param>
/// <seealso cref="Sample(string,string,int,SeriesType,DateTime,decimal,string)"/>
void SampleRange(List<Chart> samples);
/// <summary>
/// Set the algorithm of the result handler after its been initialized.
/// </summary>
/// <param name="algorithm">Algorithm object matching IAlgorithm interface</param>
void SetAlgorithm(IAlgorithm algorithm);
/// <summary>
/// Sets the current alpha runtime statistics
/// </summary>
/// <param name="statistics">The current alpha runtime statistics</param>
void SetAlphaRuntimeStatistics(AlphaRuntimeStatistics statistics);
/// <summary>
/// Save the snapshot of the total results to storage.
/// </summary>
/// <param name="packet">Packet to store.</param>
/// <param name="async">Store the packet asyncronously to speed up the thread.</param>
/// <remarks>Async creates crashes in Mono 3.10 if the thread disappears before the upload is complete so it is disabled for now.</remarks>
void StoreResult(Packet packet, bool async = false);
/// <summary>
/// Post the final result back to the controller worker if backtesting, or to console if local.
/// </summary>
/// <param name="job">Lean AlgorithmJob task</param>
/// <param name="orders">Collection of orders from the algorithm</param>
/// <param name="profitLoss">Collection of time-profit values for the algorithm</param>
/// <param name="holdings">Current holdings state for the algorithm</param>
/// <param name="statisticsResults">Statistics information for the algorithm (empty if not finished)</param>
/// <param name="banner">Runtime statistics banner information</param>
void SendFinalResult(AlgorithmNodePacket job, Dictionary<int, Order> orders, Dictionary<DateTime, decimal> profitLoss, Dictionary<string, Holding> holdings, CashBook cashbook, StatisticsResults statisticsResults, Dictionary<string, string> banner);
/// <summary>
/// Send a algorithm status update to the user of the algorithms running state.
/// </summary>
/// <param name="status">Status enum of the algorithm.</param>
/// <param name="message">Optional string message describing reason for status change.</param>
void SendStatusUpdate(AlgorithmStatus status, string message = "");
/// <summary>
/// Set the chart name:
/// </summary>
/// <param name="symbol">Symbol of the chart we want.</param>
void SetChartSubscription(string symbol);
/// <summary>
/// Set a dynamic runtime statistic to show in the (live) algorithm header
/// </summary>
/// <param name="key">Runtime headline statistic name</param>
/// <param name="value">Runtime headline statistic value</param>
void RuntimeStatistic(string key, string value);
/// <summary>
/// Send a new order event.
/// </summary>
/// <param name="newEvent">Update, processing or cancellation of an order, update the IDE in live mode or ignore in backtesting.</param>
void OrderEvent(OrderEvent newEvent);
/// <summary>
/// Terminate the result thread and apply any required exit proceedures.
/// </summary>
void Exit();
/// <summary>
/// Purge/clear any outstanding messages in message queue.
/// </summary>
void PurgeQueue();
/// <summary>
/// Process any synchronous events in here that are primarily triggered from the algorithm loop
/// </summary>
void ProcessSynchronousEvents(bool forceProcess = false);
/// <summary>
/// Save the logs
/// </summary>
/// <param name="id">Id that will be incorporated into the algorithm log name</param>
/// <param name="logs">The logs to save</param>
string SaveLogs(string id, IEnumerable<string> logs);
/// <summary>
/// Save the results
/// </summary>
/// <param name="name">The name of the results</param>
/// <param name="result">The results to save</param>
void SaveResults(string name, Result result);
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Generation;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
namespace IronPython.Runtime.Types {
/// <summary>
/// Base class for properties backed by methods. These include our slot properties,
/// indexers, and normal properties. This class provides the storage of these as well
/// as the storage of our optimized getter/setter methods, documentation for the property,
/// etc...
/// </summary>
public abstract class ReflectedGetterSetter : PythonTypeSlot {
private MethodInfo/*!*/[]/*!*/ _getter, _setter;
private readonly NameType _nameType;
private BuiltinFunction _getfunc, _setfunc;
protected ReflectedGetterSetter(MethodInfo[]/*!*/ getter, MethodInfo[]/*!*/ setter, NameType nt) {
Debug.Assert(getter != null);
Debug.Assert(setter != null);
_getter = RemoveNullEntries(getter);
_setter = RemoveNullEntries(setter);
_nameType = nt;
}
protected ReflectedGetterSetter(ReflectedGetterSetter from) {
_getter = from._getter;
_setter = from._setter;
_nameType = from._nameType;
}
internal void AddGetter(MethodInfo mi) {
lock (this) {
_getter = ArrayUtils.Append(_getter, mi);
MakeGetFunc();
}
}
private void MakeGetFunc() {
_getfunc = PythonTypeOps.GetBuiltinFunction(DeclaringType, __name__, _getter);
}
internal void AddSetter(MethodInfo mi) {
lock (this) {
_setter = ArrayUtils.Append(_setter, mi);
MakeSetFunc();
}
}
private void MakeSetFunc() {
_setfunc = PythonTypeOps.GetBuiltinFunction(DeclaringType, __name__, _setter);
}
internal abstract Type DeclaringType {
get;
}
public abstract string __name__ {
get;
}
public PythonType/*!*/ __objclass__ {
get {
return DynamicHelpers.GetPythonTypeFromType(DeclaringType);
}
}
internal MethodInfo/*!*/[]/*!*/ Getter {
get {
return _getter;
}
}
internal MethodInfo/*!*/[]/*!*/ Setter {
get {
return _setter;
}
}
public virtual PythonType PropertyType {
[PythonHidden]
get {
if (Getter != null && Getter.Length > 0) {
return DynamicHelpers.GetPythonTypeFromType(Getter[0].ReturnType);
}
return DynamicHelpers.GetPythonTypeFromType(typeof(object));
}
}
internal NameType NameType {
get {
return _nameType;
}
}
internal object CallGetter(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], object>>> storage, object instance, object[] args) {
if (NeedToReturnProperty(instance, Getter)) {
return this;
}
if (Getter.Length == 0) {
throw new MissingMemberException("unreadable property");
}
if (_getfunc == null) {
lock (this) {
if (_getfunc == null) {
MakeGetFunc();
}
}
}
return _getfunc.Call(context, storage, instance, args);
}
internal object CallTarget(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], object>>> storage, MethodInfo[] targets, object instance, params object[] args) {
BuiltinFunction target = PythonTypeOps.GetBuiltinFunction(DeclaringType, __name__, targets);
return target.Call(context, storage, instance, args);
}
internal static bool NeedToReturnProperty(object instance, MethodInfo[] mis) {
if (instance == null) {
if (mis.Length == 0) {
return true;
}
foreach (MethodInfo mi in mis) {
if (!mi.IsStatic ||
(mi.IsDefined(typeof(PropertyMethodAttribute), true) &&
!mi.IsDefined(typeof(StaticExtensionMethodAttribute), true)) &&
!mi.IsDefined(typeof(WrapperDescriptorAttribute), true)) {
return true;
}
}
}
return false;
}
internal bool CallSetter(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], object>>> storage, object instance, object[] args, object value) {
if (NeedToReturnProperty(instance, Setter)) {
return false;
}
if (_setfunc == null) {
lock (this) {
if (_setfunc == null) {
MakeSetFunc();
}
}
}
if (args.Length != 0) {
_setfunc.Call(context, storage, instance, ArrayUtils.Append(args, value));
} else {
_setfunc.Call(context, storage, instance, new [] { value });
}
return true;
}
internal override bool IsAlwaysVisible {
get {
return _nameType == NameType.PythonProperty;
}
}
private static MethodInfo[] RemoveNullEntries(MethodInfo[] mis) {
List<MethodInfo> res = null;
for (int i = 0; i < mis.Length; i++) {
if (mis[i] == null) {
if (res == null) {
res = new List<MethodInfo>();
for (int j = 0; j < i; j++) {
res.Add(mis[j]);
}
}
} else if (res != null) {
res.Add(mis[i]);
}
}
if (res != null) {
return res.ToArray();
}
return mis;
}
}
}
| |
#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.Collections.Generic;
using System.Text;
using gov.va.medora; // for StringTestObject
using NUnit.Framework;
using Spring.Context;
using Spring.Context.Support;
using Common.Logging;
using gov.va.medora.mdo.exceptions;
namespace gov.va.medora.utils
{
[TestFixture]
public class DateUtilsTest
{
//private static readonly ILog LOG
// = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[Test]
public void testIsLeapYear()
{
Assert.IsTrue(DateUtils.isLeapYear(2000));
Assert.IsFalse(DateUtils.isLeapYear(2001));
Assert.IsTrue(DateUtils.isLeapYear(2012));
Assert.IsTrue(DateUtils.isLeapYear(6024));
Assert.IsFalse(DateUtils.isLeapYear(0));
}
[Test]
public void testIsValidMonth()
{
Assert.IsFalse(DateUtils.isValidMonth(-12));
Assert.IsFalse(DateUtils.isValidMonth(13));
Assert.IsTrue(DateUtils.isValidMonth(1));
Assert.IsTrue(DateUtils.isValidMonth(2));
Assert.IsTrue(DateUtils.isValidMonth(3));
Assert.IsTrue(DateUtils.isValidMonth(4));
Assert.IsTrue(DateUtils.isValidMonth(5));
Assert.IsTrue(DateUtils.isValidMonth(6));
Assert.IsTrue(DateUtils.isValidMonth(7));
Assert.IsTrue(DateUtils.isValidMonth(8));
Assert.IsTrue(DateUtils.isValidMonth(9));
Assert.IsTrue(DateUtils.isValidMonth(10));
Assert.IsTrue(DateUtils.isValidMonth(11));
Assert.IsTrue(DateUtils.isValidMonth(12));
}
[Test]
public void testIsValidDay()
{
Assert.IsFalse(DateUtils.isValidDay(1900, 2, 0));
Assert.IsFalse(DateUtils.isValidDay(1900, 2, 32));
Assert.IsFalse(DateUtils.isValidDay(1900, 4, 31));
Assert.IsTrue(DateUtils.isValidDay(1900, 1, 30));
Assert.IsFalse(DateUtils.isValidDay(1900, 2, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 3, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 4, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 5, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 6, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 7, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 8, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 9, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 10, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 11, 30));
Assert.IsTrue(DateUtils.isValidDay(1900, 12, 30));
Assert.IsFalse(DateUtils.isValidDay(2001, 2, 29));
Assert.IsTrue(DateUtils.isValidDay(2004, 2, 29));
}
[Test]
public void testIs30DayMonth()
{
Assert.IsTrue(DateUtils.is30DayMonth(4));
Assert.IsTrue(DateUtils.is30DayMonth(6));
Assert.IsTrue(DateUtils.is30DayMonth(9));
Assert.IsTrue(DateUtils.is30DayMonth(11));
Assert.IsFalse(DateUtils.is30DayMonth(1));
Assert.IsFalse(DateUtils.is30DayMonth(2));
Assert.IsFalse(DateUtils.is30DayMonth(3));
Assert.IsFalse(DateUtils.is30DayMonth(5));
Assert.IsFalse(DateUtils.is30DayMonth(7));
Assert.IsFalse(DateUtils.is30DayMonth(8));
Assert.IsFalse(DateUtils.is30DayMonth(10));
Assert.IsFalse(DateUtils.is30DayMonth(12));
}
[Test]
public void testIsWellFormedDatePart()
{
Assert.IsFalse(DateUtils.isWellFormedDatePart(""));
Assert.IsFalse(DateUtils.isWellFormedDatePart(null));
Assert.IsFalse(DateUtils.isWellFormedDatePart("09121978"));
Assert.IsFalse(DateUtils.isWellFormedDatePart("1978"));
Assert.IsFalse(DateUtils.isWellFormedDatePart("1978052212"));
Assert.IsFalse(DateUtils.isWellFormedDatePart("theeight"));
Assert.IsFalse(DateUtils.isWellFormedDatePart("1978.0912."));
Assert.IsFalse(DateUtils.isWellFormedDatePart("19782112")); // bad month
Assert.IsFalse(DateUtils.isWellFormedDatePart("19782112")); // bad day
Assert.IsFalse(DateUtils.isWellFormedDatePart("19780499")); // too many days
Assert.IsFalse(DateUtils.isWellFormedDatePart("19780431")); // too many days
Assert.IsFalse(DateUtils.isWellFormedDatePart("19780631")); // too many days
Assert.IsFalse(DateUtils.isWellFormedDatePart("19780931")); // too many days
Assert.IsFalse(DateUtils.isWellFormedDatePart("19781131")); // too many days
Assert.IsFalse(DateUtils.isWellFormedDatePart("19780230")); // too many days
Assert.IsFalse(DateUtils.isWellFormedDatePart("19780229")); // not leap year
Assert.IsTrue(DateUtils.isWellFormedDatePart("19780912"));
Assert.IsTrue(DateUtils.isWellFormedDatePart("19780912."));
Assert.IsTrue(DateUtils.isWellFormedDatePart("19800229"));
}
[Test]
public void testIsWellFormedTimePart()
{
Assert.IsTrue(DateUtils.isWellFormedTimePart("asdf"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("200405.221234"));
Assert.IsTrue(DateUtils.isWellFormedTimePart("20040522.1234"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.12345678"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.12345678"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.asdfgh"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.443456"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.129956"));
Assert.IsFalse(DateUtils.isWellFormedTimePart("20040522.123499"));
Assert.IsTrue(DateUtils.isWellFormedTimePart("20040522.123456"));
}
[Test]
public void testIsWellFormedUtcDateTime()
{
Assert.IsTrue(DateUtils.isWellFormedUtcDateTime("20040522.123456"));
Assert.IsFalse(DateUtils.isWellFormedUtcDateTime("200405.123456"));
Assert.IsTrue(DateUtils.isWellFormedUtcDateTime("20040522.1234"));
}
[Test]
public void testTrimSeconds() {
Assert.AreEqual("20040522123456", DateUtils.trimSeconds("20040522123456"));
Assert.AreEqual("20040522.1234", DateUtils.trimSeconds("20040522.1234"));
Assert.AreEqual("20040522.1234", DateUtils.trimSeconds("20040522.123456"));
}
[Test]
public void testZeroSeconds()
{
Assert.AreEqual("20040522123456.000000", DateUtils.zeroSeconds("20040522123456"));
Assert.AreEqual("20040522.123400", DateUtils.zeroSeconds("20040522.1234"));
Assert.AreEqual("20040522.123400", DateUtils.zeroSeconds("20040522.123456"));
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid 'from' date: ")]
public void testIsValidDateRangesNull1stArg()
{
DateUtils.CheckDateRange(null, "20070102");
}
[Test]
[ExpectedException("gov.va.medora.mdo.exceptions.MdoException", "Invalid 'to' date: ")]
public void testIsValidDateRangesNull2ndArg()
{
DateUtils.CheckDateRange("20070102", null);
}
[Test]
[ExpectedException(typeof(MdoException), "Invalid 'from' date: abcd")]
public void testIsValidDateRangesBadFrom()
{
DateUtils.CheckDateRange("abcd", "20070102");
}
[Test]
[ExpectedException(typeof(MdoException), "Invalid 'to' date: abcd")]
public void testIsValidDateRangesBadTo()
{
DateUtils.CheckDateRange("20070102", "abcd");
}
[Test]
public void testValidDateRanges()
{
DateUtils.CheckDateRange("20070102", "20080102");
DateUtils.CheckDateRange("20070102.012345", "20080102");
DateUtils.CheckDateRange("20070102", "20080102.012345");
DateUtils.CheckDateRange("20070102.012345", "20080102.012345");
}
[Test]
[ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")]
public void testInvalidDateRange_starttimeBeforeEnd()
{
DateUtils.CheckDateRange("20070102.022345", "20070102.012345");
}
[Test]
[ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")]
public void testInvalidDateRange_startBeforeEnd()
{
DateUtils.CheckDateRange("20070103", "20070102");
}
[Test]
[ExpectedException(typeof(InvalidDateRangeException), "Invalid date range")]
public void testInvalidDateRange_startEqualsEnd()
{
DateUtils.CheckDateRange("20070102", "20070102"); //same date
}
[Test]
public void TestIsoDateStringToDateTime()
{
String dateString = "20070102";
DateTime testTime = DateUtils.IsoDateStringToDateTime(dateString);
Assert.AreEqual(new DateTime(2007, 01, 02), testTime, "expect new DateTime of 2007/01/02");
}
[Test]
[Category("real_sites")]
public void TestIsoDateStringToDateTimeWithHours()
{
String dateString = "20070102.123456789";
DateTime testTime = DateUtils.IsoDateStringToDateTime(dateString);
Assert.AreEqual(new DateTime(2007, 01, 02,12,34,56,789), testTime, "unexpected DateTime");
}
[Test]
[Category("real_sites")]
public void TestIsoDateStringToDateTimeWithHoursMissingSeconds()
{
String dateString = "20070102.123400789";
DateTime testTime = DateUtils.IsoDateStringToDateTime(dateString);
Assert.AreEqual(new DateTime(2007, 01, 02, 12, 34, 0, 789), testTime, "unexpected DateTime");
}
[Test]
[Category("unit_only")]
public void TestTrimTime_NormalDateTime()
{
string DATE_TIME = "20091123.123456";
Assert.AreEqual("20091123", DateUtils.trimTime(DATE_TIME));
}
[Test]
[Category("unit_only")]
public void TestTrimTime_NormalDateOnly()
{
string DATE_TIME = "20091123";
Assert.AreEqual("20091123", DateUtils.trimTime(DATE_TIME));
}
/// <summary>Function will return an empty date if nothing present before the '.' separator
/// </summary>
[Test]
[Category("unit_only")]
public void TestTrimTime_SeparatorAndTimeOnly()
{
string DATE_TIME = ".123456";
Assert.AreEqual("", DateUtils.trimTime(DATE_TIME));
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// DR task
/// First published in XenServer 6.0.
/// </summary>
public partial class DR_task : XenObject<DR_task>
{
public DR_task()
{
}
public DR_task(string uuid,
List<XenRef<SR>> introduced_SRs)
{
this.uuid = uuid;
this.introduced_SRs = introduced_SRs;
}
/// <summary>
/// Creates a new DR_task from a Proxy_DR_task.
/// </summary>
/// <param name="proxy"></param>
public DR_task(Proxy_DR_task proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given DR_task.
/// </summary>
public override void UpdateFrom(DR_task update)
{
uuid = update.uuid;
introduced_SRs = update.introduced_SRs;
}
internal void UpdateFromProxy(Proxy_DR_task proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
introduced_SRs = proxy.introduced_SRs == null ? null : XenRef<SR>.Create(proxy.introduced_SRs);
}
public Proxy_DR_task ToProxy()
{
Proxy_DR_task result_ = new Proxy_DR_task();
result_.uuid = uuid ?? "";
result_.introduced_SRs = (introduced_SRs != null) ? Helper.RefListToStringArray(introduced_SRs) : new string[] {};
return result_;
}
/// <summary>
/// Creates a new DR_task from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public DR_task(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this DR_task
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("introduced_SRs"))
introduced_SRs = Marshalling.ParseSetRef<SR>(table, "introduced_SRs");
}
public bool DeepEquals(DR_task other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._introduced_SRs, other._introduced_SRs);
}
internal static List<DR_task> ProxyArrayToObjectList(Proxy_DR_task[] input)
{
var result = new List<DR_task>();
foreach (var item in input)
result.Add(new DR_task(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, DR_task server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given DR_task.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static DR_task get_record(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_record(session.opaque_ref, _dr_task);
else
return new DR_task((Proxy_DR_task)session.proxy.dr_task_get_record(session.opaque_ref, _dr_task ?? "").parse());
}
/// <summary>
/// Get a reference to the DR_task instance with the specified UUID.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<DR_task> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<DR_task>.Create(session.proxy.dr_task_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given DR_task.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static string get_uuid(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_uuid(session.opaque_ref, _dr_task);
else
return (string)session.proxy.dr_task_get_uuid(session.opaque_ref, _dr_task ?? "").parse();
}
/// <summary>
/// Get the introduced_SRs field of the given DR_task.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static List<XenRef<SR>> get_introduced_SRs(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_introduced_srs(session.opaque_ref, _dr_task);
else
return XenRef<SR>.Create(session.proxy.dr_task_get_introduced_srs(session.opaque_ref, _dr_task ?? "").parse());
}
/// <summary>
/// Create a disaster recovery task which will query the supplied list of devices
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_type">The SR driver type of the SRs to introduce</param>
/// <param name="_device_config">The device configuration of the SRs to introduce</param>
/// <param name="_whitelist">The devices to use for disaster recovery</param>
public static XenRef<DR_task> create(Session session, string _type, Dictionary<string, string> _device_config, string[] _whitelist)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_create(session.opaque_ref, _type, _device_config, _whitelist);
else
return XenRef<DR_task>.Create(session.proxy.dr_task_create(session.opaque_ref, _type ?? "", Maps.convert_to_proxy_string_string(_device_config), _whitelist).parse());
}
/// <summary>
/// Create a disaster recovery task which will query the supplied list of devices
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_type">The SR driver type of the SRs to introduce</param>
/// <param name="_device_config">The device configuration of the SRs to introduce</param>
/// <param name="_whitelist">The devices to use for disaster recovery</param>
public static XenRef<Task> async_create(Session session, string _type, Dictionary<string, string> _device_config, string[] _whitelist)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_dr_task_create(session.opaque_ref, _type, _device_config, _whitelist);
else
return XenRef<Task>.Create(session.proxy.async_dr_task_create(session.opaque_ref, _type ?? "", Maps.convert_to_proxy_string_string(_device_config), _whitelist).parse());
}
/// <summary>
/// Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static void destroy(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.dr_task_destroy(session.opaque_ref, _dr_task);
else
session.proxy.dr_task_destroy(session.opaque_ref, _dr_task ?? "").parse();
}
/// <summary>
/// Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_dr_task">The opaque_ref of the given dr_task</param>
public static XenRef<Task> async_destroy(Session session, string _dr_task)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_dr_task_destroy(session.opaque_ref, _dr_task);
else
return XenRef<Task>.Create(session.proxy.async_dr_task_destroy(session.opaque_ref, _dr_task ?? "").parse());
}
/// <summary>
/// Return a list of all the DR_tasks known to the system.
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<DR_task>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_all(session.opaque_ref);
else
return XenRef<DR_task>.Create(session.proxy.dr_task_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the DR_task Records at once, in a single XML RPC call
/// First published in XenServer 6.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<DR_task>, DR_task> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.dr_task_get_all_records(session.opaque_ref);
else
return XenRef<DR_task>.Create<Proxy_DR_task>(session.proxy.dr_task_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// All SRs introduced by this appliance
/// </summary>
[JsonConverter(typeof(XenRefListConverter<SR>))]
public virtual List<XenRef<SR>> introduced_SRs
{
get { return _introduced_SRs; }
set
{
if (!Helper.AreEqual(value, _introduced_SRs))
{
_introduced_SRs = value;
Changed = true;
NotifyPropertyChanged("introduced_SRs");
}
}
}
private List<XenRef<SR>> _introduced_SRs = new List<XenRef<SR>>() {};
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Provisioning.Common
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// 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.IO;
using System.Threading.Tasks;
namespace System.Net.Http
{
/// <summary>
/// Helper class is used to copy the content of a source stream to a destination stream,
/// with optimizations based on expected usage within HttpClient and with the ability
/// to dispose of the source stream when the copy has completed.
/// </summary>
internal static class StreamToStreamCopy
{
/// <summary>Copies the source stream from its current position to the destination stream at its current position.</summary>
/// <param name="source">The source stream from which to copy.</param>
/// <param name="destination">The destination stream to which to copy.</param>
/// <param name="bufferSize">The size of the buffer to allocate if one needs to be allocated.</param>
/// <param name="disposeSource">Whether to dispose of the source stream after the copy has finished successfully.</param>
public static Task CopyAsync(Stream source, Stream destination, int bufferSize, bool disposeSource)
{
Debug.Assert(source != null);
Debug.Assert(destination != null);
Debug.Assert(bufferSize > 0);
try
{
// If the source is a MemoryStream from which we can extract the internal buffer,
// then we can perform the copy in a single write operation.
ArraySegment<byte> sourceBuffer;
MemoryStream sourceMemoryStream = source as MemoryStream;
if (sourceMemoryStream != null && sourceMemoryStream.TryGetBuffer(out sourceBuffer))
{
// It's possible source derives from MemoryStream but has a bad override of Position.
// If we get back a value that doesn't make sense, don't take the optimized path.
long pos = source.CanSeek ? source.Position : -1;
if (pos >= 0 && pos < sourceBuffer.Count)
{
// We need to copy from the current position, so if necessary update the buffer
// based on the position of the stream.
if (pos != 0)
{
sourceBuffer = new ArraySegment<byte>(
sourceBuffer.Array,
(int)checked(sourceBuffer.Offset + pos),
(int)checked(sourceBuffer.Count - pos));
}
// Update position to simulate reading all the data
source.Position += sourceBuffer.Count;
// Now write the buffer to the destination stream. This will complete synchronously if the
// destination's WriteAsync completes synchronously, such as if destination is also a MemoryStream.
// Thus we don't need to special case it.
return WriteToAnyStreamAsync(sourceBuffer, source, destination, disposeSource);
}
}
// The source is not a MemoryStream whose buffer we can use directly, but the destination might be our special
// LimitMemoryStream, in which case if it's been pre-sized with a capacity, we can optimize the copy
// by giving its buffer to the source directly, avoiding the need for an intermediate buffer.
HttpContent.LimitMemoryStream destinationLimitStream = destination as HttpContent.LimitMemoryStream;
if (destinationLimitStream != null)
{
// We primarily care about the case where the stream has been presized based on a Content-Length.
// If capacity is 0, we have no buffer to copy to, so we skip. If capacity is <= the max size allowed,
// then we can fill the capacity that's there, and if it's not enough (which should be very rare),
// we'll just fall back to continuing with a read/write loop for any additional data. If the capacity
// is greater than the max size, we don't want to copy to it, as if we use all of the capacity, we'll
// end up exceeding the max, so we skip the optimization for that case. That case could happen if
// there's no Content-Length, and the stream is written to by something before it's given to us, in which
// case the growth-algorithm inside the MemoryStream could cause its capacity to grow beyond the MaxSize;
// that case should also be extremely rare, and we don't care about it from an optimization perspective.
int capacity = destinationLimitStream.Capacity;
if (capacity > 0 && capacity <= destinationLimitStream.MaxSize)
{
return CopyAsyncToPreSizedLimitMemoryStream(source, destinationLimitStream, bufferSize, disposeSource);
}
}
// If the source is a MemoryStream, at this point we know we can't get its buffer. But, since
// we're about to allocate a new byte[] of length bufferSize, if the MemoryStream's Length is
// no larger than that and we're at the beginning of the stream, we can just ask it for its array
// and still do a single write to the target.
if (sourceMemoryStream != null &&
sourceMemoryStream.CanSeek &&
sourceMemoryStream.Position == 0 &&
sourceMemoryStream.Length <= bufferSize)
{
var buffer = new ArraySegment<byte>(sourceMemoryStream.ToArray());
sourceMemoryStream.Position = buffer.Count; // Update position to simulate reading all the data
return WriteToAnyStreamAsync(buffer, sourceMemoryStream, destination, disposeSource);
}
// No special-stream cases worked, so we need to fall back to doing a normal copy, involving
// allocating a byte[] of length bufferSize. However, if we don't need to dispose of the source,
// then there's no work to be performed after the copy operation finishes, and we can simply delegate
// to the source's CopyToAsync implementation to provide the best implementation the source can muster.
// If we do need to dispose of the source, then using CopyToAsync would result in needing an extra
// async method wrapper and its potential allocations, so we fall back to our own read/write loop that
// does the copy and the disposal in a single async method.
return disposeSource ?
CopyAsyncAnyStreamToAnyStreamCore(source, destination, bufferSize, disposeSource) :
source.CopyToAsync(destination, bufferSize);
}
catch (Exception e)
{
// For compatibility with the previous implementation, catch everything (including arg exceptions) and
// store errors into the task rather than letting them propagate to the synchronous caller.
return Task.FromException(e);
}
}
/// <summary>Writes the array segment to the destination stream.</summary>
/// <param name="buffer">The array segment to write.</param>
/// <param name="source">The source stream with which <paramref name="buffer"/> is associated.</param>
/// <param name="destination">The destination stream to which to write.</param>
/// <param name="disposeSource">Whether to dispose of the source stream after the copy has finished successfully.</param>
private static async Task WriteToAnyStreamAsync(ArraySegment<byte> buffer, Stream source, Stream destination, bool disposeSource)
{
await destination.WriteAsync(buffer.Array, buffer.Offset, buffer.Count).ConfigureAwait(false);
DisposeSource(disposeSource, source);
}
/// <summary>Copies a source stream to a LimitMemoryStream by writing directly to the LimitMemoryStream's buffer.</summary>
/// <param name="source">The source stream from which to copy.</param>
/// <param name="destination">The destination LimitMemoryStream to write to.</param>
/// <param name="bufferSize">The size of the buffer to allocate if one needs to be allocated.</param>
/// <param name="disposeSource">Whether to dispose of the source stream after the copy has finished successfully.</param>
private static async Task CopyAsyncToPreSizedLimitMemoryStream(Stream source, HttpContent.LimitMemoryStream destination, int bufferSize, bool disposeSource)
{
// When a LimitMemoryStream is constructed to represent a response with a particular ContentLength, its
// Capacity is set to that amount in order to pre-size it. We can take advantage of that in this copy
// by handing the destination's pre-sized underlying byte[] to the source stream for it to read into
// rather than creating a temporary buffer, copying from the source into that, and then copying again
// from the buffer into the LimitMemoryStream.
long capacity = destination.Capacity;
Debug.Assert(capacity > 0, "Caller should have checked that there's capacity");
// Get the initial length of the stream. When the length of a LimitMemoryStream is increased, the newly available
// space is zero-filled, either due to allocating a new array or due to an explicit clear. As a result, we can't
// write into the array directly and then increase the length to the right size afterward, as doing so will overwrite
// all of the data newly written. Instead, we need to increase the length to the capacity, write in our data, and
// then subsequently trim back the length to the end of the written data.
long startingLength = destination.Length;
if (startingLength < capacity)
{
destination.SetLength(capacity);
}
int bytesRead;
try
{
// Get the LimitMemoryStream's buffer.
ArraySegment<byte> entireBuffer;
bool gotBuffer = destination.TryGetBuffer(out entireBuffer);
Debug.Assert(gotBuffer, "Should only be in CopyAsyncToMemoryStream if we were able to get the buffer");
Debug.Assert(entireBuffer.Offset == 0, "LimitMemoryStream's are only constructed with a 0-offset");
Debug.Assert(entireBuffer.Count == entireBuffer.Array.Length, $"LimitMemoryStream's buffer count {entireBuffer.Count} should be the same as its length {entireBuffer.Array.Length}");
// While there's space remaining in the destination buffer, do another read to try to fill it.
// Each time we read successfully, we update the position of the destination stream to be
// at the end of the data read.
int spaceRemaining = (int)(entireBuffer.Array.Length - destination.Position);
while (spaceRemaining > 0)
{
// Read into the buffer
bytesRead = await source.ReadAsync(entireBuffer.Array, (int)destination.Position, spaceRemaining).ConfigureAwait(false);
if (bytesRead == 0)
{
DisposeSource(disposeSource, source);
return;
}
destination.Position += bytesRead;
spaceRemaining -= bytesRead;
}
}
finally
{
// Now that we're done reading directly into the buffer, if we previously increased the length
// of the stream, set it be at the end of the data read.
if (startingLength < capacity)
{
destination.SetLength(destination.Position);
}
}
// A typical case will be that we read exactly the amount requested. This means that the next
// read will likely return 0 bytes, but we need to try to do the read to know that, which means
// we need a buffer to read into. Use a cached single-byte array to do a read for 1-byte.
// Ideally this read returns 0, and we're done.
byte[] singleByteArray = RentCachedSingleByteArray();
bytesRead = await source.ReadAsync(singleByteArray, 0, 1).ConfigureAwait(false);
if (bytesRead == 0)
{
ReturnCachedSingleByteArray(singleByteArray);
DisposeSource(disposeSource, source);
return;
}
// The read actually returned data, which means there was more data available then
// the capacity of the LimitMemoryStream. This is likely an error condition, but
// regardless we need to finish the copy. First, we write out the byte we read...
await destination.WriteAsync(singleByteArray, 0, 1).ConfigureAwait(false);
ReturnCachedSingleByteArray(singleByteArray);
// ...then we fall back to doing the normal read/write loop.
await CopyAsyncAnyStreamToAnyStreamCore(source, destination, bufferSize, disposeSource).ConfigureAwait(false);
}
/// <summary>Copies a source stream to a destination stream via a standard read/write loop.</summary>
/// <param name="source">The source stream from which to copy.</param>
/// <param name="destination">The destination stream to which to copy.</param>
/// <param name="bufferSize">The size of the buffer to allocate if one needs to be allocated.</param>
/// <param name="disposeSource">Whether to dispose of the source stream after the copy has finished successfully.</param>
private static async Task CopyAsyncAnyStreamToAnyStreamCore(Stream source, Stream destination, int bufferSize, bool disposeSource)
{
var buffer = new byte[bufferSize];
int bytesRead;
while ((bytesRead = await source.ReadAsync(buffer, 0, bufferSize).ConfigureAwait(false)) > 0)
{
await destination.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
}
DisposeSource(disposeSource, source);
}
/// <summary>A cached byte[1] array.</summary>
[ThreadStatic]
private static byte[] t_singleByteArray;
/// <summary>Gets a byte[1] array, either taking a cached one or allocating one a new.</summary>
private static byte[] RentCachedSingleByteArray()
{
byte[] singleByteArray = t_singleByteArray;
if (singleByteArray != null)
{
// This will be used across async points, so we need to ensure no one else can use
// the array while it's in use.
t_singleByteArray = null;
return singleByteArray;
}
else
{
return new byte[1];
}
}
private static void ReturnCachedSingleByteArray(byte[] singleByteArray)
{
t_singleByteArray = singleByteArray; // ok if we overwrite one already there
}
/// <summary>Disposes the source stream if <paramref name="disposeSource"/> is true.</summary>
private static void DisposeSource(bool disposeSource, Stream source)
{
if (!disposeSource) return;
try
{
source.Dispose();
}
catch (Exception e)
{
// Dispose() should never throw, but since we're on an async codepath, make sure to catch the exception.
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exception(NetEventSource.ComponentType.Http, null, nameof(CopyAsync), e);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
namespace System.Globalization
{
public partial class CompareInfo
{
internal unsafe CompareInfo(CultureInfo culture)
{
_name = culture.m_name;
_sortName = culture.SortName;
}
internal unsafe static int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
fixed (char *pSource = source) fixed (char *pValue = value)
{
char *pSrc = &pSource[startIndex];
int index = FindStringOrdinal(pSrc, count, pValue, value.Length, FindStringOptions.Start, ignoreCase);
if (index >= 0)
{
return index + startIndex;
}
return -1;
}
}
internal unsafe static int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
fixed (char *pSource = source) fixed (char *pValue = value)
{
char *pSrc = &pSource[startIndex - count + 1];
int index = FindStringOrdinal(pSrc, count, pValue, value.Length, FindStringOptions.End, ignoreCase);
if (index >= 0)
{
return index + startIndex - (count - 1);
}
return -1;
}
}
private unsafe bool StartsWith(string source, string prefix, CompareOptions options)
{
fixed (char *pSource = source) fixed (char *pValue = prefix)
{
return FindStringOrdinal(pSource, source.Length, pValue, prefix.Length, FindStringOptions.StartsWith,
(options & CompareOptions.IgnoreCase) != 0) >= 0;
}
}
private unsafe bool EndsWith(string source, string suffix, CompareOptions options)
{
fixed (char *pSource = source) fixed (char *pValue = suffix)
{
return FindStringOrdinal(pSource, source.Length, pValue, suffix.Length, FindStringOptions.EndsWith,
(options & CompareOptions.IgnoreCase) != 0) >= 0;
}
}
private unsafe int IndexOfCore(string source, string value, int startIndex, int count, CompareOptions options)
{
return IndexOfOrdinal(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
}
private unsafe int LastIndexOfCore(string source, string value, int startIndex, int count, CompareOptions options)
{
return LastIndexOfOrdinal(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
}
private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
bool ignoreCase = (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0;
if (ignoreCase)
{
return source.ToUpper().GetHashCode();
}
return source.GetHashCode();
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
fixed (char *pStr1 = string1) fixed (char *pStr2 = string2)
{
char *pString1 = &pStr1[offset1];
char *pString2 = &pStr2[offset2];
return CompareString(pString1, length1, pString2, length2, options);
}
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
return CompareString(string1, count1, string2, count2, 0);
}
private static unsafe int CompareString(char *pString1, int length1, char *pString2, int length2, CompareOptions options)
{
bool ignoreCase = (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0;
int index = 0;
if (ignoreCase)
{
while ( index < length1 &&
index < length2 &&
ToUpper(pString1[index]) == ToUpper(pString2[index]))
{
index++;
}
}
else
{
while ( index < length1 &&
index < length2 &&
pString1[index] == pString2[index])
{
index++;
}
}
if (index >= length1)
{
if (index >= length2)
{
return 0;
}
return -1;
}
if (index >= length2)
{
return 1;
}
return ignoreCase ? ToUpper(pString1[index]) - ToUpper(pString2[index]) : pString1[index] - pString2[index];
}
private unsafe static int FindStringOrdinal(char *source, int sourceCount, char *value,int valueCount, FindStringOptions option, bool ignoreCase)
{
int ctrSource = 0; // index value into source
int ctrValue = 0; // index value into value
char sourceChar; // Character for case lookup in source
char valueChar; // Character for case lookup in value
int lastSourceStart;
Contract.Assert(source != null);
Contract.Assert(value != null);
Contract.Assert(sourceCount>= 0);
Contract.Assert(valueCount >= 0);
if(valueCount == 0)
{
switch (option)
{
case FindStringOptions.StartsWith:
case FindStringOptions.Start:
return(0);
case FindStringOptions.EndsWith:
case FindStringOptions.End:
return(sourceCount);
default:
return -1;
}
}
if(sourceCount < valueCount)
{
return -1;
}
switch (option)
{
case FindStringOptions.StartsWith:
{
if (ignoreCase)
{
for (ctrValue = 0; ctrValue < valueCount; ctrValue++)
{
sourceChar = ToUpper(source[ctrValue]);
valueChar = ToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
}
else
{
for (ctrValue = 0; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
}
if (ctrValue == valueCount)
{
return 0;
}
}
break;
case FindStringOptions.Start:
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = ToUpper(value[0]);
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = ToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = ToUpper(source[ctrSource + ctrValue]);
valueChar = ToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
break;
case FindStringOptions.EndsWith:
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
for (ctrSource = lastSourceStart, ctrValue = 0; ctrValue < valueCount; ctrSource++,ctrValue++)
{
sourceChar = ToUpper(source[ctrSource]);
valueChar = ToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
}
else
{
for (ctrSource = lastSourceStart, ctrValue = 0; ctrValue < valueCount; ctrSource++,ctrValue++)
{
sourceChar = source[ctrSource];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
}
if (ctrValue == valueCount)
{
return sourceCount - valueCount;
}
}
break;
case FindStringOptions.End:
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = ToUpper(value[0]);
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = ToUpper(source[ctrSource]);
if(sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = ToUpper(source[ctrSource + ctrValue]);
valueChar = ToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
} else {
char firstValueChar = value[0];
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = source[ctrSource];
if(sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
break;
default:
return -1;
}
return -1;
}
private static char ToUpper(char c)
{
return ('a' <= c && c <= 'z') ? (char)(c - 0x20) : c;
}
private enum FindStringOptions
{
Start,
StartsWith,
End,
EndsWith,
}
}
}
| |
using EIDSS.Reports.Document.Veterinary.LivestockInvestigation;
namespace EIDSS.Reports.Document.Veterinary.AvianInvestigation
{
partial class FlockReport
{
/// <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 Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FlockReport));
this.Detail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand();
this.herdDataSet1 = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSet();
this.sp_Rep_Vet_HerdDetailsTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSetTableAdapters.spRepVetHerdDetailsTableAdapter();
this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.topMarginBand1 = new DevExpress.XtraReports.UI.TopMarginBand();
this.bottomMarginBand1 = new DevExpress.XtraReports.UI.BottomMarginBand();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.herdDataSet1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// Detail
//
this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Name = "Detail";
this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UseTextAlignment = false;
//
// xrTable2
//
this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow2});
this.xrTable2.StylePriority.UseBorders = false;
this.xrTable2.StylePriority.UseFont = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell13,
this.xrTableCell4,
this.xrTableCell5,
this.xrTableCell6,
this.xrTableCell7,
this.xrTableCell11,
this.xrTableCell12});
this.xrTableRow2.Name = "xrTableRow2";
this.xrTableRow2.Weight = 1;
//
// xrTableCell13
//
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.HerdCode")});
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.Weight = 0.599692481174841;
//
// xrTableCell4
//
this.xrTableCell4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.SpeciesID")});
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.Weight = 0.59969251930226308;
//
// xrTableCell5
//
this.xrTableCell5.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Total")});
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.Weight = 0.49974374478052364;
//
// xrTableCell6
//
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Dead")});
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.Weight = 0.49974374556212009;
//
// xrTableCell7
//
this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.Sick")});
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.Weight = 0.49974376093136352;
//
// xrTableCell11
//
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.AVGAge")});
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.Weight = 0.499743773275903;
//
// xrTableCell12
//
this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetHerdDetails.SignsDate", "{0:dd/MM/yyyy}")});
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.Weight = 0.49974369531240348;
//
// PageHeader
//
this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable1});
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Name = "PageHeader";
this.PageHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)
| DevExpress.XtraPrinting.BorderSide.Bottom)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1});
this.xrTable1.StylePriority.UseBorders = false;
this.xrTable1.StylePriority.UseFont = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.xrTableCell8,
this.xrTableCell9,
this.xrTableCell1,
this.xrTableCell2,
this.xrTableCell10,
this.xrTableCell3});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.Weight = 1;
//
// xrTableCell14
//
this.xrTableCell14.Name = "xrTableCell14";
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Weight = 0.62805634735140559;
//
// xrTableCell8
//
this.xrTableCell8.Name = "xrTableCell8";
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
this.xrTableCell8.Weight = 0.62805611858687338;
//
// xrTableCell9
//
this.xrTableCell9.Name = "xrTableCell9";
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Weight = 0.52338061130160729;
//
// xrTableCell1
//
this.xrTableCell1.Name = "xrTableCell1";
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Weight = 0.52338000204445134;
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Weight = 0.52338032243307109;
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Weight = 0.52338029665018848;
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Weight = 0.523380333068955;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.Name = "PageFooter";
this.PageFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F);
//
// herdDataSet1
//
this.herdDataSet1.DataSetName = "HerdDataSet";
this.herdDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// sp_Rep_Vet_HerdDetailsTableAdapter
//
this.sp_Rep_Vet_HerdDetailsTableAdapter.ClearBeforeFill = true;
//
// ReportHeader
//
this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel1});
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Name = "ReportHeader";
this.ReportHeader.StylePriority.UseFont = false;
this.ReportHeader.StylePriority.UseTextAlignment = false;
//
// xrLabel1
//
this.xrLabel1.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseBorders = false;
this.xrLabel1.StylePriority.UseFont = false;
//
// topMarginBand1
//
resources.ApplyResources(this.topMarginBand1, "topMarginBand1");
this.topMarginBand1.Name = "topMarginBand1";
//
// bottomMarginBand1
//
resources.ApplyResources(this.bottomMarginBand1, "bottomMarginBand1");
this.bottomMarginBand1.Name = "bottomMarginBand1";
//
// FlockReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.topMarginBand1,
this.bottomMarginBand1});
this.DataAdapter = this.sp_Rep_Vet_HerdDetailsTableAdapter;
this.DataMember = "spRepVetHerdDetails";
this.DataSource = this.herdDataSet1;
this.ExportOptions.Xls.SheetName = resources.GetString("FlockReport.ExportOptions.Xls.SheetName");
this.ExportOptions.Xlsx.SheetName = resources.GetString("FlockReport.ExportOptions.Xlsx.SheetName");
resources.ApplyResources(this, "$this");
this.Version = "10.1";
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.herdDataSet1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailBand Detail;
private DevExpress.XtraReports.UI.PageHeaderBand PageHeader;
private DevExpress.XtraReports.UI.PageFooterBand PageFooter;
private HerdDataSet herdDataSet1;
private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdDataSetTableAdapters.spRepVetHerdDetailsTableAdapter sp_Rep_Vet_HerdDetailsTableAdapter;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.TopMarginBand topMarginBand1;
private DevExpress.XtraReports.UI.BottomMarginBand bottomMarginBand1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
}
}
| |
//
// DatabaseImportManager.cs
//
// Authors:
// Aaron Bockover <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.IO;
using Mono.Unix;
using Hyena;
using Hyena.Data.Sqlite;
using Banshee.Base;
using Banshee.Sources;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.ServiceStack;
using Banshee.Streaming;
namespace Banshee.Collection.Database
{
public class DatabaseImportManager : ImportManager
{
// This is a list of known media files that we may encounter. The extensions
// in this list do not mean they are actually supported - this list is just
// used to see if we should allow the file to be processed by TagLib. The
// point is to rule out, at the path level, files that we won't support.
public static readonly Banshee.IO.ExtensionSet WhiteListFileExtensions = new Banshee.IO.ExtensionSet (
"3g2", "3gp", "3gp2", "3gpp", "aac", "ac3", "aif", "aifc",
"aiff", "al", "alaw", "ape", "asf", "asx", "au", "avi",
"cda", "cdr", "divx", "dv", "flac", "flv", "gvi", "gvp",
"m1v", "m21", "m2p", "m2v", "m4a", "m4b", "m4e", "m4p",
"m4u", "m4v", "mp+", "mid", "midi", "mjp", "mkv", "moov",
"mov", "movie","mp1", "mp2", "mp21", "mp3", "mp4", "mpa",
"mpc", "mpe", "mpeg", "mpg", "mpga", "mpp", "mpu", "mpv",
"mpv2", "oga", "ogg", "ogv", "ogm", "omf", "qt", "ra",
"ram", "raw", "rm", "rmvb", "rts", "smil", "swf", "tivo",
"u", "vfw", "vob", "wav", "wave", "wax", "wm", "wma",
"wmd", "wmv", "wmx", "wv", "wvc", "wvx", "yuv", "f4v",
"f4a", "f4b", "669", "it", "med", "mod", "mol", "mtm",
"nst", "s3m", "stm", "ult", "wow", "xm", "xnm", "spx",
"ts"
);
public static bool IsWhiteListedFile (string path)
{
return WhiteListFileExtensions.IsMatchingFile (path);
}
public delegate PrimarySource TrackPrimarySourceChooser (DatabaseTrackInfo track);
private TrackPrimarySourceChooser trackPrimarySourceChooser;
private Dictionary<int, int> counts;
private ErrorSource error_source;
private int [] primary_source_ids;
private string base_directory;
private bool force_copy;
public event DatabaseImportResultHandler ImportResult;
public DatabaseImportManager (PrimarySource psource) :
this (psource.ErrorSource, delegate { return psource; }, new int [] {psource.DbId}, psource.BaseDirectory)
{
}
public DatabaseImportManager (ErrorSource error_source, TrackPrimarySourceChooser chooser,
int [] primarySourceIds, string baseDirectory) : this (chooser)
{
this.error_source = error_source;
primary_source_ids = primarySourceIds;
base_directory = baseDirectory;
}
public DatabaseImportManager (TrackPrimarySourceChooser chooser)
{
trackPrimarySourceChooser = chooser;
counts = new Dictionary<int, int> ();
}
protected virtual ErrorSource ErrorSource {
get { return error_source; }
}
protected virtual int [] PrimarySourceIds {
get { return primary_source_ids; }
set { primary_source_ids = value; }
}
protected virtual string BaseDirectory {
get { return base_directory; }
set { base_directory = value; }
}
protected virtual bool ForceCopy {
get { return force_copy; }
set { force_copy = value; }
}
protected override void OnImportRequested (string path)
{
try {
DatabaseTrackInfo track = ImportTrack (path);
if (track != null && track.TrackId > 0) {
UpdateProgress (String.Format ("{0} - {1}",
track.DisplayArtistName, track.DisplayTrackTitle));
} else {
UpdateProgress (null);
}
OnImportResult (track, path, null);
} catch (Exception e) {
LogError (path, e);
UpdateProgress (null);
OnImportResult (null, path, e);
}
}
protected virtual void OnImportResult (DatabaseTrackInfo track, string path, Exception error)
{
DatabaseImportResultHandler handler = ImportResult;
if (handler != null) {
handler (this, new DatabaseImportResultArgs (track, path, error));
}
}
public DatabaseTrackInfo ImportTrack (string path)
{
return ImportTrack (new SafeUri (path));
}
public DatabaseTrackInfo ImportTrack (SafeUri uri)
{
if (!IsWhiteListedFile (uri.LocalPath)) {
return null;
}
if (DatabaseTrackInfo.ContainsUri (uri, PrimarySourceIds)) {
// TODO add DatabaseTrackInfo.SyncedStamp property, and if the file has been
// updated since the last sync, fetch its metadata into the db.
return null;
}
DatabaseTrackInfo track = null;
// TODO note, there is deadlock potential here b/c of locking of shared commands and blocking
// because of transactions. Needs to be fixed in HyenaDatabaseConnection.
ServiceManager.DbConnection.BeginTransaction ();
try {
track = new DatabaseTrackInfo ();
track.Uri = uri;
StreamTagger.TrackInfoMerge (track, StreamTagger.ProcessUri (uri));
track.PrimarySource = trackPrimarySourceChooser (track);
bool save_track = true;
if (track.PrimarySource is Banshee.Library.LibrarySource) {
save_track = track.CopyToLibraryIfAppropriate (force_copy);
}
if (save_track) {
track.Save (false);
}
ServiceManager.DbConnection.CommitTransaction ();
} catch (Exception) {
ServiceManager.DbConnection.RollbackTransaction ();
throw;
}
counts[track.PrimarySourceId] = counts.ContainsKey (track.PrimarySourceId) ? counts[track.PrimarySourceId] + 1 : 1;
// Reload every 20% or every 250 tracks, whatever is more (eg at most reload 5 times during an import)
if (counts[track.PrimarySourceId] >= Math.Max (TotalCount/5, 250)) {
counts[track.PrimarySourceId] = 0;
track.PrimarySource.NotifyTracksAdded ();
}
return track;
}
private void LogError (string path, Exception e)
{
LogError (path, e.Message);
if (!(e is TagLib.CorruptFileException) && !(e is TagLib.UnsupportedFormatException)) {
Log.DebugFormat ("Full import exception: {0}", e.ToString ());
}
}
private void LogError (string path, string msg)
{
ErrorSource.AddMessage (path, msg);
Log.Error (path, msg, false);
}
public void NotifyAllSources ()
{
foreach (int primary_source_id in counts.Keys) {
PrimarySource.GetById (primary_source_id).NotifyTracksAdded ();
}
counts.Clear ();
}
protected override void OnFinished ()
{
NotifyAllSources ();
base.OnFinished ();
}
}
}
| |
using Glass.Mapper.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Sitecore.Globalization;
using System;
using System.Linq;
namespace Glass.Mapper.Sc.Configuration
{
/// <summary>
/// Class SitecoreTypeConfiguration
/// </summary>
public class SitecoreTypeConfiguration : AbstractTypeConfiguration
{
/// <summary>
/// Gets or sets the template id.
/// </summary>
/// <value>The template id.</value>
public ID TemplateId { get; set; }
/// <summary>
/// Gets or sets the branch id.
/// </summary>
/// <value>The branch id.</value>
public ID BranchId { get; set; }
/// <summary>
/// Gets or sets the id config.
/// </summary>
/// <value>The id config.</value>
public SitecoreIdConfiguration IdConfig { get; set; }
/// <summary>
/// Gets or sets the language config.
/// </summary>
/// <value>The language config.</value>
public SitecoreInfoConfiguration LanguageConfig { get; set; }
/// <summary>
/// Gets or sets the version config.
/// </summary>
/// <value>The version config.</value>
public SitecoreInfoConfiguration VersionConfig { get; set; }
/// <summary>
/// Gets or sets the item config
/// </summary>
public SitecoreItemConfiguration ItemConfig { get; set; }
/// <summary>
/// Gets or sets the ItemUri config
/// </summary>
public SitecoreInfoConfiguration ItemUriConfig { get; set; }
/// <summary>
/// Gets or sets the Name config
/// </summary>
public SitecoreInfoConfiguration NameConfig { get; set; }
/// <summary>
/// Gets or sets the Path config
/// </summary>
public SitecoreInfoConfiguration PathConfig { get; set; }
/// <summary>
/// Overrides the default template name when using code first
/// </summary>
/// <value>The name of the template.</value>
public string TemplateName { get; set; }
/// <summary>
/// Forces Glass to do a template check and only returns an class if the item
/// matches the template ID or inherits a template with the templateId
/// </summary>
public SitecoreEnforceTemplate EnforceTemplate { get; set; }
/// <summary>
/// Adds the property.
/// </summary>
/// <param name="property">The property.</param>
public override void AddProperty(AbstractPropertyConfiguration property)
{
if (property is SitecoreIdConfiguration)
IdConfig = property as SitecoreIdConfiguration;
var infoProperty = property as SitecoreInfoConfiguration;
if (infoProperty != null)
{
AssignInfoToKnownProperty(this, infoProperty);
}
if (property is SitecoreItemConfiguration)
ItemConfig = property as SitecoreItemConfiguration;
base.AddProperty(property);
}
public static void AssignInfoToKnownProperty(SitecoreTypeConfiguration typeConfig,
SitecoreInfoConfiguration infoProperty)
{
switch (infoProperty.Type)
{
case SitecoreInfoType.Language:
typeConfig.LanguageConfig = infoProperty;
break;
case SitecoreInfoType.Version:
typeConfig.VersionConfig = infoProperty;
break;
case SitecoreInfoType.ItemUri:
typeConfig. ItemUriConfig = infoProperty;
break;
case SitecoreInfoType.Name:
typeConfig.NameConfig = infoProperty;
break;
case SitecoreInfoType.Path:
typeConfig.PathConfig = infoProperty;
break;
}
}
public ID GetId(object target)
{
ID id = ID.Null;
if (IdConfig != null)
{
if (IdConfig.PropertyInfo.PropertyType == typeof (Guid))
{
var guidId = (Guid) IdConfig.PropertyInfo.GetValue(target, null);
id = new ID(guidId);
}
else if (IdConfig.PropertyInfo.PropertyType == typeof (ID))
{
id = IdConfig.PropertyInfo.GetValue(target, null) as ID;
}
else
{
throw new NotSupportedException("Cannot get ID for item");
}
}
else if (ItemUriConfig != null)
{
var itemUri = (ItemUri)ItemUriConfig.PropertyInfo.GetValue(target, null);
if (itemUri != null)
{
id = itemUri.ItemID;
}
}
return id;
}
/// <summary>
/// Dumps information about the current type configuration to the Sitecore logs.
/// </summary>
public virtual void LogDumpConfiguration()
{
Sitecore.Diagnostics.Log.Debug("CD - Configuration Dump for {0}".Formatted(Type.FullName), this);
var interaces = Type.GetInterfaces();
if (interaces.Any())
{
Sitecore.Diagnostics.Log.Debug("CD - {0}".Formatted(interaces.Select(x => x.FullName).Aggregate((x, y) => "{0}, {1}".Formatted(x, y))), this);
}
if (Properties != null)
{
foreach (var property in Properties)
{
Sitecore.Diagnostics.Log.Debug("CD - property: {0} - {1}".Formatted(property.PropertyInfo.Name, property.PropertyInfo.PropertyType.FullName), this);
}
}
}
/// <summary>
/// Resolves the item.
/// </summary>
/// <param name="target">The target.</param>
/// <param name="database">The database.</param>
/// <returns>
/// Item.
/// </returns>
/// <exception cref="System.NotSupportedException">You can not save a class that does not contain a property that represents the item ID. Ensure that at least one property has been marked to contain the Sitecore ID.
/// or
/// Cannot get ID for item</exception>
public Item ResolveItem(object target, Database database)
{
if (target == null)
return null;
ID id;
Language language = null;
int versionNumber = -1;
if (ItemConfig != null)
{
var item = ItemConfig.PropertyGetter(target) as Item;
if (item != null)
return item;
}
if (IdConfig == null && ItemUriConfig == null)
{
string message =
"Failed item resolve - You cannot save a class that does not contain a property that represents the item ID. Ensure that at least one property has been marked to contain the Sitecore ID. Type: {0}"
.Formatted(target.GetType().FullName);
Sitecore.Diagnostics.Log.Error(message, this);
LogDumpConfiguration();
throw new NotSupportedException(message);
}
id = GetId(target);
language = GetLanguage(target);
versionNumber = GetVersion(target);
if (language != null && versionNumber > 0)
{
return database.GetItem(id, language, global::Sitecore.Data.Version.Parse(versionNumber));
}
else if (language != null)
{
return database.GetItem(id, language);
}
else
{
return database.GetItem(id);
}
}
public int GetVersion(object target)
{
int versionNumber = -1;
if (VersionConfig != null)
{
var valueInt = VersionConfig.PropertyInfo.GetValue(target, null);
if (valueInt is int)
{
versionNumber = (int)valueInt;
}
else if (valueInt is string)
{
int.TryParse(valueInt as string, out versionNumber);
}
}
else if (ItemUriConfig != null)
{
var itemUri = (ItemUri)ItemUriConfig.PropertyInfo.GetValue(target, null);
if (itemUri != null)
{
versionNumber = itemUri.Version.Number;
}
}
return versionNumber;
}
/// <summary>
/// Gets the language.
/// </summary>
/// <param name="target">The target.</param>
/// <returns></returns>
public Language GetLanguage(object target)
{
Language language = null;
if (LanguageConfig != null)
{
object langValue = LanguageConfig.PropertyInfo.GetValue(target, null);
if (langValue == null)
{
language = Language.Current;
}
else if (langValue is Language)
{
language = langValue as Language;
}
else if (langValue is string)
{
language = LanguageManager.GetLanguage(langValue as string);
}
}
else if (ItemUriConfig != null)
{
var itemUri = (ItemUri)ItemUriConfig.PropertyInfo.GetValue(target, null);
if (itemUri != null)
{
language = itemUri.Language;
}
}
return language;
}
public string GetName(object target)
{
if (NameConfig == null)
throw new MapperException("The type {0} does not have a property with attribute SitecoreInfo(SitecoreInfoType.Name)".Formatted(target.GetType().FullName));
string name = string.Empty;
try
{
name = NameConfig.PropertyInfo.GetValue(target, null).ToString();
return name;
}
catch
{
throw new MapperException("Failed to get item name");
}
}
/// <summary>
/// Called to map each property automatically
/// </summary>
/// <param name="property"></param>
/// <returns></returns>
protected override AbstractPropertyConfiguration AutoMapProperty(System.Reflection.PropertyInfo property)
{
string name = property.Name;
SitecoreInfoType infoType;
if (name.ToLowerInvariant() == "id")
{
var idConfig = new SitecoreIdConfiguration();
idConfig.PropertyInfo = property;
return idConfig;
}
if (name.ToLowerInvariant() == "parent")
{
var parentConfig = new SitecoreParentConfiguration();
parentConfig.PropertyInfo = property;
return parentConfig;
}
if (name.ToLowerInvariant() == "children")
{
var childrenConfig = new SitecoreChildrenConfiguration();
childrenConfig.PropertyInfo = property;
return childrenConfig;
}
if (name.ToLowerInvariant() == "item" && property.PropertyType == typeof(Item))
{
var itemConfig = new SitecoreItemConfiguration();
itemConfig.PropertyInfo = property;
return itemConfig;
}
if (Enum.TryParse(name, true, out infoType))
{
SitecoreInfoConfiguration infoConfig = new SitecoreInfoConfiguration();
infoConfig.PropertyInfo = property;
infoConfig.Type = infoType;
return infoConfig;
}
SitecoreFieldConfiguration fieldConfig = new SitecoreFieldConfiguration();
fieldConfig.FieldName = name;
fieldConfig.PropertyInfo = property;
return fieldConfig;
}
public override void GetTypeOptions(GetOptions options)
{
base.GetTypeOptions(options);
var scOptions = options as GetItemOptions;
if (scOptions.EnforceTemplate == SitecoreEnforceTemplate.Default)
{
scOptions.EnforceTemplate = this.EnforceTemplate;
}
if (ID.IsNullOrEmpty(scOptions.TemplateId))
{
scOptions.TemplateId = this.TemplateId;
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="WriterValidationUtils.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.OData.Core
{
#region Namespaces
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.OData.Edm;
using Microsoft.OData.Core.Metadata;
#endregion Namespaces
/// <summary>
/// Class with utility methods for validating OData content when writing.
/// </summary>
internal static class WriterValidationUtils
{
/// <summary>
/// Validates that message writer settings are correct.
/// </summary>
/// <param name="messageWriterSettings">The message writer settings to validate.</param>
/// <param name="writingResponse">True if we are writing a response.</param>
internal static void ValidateMessageWriterSettings(ODataMessageWriterSettings messageWriterSettings, bool writingResponse)
{
Debug.Assert(messageWriterSettings != null, "messageWriterSettings != null");
if (messageWriterSettings.PayloadBaseUri != null && !messageWriterSettings.PayloadBaseUri.IsAbsoluteUri)
{
throw new ODataException(Strings.WriterValidationUtils_MessageWriterSettingsBaseUriMustBeNullOrAbsolute(UriUtils.UriToString(messageWriterSettings.PayloadBaseUri)));
}
if (messageWriterSettings.HasJsonPaddingFunction() && !writingResponse)
{
throw new ODataException(Strings.WriterValidationUtils_MessageWriterSettingsJsonPaddingOnRequestMessage);
}
}
/// <summary>
/// Validates an <see cref="ODataProperty"/> for not being null.
/// </summary>
/// <param name="property">The property to validate for not being null.</param>
internal static void ValidatePropertyNotNull(ODataProperty property)
{
if (property == null)
{
throw new ODataException(Strings.WriterValidationUtils_PropertyMustNotBeNull);
}
}
/// <summary>
/// Validates a property name to ensure all required information is specified.
/// </summary>
/// <param name="propertyName">The property name to validate.</param>
/// <param name="bypassValidation">Bypass the validation if it is true.</param>
internal static void ValidatePropertyName(string propertyName, bool bypassValidation = false)
{
if (bypassValidation)
{
return;
}
// Properties must have a non-empty name
if (string.IsNullOrEmpty(propertyName))
{
throw new ODataException(Strings.WriterValidationUtils_PropertiesMustHaveNonEmptyName);
}
ValidationUtils.ValidatePropertyName(propertyName);
}
/// <summary>
/// Validates that a property with the specified name exists on a given structured type.
/// The structured type can be null if no metadata is available.
/// </summary>
/// <param name="propertyName">The name of the property to validate.</param>
/// <param name="owningStructuredType">The owning type of the property with name <paramref name="propertyName"/>
/// or null if no metadata is available.</param>
/// <param name="throwOnMissingProperty">Whether throw exception on missing property.</param>
/// <returns>The <see cref="IEdmProperty"/> instance representing the property with name <paramref name="propertyName"/>
/// or null if no metadata is available.</returns>
internal static IEdmProperty ValidatePropertyDefined(
string propertyName,
IEdmStructuredType owningStructuredType,
bool throwOnMissingProperty = true)
{
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
if (owningStructuredType == null)
{
return null;
}
IEdmProperty property = owningStructuredType.FindProperty(propertyName);
// verify that the property is declared if the type is not an open type.
if (throwOnMissingProperty && !owningStructuredType.IsOpen && property == null)
{
throw new ODataException(Strings.ValidationUtils_PropertyDoesNotExistOnType(propertyName, owningStructuredType.ODataFullName()));
}
return property;
}
/// <summary>
/// Validates that a navigation property with the specified name exists on a given entity type.
/// The entity type can be null if no metadata is available.
/// </summary>
/// <param name="propertyName">The name of the property to validate.</param>
/// <param name="owningEntityType">The owning entity type or null if no metadata is available.</param>
/// <returns>The <see cref="IEdmProperty"/> instance representing the navigation property with name <paramref name="propertyName"/>
/// or null if no metadata is available.</returns>
internal static IEdmNavigationProperty ValidateNavigationPropertyDefined(string propertyName, IEdmEntityType owningEntityType)
{
Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)");
if (owningEntityType == null)
{
return null;
}
IEdmProperty property = ValidatePropertyDefined(propertyName, owningEntityType);
if (property == null)
{
// We don't support open navigation properties
Debug.Assert(owningEntityType.IsOpen, "We should have already failed on non-existing property on a closed type.");
throw new ODataException(Strings.ValidationUtils_OpenNavigationProperty(propertyName, owningEntityType.ODataFullName()));
}
if (property.PropertyKind != EdmPropertyKind.Navigation)
{
// The property must be a navigation property
throw new ODataException(Strings.ValidationUtils_NavigationPropertyExpected(propertyName, owningEntityType.ODataFullName(), property.PropertyKind.ToString()));
}
return (IEdmNavigationProperty)property;
}
/// <summary>
/// Validates an entry in an expanded link to make sure the entity types match.
/// </summary>
/// <param name="entryEntityType">The <see cref="IEdmEntityType"/> of the entry.</param>
/// <param name="parentNavigationPropertyType">The type of the parent navigation property.</param>
internal static void ValidateEntryInExpandedLink(IEdmEntityType entryEntityType, IEdmEntityType parentNavigationPropertyType)
{
if (parentNavigationPropertyType == null)
{
return;
}
Debug.Assert(entryEntityType != null, "If we have a parent navigation property type we should also have an entry type.");
// Make sure the entity types are compatible
if (!parentNavigationPropertyType.IsAssignableFrom(entryEntityType))
{
throw new ODataException(Strings.WriterValidationUtils_EntryTypeInExpandedLinkNotCompatibleWithNavigationPropertyType(entryEntityType.ODataFullName(), parentNavigationPropertyType.ODataFullName()));
}
}
/// <summary>
/// Validates that an <see cref="ODataOperation"/> can be written.
/// </summary>
/// <param name="operation">The operation (an action or a function) to validate.</param>
/// <param name="writingResponse">true if writing a response; otherwise false.</param>
internal static void ValidateCanWriteOperation(ODataOperation operation, bool writingResponse)
{
Debug.Assert(operation != null, "operation != null");
// Operations are only valid in responses; we fail on them in requests
if (!writingResponse)
{
throw new ODataException(Strings.WriterValidationUtils_OperationInRequest(operation.Metadata));
}
}
/// <summary>
/// Validates an <see cref="ODataFeed"/> to ensure all required information is specified and valid on the WriteEnd call.
/// </summary>
/// <param name="feed">The feed to validate.</param>
/// <param name="writingRequest">Flag indicating whether the feed is written as part of a request or a response.</param>
internal static void ValidateFeedAtEnd(ODataFeed feed, bool writingRequest)
{
Debug.Assert(feed != null, "feed != null");
// Verify next link
if (feed.NextPageLink != null)
{
// Check that NextPageLink is not set for requests
if (writingRequest)
{
throw new ODataException(Strings.WriterValidationUtils_NextPageLinkInRequest);
}
}
}
/// <summary>
/// Validates an <see cref="ODataEntry"/> to ensure all required information is specified and valid on WriteStart call.
/// </summary>
/// <param name="entry">The entry to validate.</param>
internal static void ValidateEntryAtStart(ODataEntry entry)
{
Debug.Assert(entry != null, "entry != null");
// Id can be specified at the beginning (and might be written here), so we need to validate it here.
ValidateEntryId(entry.Id);
// Type name is verified in the format readers/writers since it's shared with other non-entity types
// and verifying it here would mean doing it twice.
}
/// <summary>
/// Validates an <see cref="ODataEntry"/> to ensure all required information is specified and valid on WriteEnd call.
/// </summary>
/// <param name="entry">The entry to validate.</param>
internal static void ValidateEntryAtEnd(ODataEntry entry)
{
Debug.Assert(entry != null, "entry != null");
// If the Id was not specified in the beginning it might have been specified at the end, so validate it here as well.
ValidateEntryId(entry.Id);
}
/// <summary>
/// Validates an <see cref="ODataStreamReferenceValue"/> to ensure all required information is specified and valid.
/// </summary>
/// <param name="streamReference">The stream reference to validate.</param>
/// <param name="isDefaultStream">true if <paramref name="streamReference"/> is the default stream for an entity; false if it is a named stream property value.</param>
internal static void ValidateStreamReferenceValue(ODataStreamReferenceValue streamReference, bool isDefaultStream)
{
Debug.Assert(streamReference != null, "streamReference != null");
if (streamReference.ContentType != null && streamReference.ContentType.Length == 0)
{
throw new ODataException(Strings.WriterValidationUtils_StreamReferenceValueEmptyContentType);
}
if (isDefaultStream && streamReference.ReadLink == null && streamReference.ContentType != null)
{
throw new ODataException(Strings.WriterValidationUtils_DefaultStreamWithContentTypeWithoutReadLink);
}
if (isDefaultStream && streamReference.ReadLink != null && streamReference.ContentType == null)
{
throw new ODataException(Strings.WriterValidationUtils_DefaultStreamWithReadLinkWithoutContentType);
}
// Default stream can be completely empty (no links or anything)
// that is used to effectively mark the entry as MLE without providing any MR information.
// OData clients when creating new MLE/MR might not have the MR information (yet) when sending the first PUT, but they still
// need to mark the entry as MLE so that properties are written out-of-content. In such scenario the client can just set an empty
// default stream to mark the entry as MLE.
// That will cause the ATOM writer to write the properties outside the content without producing any content element.
if (streamReference.EditLink == null && streamReference.ReadLink == null && !isDefaultStream)
{
throw new ODataException(Strings.WriterValidationUtils_StreamReferenceValueMustHaveEditLinkOrReadLink);
}
if (streamReference.EditLink == null && streamReference.ETag != null)
{
throw new ODataException(Strings.WriterValidationUtils_StreamReferenceValueMustHaveEditLinkToHaveETag);
}
}
/// <summary>
/// Validates a named stream property to ensure it's not null and it's name if correct.
/// </summary>
/// <param name="streamProperty">The stream reference property to validate.</param>
/// <param name="edmProperty">Property metadata to validate against.</param>
/// <param name="writingResponse">true when writing a response; otherwise false.</param>
/// <param name="bypassValidation">Bypass the validation if it is true.</param>
/// <remarks>This does NOT validate the value of the stream property, just the property itself.</remarks>
internal static void ValidateStreamReferenceProperty(ODataProperty streamProperty, IEdmProperty edmProperty, bool writingResponse, bool bypassValidation = false)
{
Debug.Assert(streamProperty != null, "streamProperty != null");
if (bypassValidation)
{
return;
}
ValidationUtils.ValidateStreamReferenceProperty(streamProperty, edmProperty);
if (!writingResponse)
{
// Stream properties are only valid in responses; writers fail if they encounter them in requests.
throw new ODataException(Strings.WriterValidationUtils_StreamPropertyInRequest(streamProperty.Name));
}
}
/// <summary>
/// Validates that the specified <paramref name="entityReferenceLink"/> is not null.
/// </summary>
/// <param name="entityReferenceLink">The entity reference link to validate.</param>
/// <remarks>This should be called only for entity reference links inside the ODataEntityReferenceLinks.Links collection.</remarks>
internal static void ValidateEntityReferenceLinkNotNull(ODataEntityReferenceLink entityReferenceLink)
{
if (entityReferenceLink == null)
{
throw new ODataException(Strings.WriterValidationUtils_EntityReferenceLinksLinkMustNotBeNull);
}
}
/// <summary>
/// Validates an entity reference link instance.
/// </summary>
/// <param name="entityReferenceLink">The entity reference link to validate.</param>
internal static void ValidateEntityReferenceLink(ODataEntityReferenceLink entityReferenceLink)
{
Debug.Assert(entityReferenceLink != null, "entityReferenceLink != null");
if (entityReferenceLink.Url == null)
{
throw new ODataException(Strings.WriterValidationUtils_EntityReferenceLinkUrlMustNotBeNull);
}
}
/// <summary>
/// Validates an <see cref="ODataNavigationLink"/> to ensure all required information is specified and valid.
/// </summary>
/// <param name="navigationLink">The navigation link to validate.</param>
/// <param name="declaringEntityType">The <see cref="IEdmEntityType"/> declaring the navigation property; or null if metadata is not available.</param>
/// <param name="expandedPayloadKind">The <see cref="ODataPayloadKind"/> of the expanded content of this navigation link or null for deferred links.</param>
/// <param name="bypassValidation">Bypass the validation if it is true.</param>
/// <returns>The type of the navigation property for this navigation link; or null if no <paramref name="declaringEntityType"/> was specified.</returns>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Keeping the validation code for navigation link multiplicity in one place.")]
internal static IEdmNavigationProperty ValidateNavigationLink(
ODataNavigationLink navigationLink,
IEdmEntityType declaringEntityType,
ODataPayloadKind? expandedPayloadKind,
bool bypassValidation = false)
{
Debug.Assert(navigationLink != null, "navigationLink != null");
Debug.Assert(
!expandedPayloadKind.HasValue ||
expandedPayloadKind.Value == ODataPayloadKind.EntityReferenceLink ||
expandedPayloadKind.Value == ODataPayloadKind.Entry ||
expandedPayloadKind.Value == ODataPayloadKind.Feed,
"If an expanded payload kind is specified it must be entry, feed or entity reference link.");
if (bypassValidation)
{
return declaringEntityType == null ? null : declaringEntityType.FindProperty(navigationLink.Name) as IEdmNavigationProperty;
}
// Navigation link must have a non-empty name
if (string.IsNullOrEmpty(navigationLink.Name))
{
throw new ODataException(Strings.ValidationUtils_LinkMustSpecifyName);
}
// If we write an entity reference link, don't validate the multiplicity of the IsCollection
// property if it is 'false' (since we allow writing a singleton navigation link for
// a collection navigation property in requests) nor the consistency of payload kind and metadata
// (which is done separately in ODataWriterCore.CheckForNavigationLinkWithContent).
bool isEntityReferenceLinkPayload = expandedPayloadKind == ODataPayloadKind.EntityReferenceLink;
// true only if the expandedPayloadKind has a value and the value is 'Feed'
bool isFeedPayload = expandedPayloadKind == ODataPayloadKind.Feed;
// Make sure the IsCollection property agrees with the payload kind for entry and feed payloads
Func<object, string> errorTemplate = null;
if (!isEntityReferenceLinkPayload && navigationLink.IsCollection.HasValue && expandedPayloadKind.HasValue)
{
// For feed/entry make sure the IsCollection property is set correctly.
if (isFeedPayload != navigationLink.IsCollection.Value)
{
errorTemplate = expandedPayloadKind.Value == ODataPayloadKind.Feed
? (Func<object, string>)Strings.WriterValidationUtils_ExpandedLinkIsCollectionFalseWithFeedContent
: Strings.WriterValidationUtils_ExpandedLinkIsCollectionTrueWithEntryContent;
}
}
IEdmNavigationProperty navigationProperty = null;
if (errorTemplate == null && declaringEntityType != null)
{
navigationProperty = WriterValidationUtils.ValidateNavigationPropertyDefined(navigationLink.Name, declaringEntityType);
Debug.Assert(navigationProperty != null, "If we have a declaring type we expect a non-null navigation property since open nav props are not allowed.");
bool isCollectionType = navigationProperty.Type.TypeKind() == EdmTypeKind.Collection;
// Make sure the IsCollection property agrees with the metadata type for entry and feed payloads
if (navigationLink.IsCollection.HasValue && isCollectionType != navigationLink.IsCollection)
{
// Ignore the case where IsCollection is 'false' and we are writing an entity reference link
// (see comment above)
if (!(navigationLink.IsCollection == false && isEntityReferenceLinkPayload))
{
errorTemplate = isCollectionType
? (Func<object, string>)Strings.WriterValidationUtils_ExpandedLinkIsCollectionFalseWithFeedMetadata
: Strings.WriterValidationUtils_ExpandedLinkIsCollectionTrueWithEntryMetadata;
}
}
// Make sure that the payload kind agrees with the metadata.
// For entity reference links we check separately in ODataWriterCore.CheckForNavigationLinkWithContent.
if (!isEntityReferenceLinkPayload && expandedPayloadKind.HasValue && isCollectionType != isFeedPayload)
{
errorTemplate = isCollectionType
? (Func<object, string>)Strings.WriterValidationUtils_ExpandedLinkWithEntryPayloadAndFeedMetadata
: Strings.WriterValidationUtils_ExpandedLinkWithFeedPayloadAndEntryMetadata;
}
}
if (errorTemplate != null)
{
string uri = navigationLink.Url == null ? "null" : UriUtils.UriToString(navigationLink.Url);
throw new ODataException(errorTemplate(uri));
}
return navigationProperty;
}
/// <summary>
/// Validates that the specified navigation link has a Url.
/// </summary>
/// <param name="navigationLink">The navigation link to validate.</param>
internal static void ValidateNavigationLinkUrlPresent(ODataNavigationLink navigationLink)
{
Debug.Assert(navigationLink != null, "navigationLink != null");
// Navigation link must specify the Url
// NOTE: we currently only require a non-null Url for ATOM payloads and non-expanded navigation links in JSON.
// There is no place in JSON to write a Url if the navigation link is expanded.
if (navigationLink.Url == null)
{
throw new ODataException(Strings.WriterValidationUtils_NavigationLinkMustSpecifyUrl(navigationLink.Name));
}
}
/// <summary>
/// Validates that the sepcified navigation link has cardinality, that is it has the IsCollection value set.
/// </summary>
/// <param name="navigationLink">The navigation link to validate.</param>
internal static void ValidateNavigationLinkHasCardinality(ODataNavigationLink navigationLink)
{
Debug.Assert(navigationLink != null, "navigationLink != null");
if (!navigationLink.IsCollection.HasValue)
{
throw new ODataException(Strings.WriterValidationUtils_NavigationLinkMustSpecifyIsCollection(navigationLink.Name));
}
}
/// <summary>
/// Validates that the expected property allows null value.
/// </summary>
/// <param name="expectedPropertyTypeReference">The expected property type or null if we don't have any.</param>
/// <param name="propertyName">The name of the property.</param>
/// <param name="writerBehavior">The <see cref="ODataWriterBehavior"/> instance controlling the behavior of the writer.</param>
/// <param name="model">The model to use to get the OData version.</param>
/// <param name="bypassValidation">Bypass the validation if it is true.</param>
internal static void ValidateNullPropertyValue(IEdmTypeReference expectedPropertyTypeReference, string propertyName, ODataWriterBehavior writerBehavior, IEdmModel model, bool bypassValidation = false)
{
Debug.Assert(writerBehavior != null, "writerBehavior != null");
Debug.Assert(model != null, "For null validation, model is required.");
if (bypassValidation)
{
return;
}
if (expectedPropertyTypeReference != null)
{
if (expectedPropertyTypeReference.IsNonEntityCollectionType())
{
throw new ODataException(Strings.WriterValidationUtils_CollectionPropertiesMustNotHaveNullValue(propertyName));
}
if (expectedPropertyTypeReference.IsODataPrimitiveTypeKind())
{
// WCF DS allows null values for non-nullable primitive types, so we need to check for a knob which enables this behavior.
// See the description of ODataWriterBehavior.AllowNullValuesForNonNullablePrimitiveTypes for more details.
if (!expectedPropertyTypeReference.IsNullable && !writerBehavior.AllowNullValuesForNonNullablePrimitiveTypes)
{
throw new ODataException(Strings.WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue(propertyName, expectedPropertyTypeReference.ODataFullName()));
}
}
else if (expectedPropertyTypeReference.IsODataEnumTypeKind() && !expectedPropertyTypeReference.IsNullable)
{
throw new ODataException(Strings.WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue(propertyName, expectedPropertyTypeReference.ODataFullName()));
}
else if (expectedPropertyTypeReference.IsStream())
{
throw new ODataException(Strings.WriterValidationUtils_StreamPropertiesMustNotHaveNullValue(propertyName));
}
else if (expectedPropertyTypeReference.IsODataComplexTypeKind())
{
if (ValidationUtils.ShouldValidateComplexPropertyNullValue(model))
{
IEdmComplexTypeReference complexTypeReference = expectedPropertyTypeReference.AsComplex();
if (!complexTypeReference.IsNullable)
{
throw new ODataException(Strings.WriterValidationUtils_NonNullablePropertiesMustNotHaveNullValue(propertyName, expectedPropertyTypeReference.ODataFullName()));
}
}
}
}
}
/// <summary>
/// Validates the value of the Id property on an entry.
/// </summary>
/// <param name="id">The id value for an entry to validate.</param>
private static void ValidateEntryId(Uri id)
{
// Verify non-empty ID (entries can have no (null) ID for insert scenarios; empty IDs are not allowed)
// TODO: it always passes. Will add more validation or remove the validation after supporting relative Uri.
if (id != null && UriUtils.UriToString(id).Length == 0)
{
throw new ODataException(Strings.WriterValidationUtils_EntriesMustHaveNonEmptyId);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Web.Security;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Security;
using Umbraco.Core.Services;
namespace umbraco.cms.businesslogic.web
{
/// <summary>
/// Summary description for Access.
/// </summary>
[Obsolete("Use Umbraco.Core.Service.IPublicAccessService instead")]
public class Access
{
[Obsolete("Do not access this property directly, it is not thread safe, use GetXmlDocumentCopy instead")]
public static XmlDocument AccessXml
{
get { return GetXmlDocumentCopy(); }
}
//NOTE: This is here purely for backwards compat
[Obsolete("This should never be used, the data is stored in the database now")]
public static XmlDocument GetXmlDocumentCopy()
{
var allAccessEntries = ApplicationContext.Current.Services.PublicAccessService.GetAll().ToArray();
var xml = XDocument.Parse("<access/>");
foreach (var entry in allAccessEntries)
{
var pageXml = new XElement("page",
new XAttribute("id", entry.ProtectedNodeId),
new XAttribute("loginPage", entry.LoginNodeId),
new XAttribute("noRightsPage", entry.NoAccessNodeId));
foreach (var rule in entry.Rules)
{
if (rule.RuleType == Constants.Conventions.PublicAccess.MemberUsernameRuleType)
{
//if there is a member id claim then it is 'simple' (this is how legacy worked)
pageXml.Add(new XAttribute("simple", "True"));
pageXml.Add(new XAttribute("memberId", rule.RuleValue));
}
else if (rule.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType)
{
pageXml.Add(new XElement("group", new XAttribute("id", rule.RuleValue)));
}
}
xml.Root.Add(pageXml);
}
return xml.ToXmlDocument();
}
#region Manipulation methods
public static void AddMembershipRoleToDocument(int documentId, string role)
{
//event
var doc = new Document(documentId);
var e = new AddMemberShipRoleToDocumentEventArgs();
new Access().FireBeforeAddMemberShipRoleToDocument(doc, role, e);
if (e.Cancel) return;
var entry = ApplicationContext.Current.Services.PublicAccessService.AddRule(
doc.ContentEntity,
Constants.Conventions.PublicAccess.MemberRoleRuleType,
role);
if (entry.Success == false && entry.Result.Entity == null)
{
throw new Exception("Document is not protected!");
}
Save();
new Access().FireAfterAddMemberShipRoleToDocument(doc, role, e);
}
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static void AddMemberGroupToDocument(int DocumentId, int MemberGroupId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(DocumentId);
if (content == null)
throw new Exception("No content found with document id " + DocumentId);
if (ApplicationContext.Current.Services.PublicAccessService.AddRule(
content,
Constants.Conventions.PublicAccess.MemberGroupIdRuleType,
MemberGroupId.ToString(CultureInfo.InvariantCulture)))
{
Save();
}
}
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static void AddMemberToDocument(int DocumentId, int MemberId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(DocumentId);
if (content == null)
throw new Exception("No content found with document id " + DocumentId);
if (ApplicationContext.Current.Services.PublicAccessService.AddRule(
content,
Constants.Conventions.PublicAccess.MemberIdRuleType,
MemberId.ToString(CultureInfo.InvariantCulture)))
{
Save();
}
}
public static void AddMembershipUserToDocument(int documentId, string membershipUserName)
{
//event
var doc = new Document(documentId);
var e = new AddMembershipUserToDocumentEventArgs();
new Access().FireBeforeAddMembershipUserToDocument(doc, membershipUserName, e);
if (e.Cancel) return;
var entry = ApplicationContext.Current.Services.PublicAccessService.AddRule(
doc.ContentEntity,
Constants.Conventions.PublicAccess.MemberUsernameRuleType,
membershipUserName);
if (entry.Success == false && entry.Result.Entity == null)
{
throw new Exception("Document is not protected!");
}
if (entry)
{
Save();
new Access().FireAfterAddMembershipUserToDocument(doc, membershipUserName, e);
}
}
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static void RemoveMemberGroupFromDocument(int DocumentId, int MemberGroupId)
{
var doc = new Document(DocumentId);
var entry = ApplicationContext.Current.Services.PublicAccessService.AddRule(
doc.ContentEntity,
Constants.Conventions.PublicAccess.MemberGroupIdRuleType,
MemberGroupId.ToString(CultureInfo.InvariantCulture));
if (entry.Success == false && entry.Result.Entity == null)
{
throw new Exception("Document is not protected!");
}
if (entry)
{
Save();
}
}
public static void RemoveMembershipRoleFromDocument(int documentId, string role)
{
var doc = new Document(documentId);
var e = new RemoveMemberShipRoleFromDocumentEventArgs();
new Access().FireBeforeRemoveMemberShipRoleFromDocument(doc, role, e);
if (e.Cancel) return;
if (ApplicationContext.Current.Services.PublicAccessService.RemoveRule(
doc.ContentEntity,
Constants.Conventions.PublicAccess.MemberRoleRuleType,
role))
{
Save();
new Access().FireAfterRemoveMemberShipRoleFromDocument(doc, role, e);
};
}
public static bool RenameMemberShipRole(string oldRolename, string newRolename)
{
var hasChange = ApplicationContext.Current.Services.PublicAccessService.RenameMemberGroupRoleRules(oldRolename, newRolename);
if (hasChange)
Save();
return hasChange;
}
public static void ProtectPage(bool Simple, int DocumentId, int LoginDocumentId, int ErrorDocumentId)
{
var doc = new Document(DocumentId);
var e = new AddProtectionEventArgs();
new Access().FireBeforeAddProtection(doc, e);
if (e.Cancel) return;
var loginContent = ApplicationContext.Current.Services.ContentService.GetById(LoginDocumentId);
if (loginContent == null) throw new NullReferenceException("No content item found with id " + LoginDocumentId);
var noAccessContent = ApplicationContext.Current.Services.ContentService.GetById(ErrorDocumentId);
if (noAccessContent == null) throw new NullReferenceException("No content item found with id " + ErrorDocumentId);
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(doc.ContentEntity.Id.ToString());
if (entry != null)
{
if (Simple)
{
// if using simple mode, make sure that all existing groups are removed
entry.ClearRules();
}
//ensure the correct ids are applied
entry.LoginNodeId = loginContent.Id;
entry.NoAccessNodeId = noAccessContent.Id;
}
else
{
entry = new PublicAccessEntry(doc.ContentEntity,
ApplicationContext.Current.Services.ContentService.GetById(LoginDocumentId),
ApplicationContext.Current.Services.ContentService.GetById(ErrorDocumentId),
new List<PublicAccessRule>());
}
if (ApplicationContext.Current.Services.PublicAccessService.Save(entry))
{
Save();
new Access().FireAfterAddProtection(new Document(DocumentId), e);
}
}
public static void RemoveProtection(int DocumentId)
{
//event
var doc = new Document(DocumentId);
var e = new RemoveProtectionEventArgs();
new Access().FireBeforeRemoveProtection(doc, e);
if (e.Cancel) return;
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(doc.ContentEntity);
if (entry != null)
{
ApplicationContext.Current.Services.PublicAccessService.Delete(entry);
}
Save();
new Access().FireAfterRemoveProtection(doc, e);
}
#endregion
#region Reading methods
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static bool IsProtectedByGroup(int DocumentId, int GroupId)
{
var d = new Document(DocumentId);
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(d.ContentEntity);
if (entry == null) return false;
return entry.Rules
.Any(x => x.RuleType == Constants.Conventions.PublicAccess.MemberGroupIdRuleType
&& x.RuleValue == GroupId.ToString(CultureInfo.InvariantCulture));
}
public static bool IsProtectedByMembershipRole(int documentId, string role)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(documentId);
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(content);
if (entry == null) return false;
return entry.Rules
.Any(x => x.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType
&& x.RuleValue == role);
}
public static string[] GetAccessingMembershipRoles(int documentId, string path)
{
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(path.EnsureEndsWith("," + documentId));
if (entry == null) return new string[] { };
var memberGroupRoleRules = entry.Rules.Where(x => x.RuleType == Constants.Conventions.PublicAccess.MemberRoleRuleType);
return memberGroupRoleRules.Select(x => x.RuleValue).ToArray();
}
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static member.MemberGroup[] GetAccessingGroups(int DocumentId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(DocumentId);
if (content == null) return null;
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(content);
if (entry == null) return null;
var memberGroupIdRules = entry.Rules.Where(x => x.RuleType == Constants.Conventions.PublicAccess.MemberGroupIdRuleType);
return memberGroupIdRules.Select(x => new member.MemberGroup(int.Parse(x.RuleValue))).ToArray();
}
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static member.Member GetAccessingMember(int DocumentId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(DocumentId);
if (content == null) return null;
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(content);
if (entry == null) return null;
//legacy would throw an exception here if it was not 'simple' and simple means based on a member id in this case
if (entry.Rules.All(x => x.RuleType != Constants.Conventions.PublicAccess.MemberIdRuleType))
{
throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead");
}
var memberIdRule = entry.Rules.First(x => x.RuleType == Constants.Conventions.PublicAccess.MemberIdRuleType);
return new member.Member(int.Parse(memberIdRule.RuleValue));
}
public static MembershipUser GetAccessingMembershipUser(int documentId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(documentId);
if (content == null) return null;
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(content);
if (entry == null) return null;
//legacy would throw an exception here if it was not 'simple' and simple means based on a username
if (entry.Rules.All(x => x.RuleType != Constants.Conventions.PublicAccess.MemberUsernameRuleType))
{
throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead");
}
var provider = MembershipProviderExtensions.GetMembersMembershipProvider();
var usernameRule = entry.Rules.First(x => x.RuleType == Constants.Conventions.PublicAccess.MemberUsernameRuleType);
return provider.GetUser(usernameRule.RuleValue, false);
}
[Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)]
public static bool HasAccess(int DocumentId, member.Member Member)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(DocumentId);
if (content == null) return true;
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(content);
if (entry == null) return true;
var memberGroupIds = Member.Groups.Values.Cast<MemberGroup>().Select(x => x.Id.ToString(CultureInfo.InvariantCulture)).ToArray();
return entry.Rules.Any(x => x.RuleType == Constants.Conventions.PublicAccess.MemberGroupIdRuleType
&& memberGroupIds.Contains(x.RuleValue));
}
[Obsolete("This method has been replaced because of a spelling mistake. Use the HasAccess method instead.", false)]
public static bool HasAccces(int documentId, object memberId)
{
// Call the correctly named version of this method
return HasAccess(documentId, memberId);
}
public static bool HasAccess(int documentId, object memberId)
{
return ApplicationContext.Current.Services.PublicAccessService.HasAccess(
documentId,
memberId,
ApplicationContext.Current.Services.ContentService,
MembershipProviderExtensions.GetMembersMembershipProvider(),
//TODO: This should really be targeting a specific provider by name!!
Roles.Provider);
}
public static bool HasAccess(int documentId, string path, MembershipUser member)
{
return ApplicationContext.Current.Services.PublicAccessService.HasAccess(
path,
member,
//TODO: This should really be targeting a specific provider by name!!
Roles.Provider);
}
public static ProtectionType GetProtectionType(int DocumentId)
{
var content = ApplicationContext.Current.Services.ContentService.GetById(DocumentId);
if (content == null) return ProtectionType.NotProtected;
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(content);
if (entry == null) return ProtectionType.NotProtected;
//legacy states that if it is protected by a member id then it is 'simple'
return entry.Rules.Any(x => x.RuleType == Constants.Conventions.PublicAccess.MemberIdRuleType)
? ProtectionType.Simple
: ProtectionType.Advanced;
}
public static bool IsProtected(int DocumentId, string Path)
{
return ApplicationContext.Current.Services.PublicAccessService.IsProtected(Path.EnsureEndsWith("," + DocumentId));
}
//return the protection status of this exact document - not based on inheritance
public static bool IsProtected(int DocumentId)
{
return ApplicationContext.Current.Services.PublicAccessService.IsProtected(DocumentId.ToString());
}
public static int GetErrorPage(string Path)
{
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(Path);
if (entry == null) return -1;
var entity = ApplicationContext.Current.Services.EntityService.Get(entry.NoAccessNodeId, UmbracoObjectTypes.Document, false);
return entity.Id;
}
public static int GetLoginPage(string Path)
{
var entry = ApplicationContext.Current.Services.PublicAccessService.GetEntryForContent(Path);
if (entry == null) return -1;
var entity = ApplicationContext.Current.Services.EntityService.Get(entry.LoginNodeId, UmbracoObjectTypes.Document, false);
return entity.Id;
}
#endregion
//NOTE: This is purely here for backwards compat for events
private static void Save()
{
var e = new SaveEventArgs();
new Access().FireBeforeSave(e);
if (e.Cancel) return;
new Access().FireAfterSave(e);
}
//Event delegates
public delegate void SaveEventHandler(Access sender, SaveEventArgs e);
public delegate void AddProtectionEventHandler(Document sender, AddProtectionEventArgs e);
public delegate void RemoveProtectionEventHandler(Document sender, RemoveProtectionEventArgs e);
public delegate void AddMemberShipRoleToDocumentEventHandler(Document sender, string role, AddMemberShipRoleToDocumentEventArgs e);
public delegate void RemoveMemberShipRoleFromDocumentEventHandler(Document sender, string role, RemoveMemberShipRoleFromDocumentEventArgs e);
public delegate void RemoveMemberShipUserFromDocumentEventHandler(Document sender, string MembershipUserName, RemoveMemberShipUserFromDocumentEventArgs e);
public delegate void AddMembershipUserToDocumentEventHandler(Document sender, string MembershipUserName, AddMembershipUserToDocumentEventArgs e);
//Events
public static event SaveEventHandler BeforeSave;
protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
public static event SaveEventHandler AfterSave;
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
public static event AddProtectionEventHandler BeforeAddProtection;
protected virtual void FireBeforeAddProtection(Document doc, AddProtectionEventArgs e)
{
if (BeforeAddProtection != null)
BeforeAddProtection(doc, e);
}
public static event AddProtectionEventHandler AfterAddProtection;
protected virtual void FireAfterAddProtection(Document doc, AddProtectionEventArgs e)
{
if (AfterAddProtection != null)
AfterAddProtection(doc, e);
}
public static event RemoveProtectionEventHandler BeforeRemoveProtection;
protected virtual void FireBeforeRemoveProtection(Document doc, RemoveProtectionEventArgs e)
{
if (BeforeRemoveProtection != null)
BeforeRemoveProtection(doc, e);
}
public static event RemoveProtectionEventHandler AfterRemoveProtection;
protected virtual void FireAfterRemoveProtection(Document doc, RemoveProtectionEventArgs e)
{
if (AfterRemoveProtection != null)
AfterRemoveProtection(doc, e);
}
public static event AddMemberShipRoleToDocumentEventHandler BeforeAddMemberShipRoleToDocument;
protected virtual void FireBeforeAddMemberShipRoleToDocument(Document doc, string role, AddMemberShipRoleToDocumentEventArgs e)
{
if (BeforeAddMemberShipRoleToDocument != null)
BeforeAddMemberShipRoleToDocument(doc, role, e);
}
public static event AddMemberShipRoleToDocumentEventHandler AfterAddMemberShipRoleToDocument;
protected virtual void FireAfterAddMemberShipRoleToDocument(Document doc, string role, AddMemberShipRoleToDocumentEventArgs e)
{
if (AfterAddMemberShipRoleToDocument != null)
AfterAddMemberShipRoleToDocument(doc, role, e);
}
public static event RemoveMemberShipRoleFromDocumentEventHandler BeforeRemoveMemberShipRoleToDocument;
protected virtual void FireBeforeRemoveMemberShipRoleFromDocument(Document doc, string role, RemoveMemberShipRoleFromDocumentEventArgs e)
{
if (BeforeRemoveMemberShipRoleToDocument != null)
BeforeRemoveMemberShipRoleToDocument(doc, role, e);
}
public static event RemoveMemberShipRoleFromDocumentEventHandler AfterRemoveMemberShipRoleToDocument;
protected virtual void FireAfterRemoveMemberShipRoleFromDocument(Document doc, string role, RemoveMemberShipRoleFromDocumentEventArgs e)
{
if (AfterRemoveMemberShipRoleToDocument != null)
AfterRemoveMemberShipRoleToDocument(doc, role, e);
}
public static event RemoveMemberShipUserFromDocumentEventHandler BeforeRemoveMembershipUserFromDocument;
protected virtual void FireBeforeRemoveMembershipUserFromDocument(Document doc, string username, RemoveMemberShipUserFromDocumentEventArgs e)
{
if (BeforeRemoveMembershipUserFromDocument != null)
BeforeRemoveMembershipUserFromDocument(doc, username, e);
}
public static event RemoveMemberShipUserFromDocumentEventHandler AfterRemoveMembershipUserFromDocument;
protected virtual void FireAfterRemoveMembershipUserFromDocument(Document doc, string username, RemoveMemberShipUserFromDocumentEventArgs e)
{
if (AfterRemoveMembershipUserFromDocument != null)
AfterRemoveMembershipUserFromDocument(doc, username, e);
}
public static event AddMembershipUserToDocumentEventHandler BeforeAddMembershipUserToDocument;
protected virtual void FireBeforeAddMembershipUserToDocument(Document doc, string username, AddMembershipUserToDocumentEventArgs e)
{
if (BeforeAddMembershipUserToDocument != null)
BeforeAddMembershipUserToDocument(doc, username, e);
}
public static event AddMembershipUserToDocumentEventHandler AfterAddMembershipUserToDocument;
protected virtual void FireAfterAddMembershipUserToDocument(Document doc, string username, AddMembershipUserToDocumentEventArgs e)
{
if (AfterAddMembershipUserToDocument != null)
AfterAddMembershipUserToDocument(doc, username, e);
}
}
public enum ProtectionType
{
NotProtected,
Simple,
Advanced
}
}
| |
using System;
using System.Drawing;
using MonoTouch.ObjCRuntime;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
namespace SDWebImage
{
[BaseType (typeof (UIView))]
[Model]
interface SDWebImageManagerDelegate
{
[Export ("imageManager:shouldDownloadImageForURL:")]
void ShouldDownloadImage (SDWebImageManager imageManager, NSUrl url);
[Export ("imageManager:transformDownloadedImage:withURL:")]
void TransformDownloadedImage (SDWebImageManager imageManager, UIImage image, NSUrl url);
}
public delegate void SDWebImageCompletedBlock (UIImage image, NSError error, SDImageCacheType cacheType);
public delegate void SDWebImageCompletedWithFinishedBlock (UIImage image, NSError error, SDImageCacheType cacheType, bool finished);
public delegate void SDWebImageDownloaderProgressBlock (uint receivedSize, long expectedSize);
public delegate void SDWebImageDownloaderCompletedBlock (UIImage image, NSData data, NSError error, bool finished);
public delegate string CacheKeyFilterBlock (NSUrl url);
public delegate void CalculateSizeCompletionBlock (uint fileCount, ulong totalSize);
[BaseType (typeof (NSObject))]
interface SDWebImageDownloader
{
[Export ("maxConcurrentDownloads", ArgumentSemantic.Assign)]
int MaxConcurrentDownloads { get; set; }
[Export ("executionOrder", ArgumentSemantic.Assign)]
SDWebImageDownloaderExecutionOrder ExecutionOrder { get; set; }
[Static, Export ("sharedDownloader")]
SDWebImageDownloader SharedDownloader { get; }
[Export ("setValue:forHTTPHeaderField:")]
void SetHTTPHeaderValue (string value, string field);
[Export ("valueForHTTPHeaderField:")]
string GetHTTPHeaderValue (string field);
[Export ("downloadImageWithURL:options:progress:completed:")]
void DownloadImage (NSUrl url, SDWebImageDownloaderOptions options, [NullAllowed] SDWebImageDownloaderProgressBlock progress, [NullAllowed] SDWebImageDownloaderCompletedBlock completed);
}
[BaseType (typeof (NSObject))]
interface SDWebImageOperation
{
[Export ("cancel")]
void Cancel ();
}
[BaseType (typeof (NSObject))]
interface SDWebImageManager
{
[Wrap ("WeakDelegate")]
SDWebImageManagerDelegate Delegate { get; set; }
[Export ("delegate", ArgumentSemantic.Assign)]
NSObject WeakDelegate { get; set; }
[Static, Export ("sharedManager")]
SDWebImageManager SharedManager { get; }
[Export ("cancelAll")]
void CancelAll ();
[Export ("isRunning")]
bool IsRunning ();
[Export ("diskImageExistsForURL:")]
bool DiskImageExists (NSUrl url);
[Export ("cacheKeyFilter")]
Func<NSUrl, string> CacheKeyFilter { get; }
[Export ("imageCache")]
SDImageCache ImageCache { get; }
[Export ("imageDownloader")]
SDWebImageDownloader ImageDownloader { get; }
[Export ("downloadWithURL:options:progress:completed:")]
SDWebImageOperation Download (NSUrl url, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressBlock progress, SDWebImageCompletedWithFinishedBlock completed);
#region UIImageView
[Bind ("setImageWithURL:")]
void SetImage ([Target] UIImageView view, NSUrl url);
[Bind ("setImageWithURL:placeholderImage:")]
void SetImage ([Target] UIImageView view, NSUrl url, [NullAllowed] UIImage placeholder);
[Bind ("setImageWithURL:placeholderImage:options:")]
void SetImage ([Target] UIImageView view, NSUrl url, [NullAllowed] UIImage placeholder, SDWebImageOptions options);
[Bind ("setImageWithURL:completed:")]
void SetImage ([Target] UIImageView view, NSUrl url, SDWebImageCompletedBlock completedBlock);
[Bind ("setImageWithURL:placeholderImage:completed:")]
void SetImage ([Target] UIImageView view, NSUrl url, [NullAllowed] UIImage placeholder, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setImageWithURL:placeholderImage:options:completed:")]
void SetImage ([Target] UIImageView view, NSUrl url, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setImageWithURL:placeholderImage:options:progress:completed:")]
void SetImage ([Target] UIImageView view, NSUrl url, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageDownloaderProgressBlock progress, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setAnimationImagesWithURLs:")]
void SetAnimationImages ([Target] UIImageView view, NSUrl[] urls);
[Bind ("cancelCurrentImageLoad")]
void CancelCurrentImageLoad ([Target] UIImageView view);
[Bind ("cancelCurrentArrayLoad")]
void CancelCurrentArrayLoad ([Target] UIImageView view);
#endregion
#region UIButton
[Bind ("setImageWithURL:forState:")]
void SetImage ([Target] UIButton view, NSUrl url, UIControlState state);
[Bind ("setImageWithURL:forState:placeholderImage:")]
void SetImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder);
[Bind ("setImageWithURL:forState:placeholderImage:options:")]
void SetImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options);
[Bind ("setImageWithURL:forState:completed:")]
void SetImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setImageWithURL:forState:placeholderImage:completed:")]
void SetImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setImageWithURL:forState:placeholderImage:options:completed:")]
void SetImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setBackgroundImageWithURL:forState:")]
void SetBackgroundImage ([Target] UIButton view, NSUrl url, UIControlState state);
[Bind ("setBackgroundImageWithURL:forState:placeholderImage:")]
void SetBackgroundImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder);
[Bind ("setBackgroundImageWithURL:forState:placeholderImage:options:")]
void SetBackgroundImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options);
[Bind ("setBackgroundImageWithURL:forState:completed:")]
void SetBackgroundImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setBackgroundImageWithURL:forState:placeholderImage:completed:")]
void SetBackgroundImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("setBackgroundImageWithURL:forState:placeholderImage:options:completed:")]
void SetBackgroundImage ([Target] UIButton view, NSUrl url, UIControlState state, [NullAllowed] UIImage placeholder, SDWebImageOptions options, [NullAllowed] SDWebImageCompletedBlock completedBlock);
[Bind ("cancelCurrentImageLoad")]
void CancelCurrentImageLoad ([Target] UIButton view);
#endregion
}
[BaseType (typeof (NSObject))]
interface SDImageCache
{
[Static, Export ("sharedImageCache")]
SDImageCache SharedImageCache { get; }
[Export ("maxCacheAge", ArgumentSemantic.Assign)]
int MaxCacheAge { get; set; }
[Export ("maxCacheSize", ArgumentSemantic.Assign)]
ulong MaxCacheSize { get; set; }
[Export ("initWithNamespace:")]
IntPtr Constructor (string ns);
[Export ("addReadOnlyCachePath:")]
void AddReadOnlyCachePath (string path);
[Export ("storeImage:forKey:")]
void StoreImage (UIImage image, string key);
[Export ("storeImage:forKey:toDisk:")]
void StoreImage (UIImage image, string key, bool toDisk);
[Export ("storeImage:imageData:forKey:toDisk:")]
void StoreImage (UIImage image, NSData data, string key, bool toDisk);
[Export ("queryDiskCacheForKey:done:")]
void QueryDiskCache (string key, Action<UIImage, SDImageCacheType> done);
[Export ("imageFromMemoryCacheForKey:")]
UIImage ImageFromMemoryCache (string key);
[Export ("imageFromDiskCacheForKey:")]
UIImage ImageFromDiskCache (string key);
[Export ("removeImageForKey:")]
void RemoveImage (string key);
[Export ("removeImageForKey:fromDisk:")]
void RemoveImage (string key, bool fromDisk);
[Export ("clearMemory")]
void ClearMemory ();
[Export ("clearDisk")]
void ClearDisk ();
[Export ("cleanDisk")]
void CleanDisk ();
[Export ("getSize")]
ulong GetSize ();
[Export ("getDiskCount")]
int GetDiskCount ();
[Export ("calculateSizeWithCompletionBlock:")]
void CalculateSize (CalculateSizeCompletionBlock completionBlock);
[Export ("diskImageExistsWithKey:")]
bool DiskImageExists (string key);
[Export ("setValue:forKey:")]
void SetValueForKey ([NullAllowed] NSObject value, NSString key);
#region private methods
[Export ("defaultCachePathForKey:"), Advice ("This is a private method so be careful!")]
string GetDefaultCachePath (string key);
#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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Dynamic.Utils;
namespace System.Linq.Expressions.Interpreter
{
internal sealed class InterpretedFrame
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
[ThreadStatic]
public static InterpretedFrame CurrentFrame;
internal readonly Interpreter Interpreter;
internal InterpretedFrame _parent;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
private int[] _continuations;
private int _continuationIndex;
private int _pendingContinuation;
private object _pendingValue;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public readonly object[] Data;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")]
public readonly IStrongBox[] Closure;
public int StackIndex;
public int InstructionIndex;
#if FEATURE_THREAD_ABORT
// When a ThreadAbortException is raised from interpreted code this is the first frame that caught it.
// No handlers within this handler re-abort the current thread when left.
public ExceptionHandler CurrentAbortHandler;
#endif
internal InterpretedFrame(Interpreter interpreter, IStrongBox[] closure)
{
Interpreter = interpreter;
StackIndex = interpreter.LocalCount;
Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth];
int c = interpreter.Instructions.MaxContinuationDepth;
if (c > 0)
{
_continuations = new int[c];
}
Closure = closure;
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
}
public DebugInfo GetDebugInfo(int instructionIndex)
{
return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex);
}
public string Name
{
get { return Interpreter._name; }
}
#region Data Stack Operations
public void Push(object value)
{
Data[StackIndex++] = value;
}
public void Push(bool value)
{
Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False;
}
public void Push(int value)
{
Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value);
}
public void Push(byte value)
{
Data[StackIndex++] = value;
}
public void Push(sbyte value)
{
Data[StackIndex++] = value;
}
public void Push(Int16 value)
{
Data[StackIndex++] = value;
}
public void Push(UInt16 value)
{
Data[StackIndex++] = value;
}
public object Pop()
{
return Data[--StackIndex];
}
internal void SetStackDepth(int depth)
{
StackIndex = Interpreter.LocalCount + depth;
}
public object Peek()
{
return Data[StackIndex - 1];
}
public void Dup()
{
int i = StackIndex;
Data[i] = Data[i - 1];
StackIndex = i + 1;
}
#endregion
#region Stack Trace
public InterpretedFrame Parent
{
get { return _parent; }
}
public static bool IsInterpretedFrame(MethodBase method)
{
//ContractUtils.RequiresNotNull(method, "method");
return method.DeclaringType == typeof(Interpreter) && method.Name == "Run";
}
public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo()
{
var frame = this;
do
{
yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex));
frame = frame.Parent;
} while (frame != null);
}
internal void SaveTraceToException(Exception exception)
{
if (exception.Data[typeof(InterpretedFrameInfo)] == null)
{
exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray();
}
}
public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception)
{
return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[];
}
#if DEBUG
internal string[] Trace
{
get
{
var trace = new List<string>();
var frame = this;
do
{
trace.Add(frame.Name);
frame = frame.Parent;
} while (frame != null);
return trace.ToArray();
}
}
#endif
internal InterpretedFrame Enter()
{
var currentFrame = CurrentFrame;
CurrentFrame = this;
return _parent = currentFrame;
}
internal void Leave(InterpretedFrame prevFrame)
{
CurrentFrame = prevFrame;
}
#endregion
#region Continuations
internal bool IsJumpHappened()
{
return _pendingContinuation >= 0;
}
public void RemoveContinuation()
{
_continuationIndex--;
}
public void PushContinuation(int continuation)
{
_continuations[_continuationIndex++] = continuation;
}
public int YieldToCurrentContinuation()
{
var target = Interpreter._labels[_continuations[_continuationIndex - 1]];
SetStackDepth(target.StackDepth);
return target.Index - InstructionIndex;
}
/// <summary>
/// Get called from the LeaveFinallyInstruction
/// </summary>
public int YieldToPendingContinuation()
{
Debug.Assert(_pendingContinuation >= 0);
RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation];
// the current continuation might have higher priority (continuationIndex is the depth of the current continuation):
if (pendingTarget.ContinuationStackDepth < _continuationIndex)
{
RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]];
SetStackDepth(currentTarget.StackDepth);
return currentTarget.Index - InstructionIndex;
}
SetStackDepth(pendingTarget.StackDepth);
if (_pendingValue != Interpreter.NoValue)
{
Data[StackIndex - 1] = _pendingValue;
}
// Set the _pendingContinuation and _pendingValue to the default values if we finally gets to the Goto target
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
return pendingTarget.Index - InstructionIndex;
}
internal void PushPendingContinuation()
{
Push(_pendingContinuation);
Push(_pendingValue);
_pendingContinuation = -1;
_pendingValue = Interpreter.NoValue;
}
internal void PopPendingContinuation()
{
_pendingValue = Pop();
_pendingContinuation = (int)Pop();
}
public int Goto(int labelIndex, object value, bool gotoExceptionHandler)
{
// TODO: we know this at compile time (except for compiled loop):
RuntimeLabel target = Interpreter._labels[labelIndex];
Debug.Assert(!gotoExceptionHandler || (gotoExceptionHandler && _continuationIndex == target.ContinuationStackDepth),
"When it's time to jump to the exception handler, all previous finally blocks should already be processed");
if (_continuationIndex == target.ContinuationStackDepth)
{
SetStackDepth(target.StackDepth);
if (value != Interpreter.NoValue)
{
Data[StackIndex - 1] = value;
}
return target.Index - InstructionIndex;
}
// if we are in the middle of executing jump we forget the previous target and replace it by a new one:
_pendingContinuation = labelIndex;
_pendingValue = value;
return YieldToCurrentContinuation();
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.